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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .18(raeb    4:-21): # $Id: lonnet.pm,v 1.1172.2.118.2.17 2021/02/10 15:38:15 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.118.  .14(raeb  128:-21):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   129:         my $logentry = {
                    130:                          $id => {
                    131:                                   'exe_uname' => $env{'user.name'},
                    132:                                   'exe_udom'  => $env{'user.domain'},
                    133:                                   'exe_time'  => $now,
1.1172.2.118.  .14(raeb  134:-21):                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   135:                                   'delflag'   => $delflag,
                    136:                                   'logentry'  => $storehash,
                    137:                                   'uname'     => $uname,
                    138:                                   'udom'      => $udom,
                    139:                                 }
                    140:                        };
                    141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       142:     }
                    143: }
1.1       albertel  144: 
1.163     harris41  145: sub logtouch {
                    146:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  147:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  149: 	close $fh;
                    150:     }
                    151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    153: }
                    154: 
1.1       albertel  155: sub logthis {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.1172.2.96  raeburn   160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    162: 	print $fh $logstring;
1.448     albertel  163: 	close($fh);
                    164:     }
1.1       albertel  165:     return 1;
                    166: }
                    167: 
                    168: sub logperm {
                    169:     my $message=shift;
                    170:     my $execdir=$perlvar{'lonDaemons'};
                    171:     my $now=time;
                    172:     my $local=localtime($now);
1.1172.2.96  raeburn   173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  174: 	print $fh "$now:$message:$local\n";
                    175: 	close($fh);
                    176:     }
1.1       albertel  177:     return 1;
                    178: }
                    179: 
1.850     albertel  180: sub create_connection {
1.853     albertel  181:     my ($hostname,$lonid) = @_;
1.851     albertel  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  183: 				     Type    => SOCK_STREAM,
                    184: 				     Timeout => 10);
                    185:     return 0 if (!$client);
1.890     albertel  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  187:     my $result = <$client>;
                    188:     chomp($result);
                    189:     return 1 if ($result eq 'done');
                    190:     return 0;
                    191: }
                    192: 
1.983     raeburn   193: sub get_server_timezone {
                    194:     my ($cnum,$cdom) = @_;
                    195:     my $home=&homeserver($cnum,$cdom);
                    196:     if ($home ne 'no_host') {
                    197:         my $cachetime = 24*3600;
                    198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    199:         if (defined($cached)) {
                    200:             return $timezone;
                    201:         } else {
                    202:             my $timezone = &reply('servertimezone',$home);
                    203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    204:         }
                    205:     }
                    206: }
1.850     albertel  207: 
1.1106    raeburn   208: sub get_server_distarch {
                    209:     my ($lonhost,$ignore_cache) = @_;
                    210:     if (defined($lonhost)) {
                    211:         if (!defined(&hostname($lonhost))) {
                    212:             return;
                    213:         }
                    214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $distarch;
                    219:             }
                    220:         }
                    221:         my $rep = &reply('serverdistarch',$lonhost);
                    222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    224:                 $rep eq '') {
                    225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    226:         }
                    227:     }
                    228:     return;
                    229: }
                    230: 
1.993     raeburn   231: sub get_server_loncaparev {
1.1073    raeburn   232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   233:     if (defined($lonhost)) {
                    234:         if (!defined(&hostname($lonhost))) {
                    235:             undef($lonhost);
                    236:         }
                    237:     }
                    238:     if (!defined($lonhost)) {
                    239:         if (defined(&domain($dom,'primary'))) {
                    240:             $lonhost=&domain($dom,'primary');
                    241:             if ($lonhost eq 'no_host') {
                    242:                 undef($lonhost);
                    243:             }
                    244:         }
                    245:     }
                    246:     if (defined($lonhost)) {
1.1073    raeburn   247:         my $cachetime = 12*3600;
                    248:         if (!$ignore_cache) {
                    249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    250:             if (defined($cached)) {
                    251:                 return $loncaparev;
                    252:             }
                    253:         }
                    254:         my ($answer,$loncaparev);
                    255:         my @ids=&current_machine_ids();
                    256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    257:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   259:                 $loncaparev = $1;
                    260:             }
                    261:         } else {
                    262:             $answer = &reply('serverloncaparev',$lonhost);
                    263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    264:                 if ($caller eq 'loncron') {
                    265:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   266:                     $ua->timeout(4);
1.1172.2.118.  .3(raebu  267:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  270:20):                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1172.2.35  raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364: }
                    365: 
1.1       albertel  366: # -------------------------------------------------- Non-critical communication
                    367: sub subreply {
                    368:     my ($cmd,$server)=@_;
1.838     albertel  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      370:     #
                    371:     #  With loncnew process trimming, there's a timing hole between lonc server
                    372:     #  process exit and the master server picking up the listen on the AF_UNIX
                    373:     #  socket.  In that time interval, a lock file will exist:
                    374: 
                    375:     my $lockfile=$peerfile.".lock";
                    376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   377: 	sleep(0.1);
1.549     foxr      378:     }
                    379:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      380:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      381:     #
1.550     foxr      382:     #   We'll give the connection a few tries before abandoning it.  If
                    383:     #   connection is not possible, we'll con_lost back to the client.
                    384:     #   
                    385:     my $client;
                    386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    388: 				      Type    => SOCK_STREAM,
                    389: 				      Timeout => 10);
1.869     albertel  390: 	if ($client) {
1.550     foxr      391: 	    last;		# Connected!
1.850     albertel  392: 	} else {
1.853     albertel  393: 	    &create_connection(&hostname($server),$server);
1.550     foxr      394: 	}
1.1172.2.79  raeburn   395:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      396:     }
                    397:     my $answer;
                    398:     if ($client) {
1.704     albertel  399: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      400: 	$answer=<$client>;
                    401: 	if (!$answer) { $answer="con_lost"; }
                    402: 	chomp($answer);
                    403:     } else {
                    404: 	$answer = 'con_lost';	# Failed connection.
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: sub reply {
                    410:     my ($cmd,$server)=@_;
1.838     albertel  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  412:     my $answer=subreply($cmd,$server);
1.65      www       413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   414:         my $logged = $cmd;
                    415:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    416:             my $subcmd = $1;
                    417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    420:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    422:                     splice(@rest,2,1,'Hidden');
                    423:                 } elsif ($subcmd eq 'passwd') {
                    424:                     splice(@rest,2,2,('Hidden','Hidden'));
                    425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    426:                          ($subcmd eq 'autoexportgrades')) {
                    427:                     splice(@rest,3,1,'Hidden');
                    428:                 }
                    429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    430:             }
                    431:         }
                    432:         &logthis("<font color=\"blue\">WARNING:".
                    433:                  " $logged to $server returned $answer</font>");
1.12      www       434:     }
1.1       albertel  435:     return $answer;
                    436: }
                    437: 
                    438: # ----------------------------------------------------------- Send USR1 to lonc
                    439: 
                    440: sub reconlonc {
1.891     albertel  441:     my ($lonid) = @_;
                    442:     if ($lonid) {
1.1172.2.72  raeburn   443:         my $hostname = &hostname($lonid);
1.891     albertel  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    445: 	if ($hostname && -e $peerfile) {
                    446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    448: 					     Type    => SOCK_STREAM,
                    449: 					     Timeout => 10);
                    450: 	    if ($client) {
                    451: 		print $client ("reset_retries\n");
                    452: 		my $answer=<$client>;
                    453: 		#reset just this one.
                    454: 	    }
                    455: 	}
                    456: 	return;
                    457:     }
                    458: 
1.836     www       459:     &logthis("Trying to reconnect lonc");
1.1       albertel  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   461:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  462: 	my $loncpid=<$fh>;
                    463:         chomp($loncpid);
                    464:         if (kill 0 => $loncpid) {
                    465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    466:             kill USR1 => $loncpid;
                    467:             sleep 1;
1.836     www       468:          } else {
1.12      www       469: 	    &logthis(
1.672     albertel  470:                "<font color=\"blue\">WARNING:".
1.12      www       471:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  472:         }
                    473:     } else {
1.836     www       474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  475:     }
                    476: }
                    477: 
                    478: # ------------------------------------------------------ Critical communication
1.12      www       479: 
1.1       albertel  480: sub critical {
                    481:     my ($cmd,$server)=@_;
1.838     albertel  482:     unless (&hostname($server)) {
1.672     albertel  483:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       484:                " Critical message to unknown server ($server)</font>");
                    485:         return 'no_such_host';
                    486:     }
1.1       albertel  487:     my $answer=reply($cmd,$server);
                    488:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   489: 	&reconlonc($server);
1.589     albertel  490: 	my $answer=reply($cmd,$server);
1.1       albertel  491:         if ($answer eq 'con_lost') {
                    492:             my $now=time;
                    493:             my $middlename=$cmd;
1.5       www       494:             $middlename=substr($middlename,0,16);
1.1       albertel  495:             $middlename=~s/\W//g;
                    496:             my $dfilename=
1.305     www       497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    498:             $dumpcount++;
1.1       albertel  499:             {
1.448     albertel  500: 		my $dfh;
1.1172.2.96  raeburn   501: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  502: 		    print $dfh "$cmd\n"; 
                    503: 		    close($dfh);
                    504: 		}
1.1       albertel  505:             }
1.1172.2.79  raeburn   506:             sleep 1;
1.1       albertel  507:             my $wcmd='';
                    508:             {
1.448     albertel  509: 		my $dfh;
1.1172.2.96  raeburn   510: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  511: 		    $wcmd=<$dfh>; 
                    512: 		    close($dfh);
                    513: 		}
1.1       albertel  514:             }
                    515:             chomp($wcmd);
1.7       www       516:             if ($wcmd eq $cmd) {
1.672     albertel  517: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       518:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  519:                 &logperm("D:$server:$cmd");
                    520: 	        return 'con_delayed';
                    521:             } else {
1.672     albertel  522:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       523:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  524:                 &logperm("F:$server:$cmd");
                    525:                 return 'con_failed';
                    526:             }
                    527:         }
                    528:     }
                    529:     return $answer;
1.405     albertel  530: }
                    531: 
1.755     albertel  532: # ------------------------------------------- check if return value is an error
                    533: 
                    534: sub error {
                    535:     my ($result) = @_;
1.756     albertel  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  537: 	if ($2 == 2) { return undef; }
                    538: 	return $1;
                    539:     }
                    540:     return undef;
                    541: }
                    542: 
1.783     albertel  543: sub convert_and_load_session_env {
                    544:     my ($lonidsdir,$handle)=@_;
                    545:     my @profile;
                    546:     {
1.917     albertel  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    548: 	if (!$opened) {
1.915     albertel  549: 	    return 0;
                    550: 	}
1.783     albertel  551: 	flock($idf,LOCK_SH);
                    552: 	@profile=<$idf>;
                    553: 	close($idf);
                    554:     }
                    555:     my %temp_env;
                    556:     foreach my $line (@profile) {
1.786     albertel  557: 	if ($line !~ m/=/) {
                    558: 	    return 0;
                    559: 	}
1.783     albertel  560: 	chomp($line);
                    561: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    563:     }
                    564:     unlink("$lonidsdir/$handle.id");
                    565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    566: 	    0640)) {
                    567: 	%disk_env = %temp_env;
                    568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    569: 	untie(%disk_env);
                    570:     }
1.786     albertel  571:     return 1;
1.783     albertel  572: }
                    573: 
1.374     www       574: # ------------------------------------------- Transfer profile into environment
1.780     albertel  575: my $env_loaded;
                    576: sub transfer_profile_to_env {
1.788     albertel  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    578:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       579: 
1.720     albertel  580:     if (!defined($lonidsdir)) {
                    581: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    582:     }
                    583:     if (!defined($handle)) {
                    584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    585:     }
                    586: 
1.786     albertel  587:     my $convert;
                    588:     {
1.917     albertel  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    590: 	if (!$opened) {
1.915     albertel  591: 	    return;
                    592: 	}
1.786     albertel  593: 	flock($idf,LOCK_SH);
                    594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    595: 		&GDBM_READER(),0640)) {
                    596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    597: 	    untie(%disk_env);
                    598: 	} else {
                    599: 	    $convert = 1;
                    600: 	}
                    601:     }
                    602:     if ($convert) {
                    603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    604: 	    &logthis("Failed to load session, or convert session.");
                    605: 	}
1.374     www       606:     }
1.783     albertel  607: 
1.786     albertel  608:     my %remove;
1.783     albertel  609:     while ( my $envname = each(%env) ) {
1.433     matthew   610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    611:             if ($time < time-300) {
1.783     albertel  612:                 $remove{$key}++;
1.433     matthew   613:             }
                    614:         }
                    615:     }
1.783     albertel  616: 
1.619     albertel  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  618:     $env_loaded=1;
1.783     albertel  619:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   620:         &delenv($expired_key);
1.374     www       621:     }
1.1       albertel  622: }
                    623: 
1.916     albertel  624: # ---------------------------------------------------- Check for valid session 
                    625: sub check_for_valid_session {
1.1172.2.96  raeburn   626:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   629:     if ($name eq 'lonDAV') {
                    630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    631:     } else {
                    632:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   633:         if ($name eq '') {
                    634:             $name = 'lonID';
                    635:         }
                    636:     }
                    637:     if ($name eq 'lonID') {
                    638:         $secure = 'lonSID';
                    639:         $linkname = 'lonLinkID';
                    640:         $pubname = 'lonPubID';
                    641:         if (exists($cookies{$secure})) {
                    642:             $lonid=$cookies{$secure};
                    643:         } elsif (exists($cookies{$name})) {
                    644:             $lonid=$cookies{$name};
                    645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    646:             $lonid=$cookies{$linkname};
                    647:         } elsif (exists($cookies{$pubname})) {
                    648:             $lonid=$cookies{$pubname};
                    649:         }
                    650:     } else {
                    651:         $lonid=$cookies{$name};
                    652:     }
                    653:     return undef if (!$lonid);
                    654: 
                    655:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    656:     if (-l "$lonidsdir/$handle.id") {
                    657:         my $link = readlink("$lonidsdir/$handle.id");
                    658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    659:             $handle = $1;
                    660:         }
1.1155    raeburn   661:     }
1.1172.2.96  raeburn   662:     if (!-e "$lonidsdir/$handle.id") {
                    663:         if ((ref($domref)) && ($name eq 'lonID') &&
                    664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    667:                 $$domref = $possudom;
                    668:             }
                    669:         }
                    670:         return undef;
                    671:     }
1.916     albertel  672: 
1.917     albertel  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    674:     return undef if (!$opened);
1.916     albertel  675: 
                    676:     flock($idf,LOCK_SH);
                    677:     my %disk_env;
                    678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    679: 	    &GDBM_READER(),0640)) {
                    680: 	return undef;	
                    681:     }
                    682: 
                    683:     if (!defined($disk_env{'user.name'})
                    684: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   685:         untie(%disk_env);
1.916     albertel  686: 	return undef;
                    687:     }
1.1172.2.18  raeburn   688: 
1.1172.2.36  raeburn   689:     if (ref($userhashref) eq 'HASH') {
                    690:         $userhashref->{'name'} = $disk_env{'user.name'};
                    691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   692:     }
1.1172.2.107  raeburn   693:     untie(%disk_env);
1.1172.2.18  raeburn   694: 
1.916     albertel  695:     return $handle;
                    696: }
                    697: 
1.830     albertel  698: sub timed_flock {
                    699:     my ($file,$lock_type) = @_;
                    700:     my $failed=0;
                    701:     eval {
                    702: 	local $SIG{__DIE__}='DEFAULT';
                    703: 	local $SIG{ALRM}=sub {
                    704: 	    $failed=1;
                    705: 	    die("failed lock");
                    706: 	};
                    707: 	alarm(13);
                    708: 	flock($file,$lock_type);
                    709: 	alarm(0);
                    710:     };
                    711:     if ($failed) {
                    712: 	return undef;
                    713:     } else {
                    714: 	return 1;
                    715:     }
                    716: }
                    717: 
1.1172.2.107  raeburn   718: sub get_sessionfile_vars {
                    719:     my ($handle,$lonidsdir,$storearr) = @_;
                    720:     my %returnhash;
                    721:     unless (ref($storearr) eq 'ARRAY') {
                    722:         return %returnhash;
                    723:     }
                    724:     if (-l "$lonidsdir/$handle.id") {
                    725:         my $link = readlink("$lonidsdir/$handle.id");
                    726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    727:             $handle = $1;
                    728:         }
                    729:     }
                    730:     if ((-e "$lonidsdir/$handle.id") &&
                    731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    735:                 flock($idf,LOCK_SH);
                    736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    737:                         &GDBM_READER(),0640)) {
                    738:                     foreach my $item (@{$storearr}) {
                    739:                         $returnhash{$item} = $disk_env{$item};
                    740:                     }
                    741:                     untie(%disk_env);
                    742:                 }
                    743:             }
                    744:         }
                    745:     }
                    746:     return %returnhash;
                    747: }
                    748: 
1.5       www       749: # ---------------------------------------------------------- Append Environment
                    750: 
                    751: sub appenv {
1.949     raeburn   752:     my ($newenv,$roles) = @_;
                    753:     if (ref($newenv) eq 'HASH') {
                    754:         foreach my $key (keys(%{$newenv})) {
                    755:             my $refused = 0;
                    756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    757:                 $refused = 1;
                    758:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    761:                         $refused = 0;
                    762:                     }
                    763:                 }
                    764:             }
                    765:             if ($refused) {
                    766:                 &logthis("<font color=\"blue\">WARNING: ".
                    767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    768:                          .'</font>');
                    769: 	        delete($newenv->{$key});
                    770:             } else {
                    771:                 $env{$key}=$newenv->{$key};
                    772:             }
                    773:         }
1.1172.2.96  raeburn   774:         my $lonids = $perlvar{'lonIDsDir'};
                    775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    777:             if ($opened
                    778: 	        && &timed_flock($env_file,LOCK_EX)
                    779: 	        &&
                    780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    782: 	        while (my ($key,$value) = each(%{$newenv})) {
                    783: 	            $disk_env{$key} = $value;
                    784: 	        }
                    785: 	        untie(%disk_env);
                    786:             }
1.35      www       787:         }
1.191     harris41  788:     }
1.56      www       789:     return 'ok';
                    790: }
                    791: # ----------------------------------------------------- Delete from Environment
                    792: 
                    793: sub delenv {
1.1104    raeburn   794:     my ($delthis,$regexp,$roles) = @_;
                    795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    796:         my $refused = 1;
                    797:         if (ref($roles) eq 'ARRAY') {
                    798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    799:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    800:                 $refused = 0;
                    801:             }
                    802:         }
                    803:         if ($refused) {
                    804:             &logthis("<font color=\"blue\">WARNING: ".
                    805:                      "Attempt to delete from environment ".$delthis);
                    806:             return 'error';
                    807:         }
1.56      www       808:     }
1.917     albertel  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    810:     if ($opened
1.915     albertel  811: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  812: 	&&
                    813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  815: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   816: 	    if ($regexp) {
                    817:                 if ($key=~/^$delthis/) {
                    818:                     delete($env{$key});
                    819:                     delete($disk_env{$key});
                    820:                 } 
                    821:             } else {
                    822:                 if ($key=~/^\Q$delthis\E/) {
                    823: 		    delete($env{$key});
                    824: 		    delete($disk_env{$key});
                    825: 	        }
                    826:             }
1.448     albertel  827: 	}
1.783     albertel  828: 	untie(%disk_env);
1.5       www       829:     }
                    830:     return 'ok';
1.369     albertel  831: }
                    832: 
1.790     albertel  833: sub get_env_multiple {
                    834:     my ($name) = @_;
                    835:     my @values;
                    836:     if (defined($env{$name})) {
                    837:         # exists is it an array
                    838:         if (ref($env{$name})) {
                    839:             @values=@{ $env{$name} };
                    840:         } else {
                    841:             $values[0]=$env{$name};
                    842:         }
                    843:     }
                    844:     return(@values);
                    845: }
                    846: 
1.958     www       847: # ------------------------------------------------------------------- Locking
                    848: 
                    849: sub set_lock {
                    850:     my ($text)=@_;
                    851:     $locknum++;
                    852:     my $id=$$.'-'.$locknum;
                    853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    854:              'session.lock.'.$id => $text});
                    855:     return $id;
                    856: }
                    857: 
                    858: sub get_locks {
                    859:     my $num=0;
                    860:     my %texts=();
                    861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    862:        if ($lock=~/\w/) {
                    863:           $num++;
                    864:           $texts{$lock}=$env{'session.lock.'.$lock};
                    865:        }
                    866:    }
                    867:    return ($num,%texts);
                    868: }
                    869: 
                    870: sub remove_lock {
                    871:     my ($id)=@_;
                    872:     my $newlocks='';
                    873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    874:        if (($lock=~/\w/) && ($lock ne $id)) {
                    875:           $newlocks.=','.$lock;
                    876:        }
                    877:     }
                    878:     &appenv({'session.locks' => $newlocks});
                    879:     &delenv('session.lock.'.$id);
                    880: }
                    881: 
                    882: sub remove_all_locks {
                    883:     my $activelocks=$env{'session.locks'};
                    884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    885:        if ($lock=~/\w/) {
                    886:           &remove_lock($lock);
                    887:        }
                    888:     }
                    889: }
                    890: 
                    891: 
1.369     albertel  892: # ------------------------------------------ Find out current server userload
                    893: sub userload {
                    894:     my $numusers=0;
                    895:     {
                    896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    897: 	my $filename;
                    898: 	my $curtime=time;
                    899: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  900: 	    next if ($filename eq '.' || $filename eq '..');
                    901: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.1001    raeburn   958:         if (defined($spare_server)) {
                    959:             my $hostname = &hostname($spare_server);
1.1083    raeburn   960:             if (defined($hostname)) {
1.1172.2.118.  .3(raebu  961:20):                 my $protocol = 'http';
                    962:20):                 if ($protocol{$spare_server} eq 'https') {
                    963:20):                     $protocol = $protocol{$spare_server};
                    964:20):                 }
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1172.2.41  raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
1.1172.2.107  raeburn  1031: # check if user's browser sent load balancer cookie and server still has session
                   1032: # and is not overloaded.
                   1033: sub check_for_balancer_cookie {
                   1034:     my ($r,$update_mtime) = @_;
                   1035:     my ($otherserver,$cookie);
                   1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1037:     if (exists($cookies{'balanceID'})) {
                   1038:         my $balid = $cookies{'balanceID'};
                   1039:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1040:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1043:                 my ($possudom,$possuname) = ($1,$2);
                   1044:                 my $has_session = 0;
                   1045:                 if ((&domain($possudom) ne '') &&
                   1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1047:                     my $try_server;
                   1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1049:                     if ($opened) {
                   1050:                         flock($idf,LOCK_SH);
                   1051:                         while (my $line = <$idf>) {
                   1052:                             chomp($line);
                   1053:                             if (&hostname($line) ne '') {
                   1054:                                 $try_server = $line;
                   1055:                                 last;
                   1056:                             }
                   1057:                         }
                   1058:                         close($idf);
                   1059:                         if (($try_server) &&
                   1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1061:                             my $lowest_load = 30000;
                   1062:                             ($otherserver,$lowest_load) =
                   1063:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1064:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1065:                                 $has_session = 1;
                   1066:                             } else {
                   1067:                                 undef($otherserver);
                   1068:                             }
                   1069:                         }
                   1070:                     }
                   1071:                 }
                   1072:                 if ($has_session) {
                   1073:                     if ($update_mtime) {
                   1074:                         my $atime = my $mtime = time;
                   1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1076:                     }
                   1077:                 } else {
                   1078:                     unlink("$balancedir/$cookie.id");
                   1079:                 }
                   1080:             }
                   1081:         }
                   1082:     }
                   1083:     return ($otherserver,$cookie);
                   1084: }
                   1085: 
1.1172.2.118.  .11(raeb 1086:-20): sub updatebalcookie {
                   1087:-20):     my ($cookie,$balancer,$lastentry)=@_;
                   1088:-20):     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1089:-20):         my ($udom,$uname) = ($1,$2);
                   1090:-20):         my $uprimary_id = &domain($udom,'primary');
                   1091:-20):         my $uintdom = &internet_dom($uprimary_id);
                   1092:-20):         my $intdom = &internet_dom($balancer);
                   1093:-20):         my $serverhomedom = &host_domain($balancer);
                   1094:-20):         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1095:-20):             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1096:-20):         }
                   1097:-20):     }
                   1098:-20):     return;
                   1099:-20): }
                   1100:-20): 
1.1172.2.107  raeburn  1101: sub delbalcookie {
                   1102:     my ($cookie,$balancer) =@_;
                   1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1104:         my ($udom,$uname) = ($1,$2);
                   1105:         my $uprimary_id = &domain($udom,'primary');
                   1106:         my $uintdom = &internet_dom($uprimary_id);
                   1107:         my $intdom = &internet_dom($balancer);
                   1108:         my $serverhomedom = &host_domain($balancer);
                   1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.118.  .11(raeb 1110:-20):             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1111:         }
                   1112:     }
                   1113: }
                   1114: 
1.914     albertel 1115: # -------------------------------- ask if server already has a session for user
                   1116: sub has_user_session {
                   1117:     my ($lonid,$udom,$uname) = @_;
                   1118:     my $result = &reply(join(':','userhassession',
                   1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1120:     return 1 if ($result eq 'ok');
                   1121: 
                   1122:     return 0;
                   1123: }
                   1124: 
1.1076    raeburn  1125: # --------- determine least loaded server in a user's domain which allows login
                   1126: 
                   1127: sub choose_server {
1.1172.2.47  raeburn  1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1130:     my %servers = &get_servers($udom);
1.1076    raeburn  1131:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1133:     if ($skiploadbal) {
                   1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1135:         unless (defined($cached)) {
                   1136:             my $cachetime = 60*60*24;
                   1137:             my %domconfig =
                   1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1141:                                            $cachetime);
                   1142:             }
                   1143:         }
                   1144:     }
1.1076    raeburn  1145:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1146:         my $loginvia;
1.1172.2.47  raeburn  1147:         if ($skiploadbal) {
                   1148:             if (ref($balancers) eq 'HASH') {
                   1149:                 next if (exists($balancers->{$lonhost}));
                   1150:             }
                   1151:         }
1.1115    raeburn  1152:         if ($checkloginvia) {
                   1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1154:             if ($loginvia) {
                   1155:                 my ($server,$path) = split(/:/,$loginvia);
                   1156:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1158:                 if ($login_host eq $server) {
                   1159:                     $portal_path = $path;
1.1151    raeburn  1160:                     $isredirect = 1;
1.1116    raeburn  1161:                 }
                   1162:             } else {
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $lonhost) {
                   1166:                     $portal_path = '';
1.1151    raeburn  1167:                     $isredirect = ''; 
1.1116    raeburn  1168:                 }
                   1169:             }
                   1170:         } else {
1.1076    raeburn  1171:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1173:         }
                   1174:     }
                   1175:     if ($login_host ne '') {
1.1116    raeburn  1176:         $hostname = &hostname($login_host);
1.1076    raeburn  1177:     }
1.1172.2.88  raeburn  1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1179: }
                   1180: 
1.1172.2.118.  .5(raebu 1181:20): sub get_course_sessions {
                   1182:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1183:20):     my %servers = &internet_dom_servers($cdom);
                   1184:20):     my %returnhash;
                   1185:20):     foreach my $server (sort(keys(%servers))) {
                   1186:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1187:20):         my @pairs=split(/\&/,$rep);
                   1188:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1189:20):             foreach my $item (@pairs) {
                   1190:20):                 my ($key,$value)=split(/=/,$item,2);
                   1191:20):                 $key = &unescape($key);
                   1192:20):                 next if ($key =~ /^error: 2 /);
                   1193:20):                 if (exists($returnhash{$key})) {
                   1194:20):                     next if ($value < $returnhash{$key});
                   1195:20):                 }
                   1196:20):                 $returnhash{$key}=$value;
                   1197:20):             }
                   1198:20):         }
                   1199:20):     }
                   1200:20):     return %returnhash;
                   1201:20): }
                   1202:20): 
1.202     matthew  1203: # --------------------------------------------- Try to change a user's password
                   1204: 
                   1205: sub changepass {
1.799     raeburn  1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1207:     $currentpass = &escape($currentpass);
                   1208:     $newpass     = &escape($newpass);
1.1030    raeburn  1209:     my $lonhost = $perlvar{'lonHostID'};
                   1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1211: 		       $server);
                   1212:     if (! $answer) {
                   1213: 	&logthis("No reply on password change request to $server ".
                   1214: 		 "by $uname in domain $udom.");
                   1215:     } elsif ($answer =~ "^ok") {
                   1216:         &logthis("$uname in $udom successfully changed their password ".
                   1217: 		 "on $server.");
                   1218:     } elsif ($answer =~ "^pwchange_failure") {
                   1219: 	&logthis("$uname in $udom was unable to change their password ".
                   1220: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1221: 		 "or pwchange");
                   1222:     } elsif ($answer =~ "^non_authorized") {
                   1223:         &logthis("$uname in $udom did not get their password correct when ".
                   1224: 		 "attempting to change it on $server.");
                   1225:     } elsif ($answer =~ "^auth_mode_error") {
                   1226:         &logthis("$uname in $udom attempted to change their password despite ".
                   1227: 		 "not being locally or internally authenticated on $server.");
                   1228:     } elsif ($answer =~ "^unknown_user") {
                   1229:         &logthis("$uname in $udom attempted to change their password ".
                   1230: 		 "on $server but were unable to because $server is not ".
                   1231: 		 "their home server.");
                   1232:     } elsif ($answer =~ "^refused") {
                   1233: 	&logthis("$server refused to change $uname in $udom password because ".
                   1234: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1235:     } elsif ($answer =~ "invalid_client") {
                   1236:         &logthis("$server refused to change $uname in $udom password because ".
                   1237:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1238:     } elsif ($answer =~ "^prioruse") {
                   1239:        &logthis("$server refused to change $uname in $udom password because ".
                   1240:                 "the password had been used before");
1.202     matthew  1241:     }
                   1242:     return $answer;
1.1       albertel 1243: }
                   1244: 
1.169     harris41 1245: # ----------------------- Try to determine user's current authentication scheme
                   1246: 
                   1247: sub queryauthenticate {
                   1248:     my ($uname,$udom)=@_;
1.456     albertel 1249:     my $uhome=&homeserver($uname,$udom);
                   1250:     if (!$uhome) {
                   1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1252: 	return 'no_host';
                   1253:     }
                   1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1257:     }
1.456     albertel 1258:     return $answer;
1.169     harris41 1259: }
                   1260: 
1.1       albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1262: 
1.1       albertel 1263: sub authenticate {
1.1073    raeburn  1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1265:     $upass=&escape($upass);
                   1266:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1267:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1268:     my $newhome;
1.836     www      1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1270: # Maybe the machine was offline and only re-appeared again recently?
                   1271:         &reconlonc();
                   1272: # One more
1.952     raeburn  1273: 	$uhome=&homeserver($uname,$udom,1);
                   1274:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1275:             if (defined(&domain($udom,'primary'))) {
                   1276:                 $newhome=&domain($udom,'primary');
                   1277:             }
                   1278:             if ($newhome ne '') {
                   1279:                 $uhome = $newhome;
                   1280:             }
                   1281:         }
1.836     www      1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1284: 	    return 'no_host';
                   1285:         }
1.1       albertel 1286:     }
1.1073    raeburn  1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1288:     if ($answer eq 'authorized') {
1.952     raeburn  1289:         if ($newhome) {
                   1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1291:             return 'no_account_on_host'; 
                   1292:         } else {
                   1293:             &logthis("User $uname at $udom authorized by $uhome");
                   1294:             return $uhome;
                   1295:         }
1.471     albertel 1296:     }
                   1297:     if ($answer eq 'non_authorized') {
                   1298: 	&logthis("User $uname at $udom rejected by $uhome");
                   1299: 	return 'no_host'; 
1.9       www      1300:     }
1.471     albertel 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1302:     return 'no_host';
                   1303: }
                   1304: 
1.1073    raeburn  1305: sub can_host_session {
1.1074    raeburn  1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1307:     my $canhost = 1;
1.1074    raeburn  1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1309:     if (ref($remotesessions) eq 'HASH') {
                   1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1312:                 $canhost = 0;
                   1313:             } else {
                   1314:                 $canhost = 1;
                   1315:             }
                   1316:         }
                   1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 1;
                   1320:             } else {
                   1321:                 $canhost = 0;
                   1322:             }
                   1323:         }
                   1324:         if ($canhost) {
                   1325:             if ($remotesessions->{'version'} ne '') {
                   1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1327:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1329:                         my $major = $1;
                   1330:                         my $minor = $2;
                   1331:                         if (($major < $reqmajor ) ||
                   1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1333:                             $canhost = 0;
                   1334:                         }
                   1335:                     } else {
                   1336:                         $canhost = 0;
                   1337:                     }
                   1338:                 }
                   1339:             }
                   1340:         }
                   1341:     }
                   1342:     if ($canhost) {
                   1343:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1347:                 if (($uint_dom ne '') && 
                   1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1349:                     $canhost = 0;
                   1350:                 } else {
                   1351:                     $canhost = 1;
                   1352:                 }
                   1353:             }
                   1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1355:                 if (($uint_dom ne '') && 
                   1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1357:                     $canhost = 1;
                   1358:                 } else {
                   1359:                     $canhost = 0;
                   1360:                 }
                   1361:             }
                   1362:         }
                   1363:     }
                   1364:     return $canhost;
                   1365: }
                   1366: 
1.1083    raeburn  1367: sub spare_can_host {
                   1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1369:     my $canhost=1;
1.1172.2.62  raeburn  1370:     my $try_server_hostname = &hostname($try_server);
                   1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1372:     my $serverhomedom = &host_domain($serverhomeID);
                   1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1376:             $canhost = 0;
                   1377:         }
                   1378:     }
1.1172.2.118.  .15(raeb 1379:-21):     if ($canhost) {
                   1380:-21):         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1381:-21):             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1382:-21):                 unless (&shared_institution($udom,$try_server)) {
                   1383:-21):                     $canhost = 0;
                   1384:-21):                 }
                   1385:-21):             }
                   1386:-21):         }
                   1387:-21):     }
1.1172.2.62  raeburn  1388:     if (($canhost) && ($uint_dom)) {
                   1389:         my @intdoms;
                   1390:         my $internet_names = &get_internet_names($try_server);
                   1391:         if (ref($internet_names) eq 'ARRAY') {
                   1392:             @intdoms = @{$internet_names};
                   1393:         }
                   1394:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1395:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1396:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1397:                                          $remotesessions,
                   1398:                                          $defdomdefaults{'hostedsessions'});
                   1399:         }
1.1083    raeburn  1400:     }
                   1401:     return $canhost;
                   1402: }
                   1403: 
1.1123    raeburn  1404: sub this_host_spares {
                   1405:     my ($dom) = @_;
1.1126    raeburn  1406:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1407:     my @hosts = &current_machine_ids();
                   1408:     foreach my $lonhost (@hosts) {
                   1409:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1410:             $dom_in_use = $dom;
                   1411:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1412:             last;
                   1413:         }
                   1414:     }
1.1126    raeburn  1415:     if ($dom_in_use ne '') {
                   1416:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1417:     }
                   1418:     if (ref($result) ne 'HASH') {
                   1419:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1420:         $dom_in_use = &host_domain($lonhost_in_use);
                   1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1422:         if (ref($result) ne 'HASH') {
                   1423:             $result = \%spareid;
                   1424:         }
                   1425:     }
                   1426:     return $result;
                   1427: }
                   1428: 
                   1429: sub spares_for_offload  {
                   1430:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1431:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1432:     if (defined($cached)) {
                   1433:         return $result;
                   1434:     } else {
1.1126    raeburn  1435:         my $cachetime = 60*60*24;
                   1436:         my %domconfig =
                   1437:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1438:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1439:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1440:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1441:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1442:                 }
                   1443:             }
                   1444:         }
                   1445:     }
1.1126    raeburn  1446:     return;
1.1123    raeburn  1447: }
                   1448: 
1.1129    raeburn  1449: sub get_lonbalancer_config {
                   1450:     my ($servers) = @_;
                   1451:     my ($currbalancer,$currtargets);
                   1452:     if (ref($servers) eq 'HASH') {
                   1453:         foreach my $server (keys(%{$servers})) {
                   1454:             my %what = (
                   1455:                          spareid => 1,
                   1456:                          perlvar => 1,
                   1457:                        );
                   1458:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1459:             if ($result eq 'ok') {
                   1460:                 if (ref($returnhash) eq 'HASH') {
                   1461:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1462:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1463:                             $currbalancer = $server;
                   1464:                             $currtargets = {};
                   1465:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1466:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1467:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1468:                                 }
                   1469:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1470:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1471:                                 }
                   1472:                             }
                   1473:                             last;
                   1474:                         }
                   1475:                     }
                   1476:                 }
                   1477:             }
                   1478:         }
                   1479:     }
                   1480:     return ($currbalancer,$currtargets);
                   1481: }
                   1482: 
                   1483: sub check_loadbalancing {
1.1172.2.88  raeburn  1484:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1485:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1486:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1487:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1488:     my @hosts = &current_machine_ids();
1.1129    raeburn  1489:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1490:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1491:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1492:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1493:     my $domneedscache; 
1.1129    raeburn  1494:     my $cachetime = 60*60*24;
                   1495: 
                   1496:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1497:         $dom_in_use = $udom;
                   1498:         $homeintdom = 1;
                   1499:     } else {
                   1500:         $dom_in_use = $serverhomedom;
                   1501:     }
                   1502:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1503:     unless (defined($cached)) {
                   1504:         my %domconfig =
                   1505:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1506:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1507:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1508:         } else {
                   1509:             $domneedscache = $dom_in_use;
1.1129    raeburn  1510:         }
                   1511:     }
                   1512:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1513:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1514:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1515:         if ($is_balancer) {
                   1516:             if (ref($currrules) eq 'HASH') {
                   1517:                 if ($homeintdom) {
                   1518:                     if ($uname ne '') {
                   1519:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1520:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1521:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1522:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1523:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1524:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1525:                             }
                   1526:                         }
                   1527:                         if ($rule_in_effect eq '') {
                   1528:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1529:                             if ($userenv{'inststatus'} ne '') {
                   1530:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1531:                                 my ($othertitle,$usertypes,$types) =
                   1532:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1533:                                 if (ref($types) eq 'ARRAY') {
                   1534:                                     foreach my $type (@{$types}) {
                   1535:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1536:                                             if (exists($currrules->{$type})) {
                   1537:                                                 $rule_in_effect = $currrules->{$type};
                   1538:                                             }
                   1539:                                         }
                   1540:                                     }
                   1541:                                 }
                   1542:                             } else {
                   1543:                                 if (exists($currrules->{'default'})) {
                   1544:                                     $rule_in_effect = $currrules->{'default'};
                   1545:                                 }
                   1546:                             }
                   1547:                         }
                   1548:                     } else {
                   1549:                         if (exists($currrules->{'default'})) {
                   1550:                             $rule_in_effect = $currrules->{'default'};
                   1551:                         }
                   1552:                     }
                   1553:                 } else {
                   1554:                     if ($currrules->{'_LC_external'} ne '') {
                   1555:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1556:                     }
                   1557:                 }
                   1558:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1559:                                                        $uname,$udom);
                   1560:             }
                   1561:         }
                   1562:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1563:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1564:         unless (defined($cached)) {
                   1565:             my %domconfig =
                   1566:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1567:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1568:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1569:             } else {
                   1570:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1571:             }
                   1572:         }
                   1573:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1574:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1575:                 &check_balancer_result($result,@hosts);
                   1576:             if ($is_balancer) {
1.1129    raeburn  1577:                 if (ref($currrules) eq 'HASH') {
                   1578:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1579:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1580:                     }
                   1581:                 }
                   1582:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1583:                                                        $uname,$udom);
                   1584:             }
                   1585:         } else {
                   1586:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1587:                 $is_balancer = 1;
                   1588:                 $offloadto = &this_host_spares($dom_in_use);
                   1589:             }
1.1172.2.75  raeburn  1590:             unless (defined($cached)) {
                   1591:                 $domneedscache = $serverhomedom;
                   1592:             }
1.1129    raeburn  1593:         }
                   1594:     } else {
                   1595:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1596:             $is_balancer = 1;
                   1597:             $offloadto = &this_host_spares($dom_in_use);
                   1598:         }
1.1172.2.75  raeburn  1599:         unless (defined($cached)) {
                   1600:             $domneedscache = $serverhomedom;
                   1601:         }
                   1602:     }
                   1603:     if ($domneedscache) {
                   1604:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1605:     }
1.1172.2.118.  .11(raeb 1606:-20):     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1607:         my $lowest_load = 30000;
                   1608:         if (ref($offloadto) eq 'HASH') {
                   1609:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1610:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1611:                     ($otherserver,$lowest_load) =
                   1612:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1613:                 }
1.1129    raeburn  1614:             }
1.1172.2.5  raeburn  1615:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1616: 
1.1172.2.5  raeburn  1617:             if (!$found_server) {
                   1618:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1619:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1620:                         ($otherserver,$lowest_load) =
                   1621:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                     }
                   1623:                 }
                   1624:             }
                   1625:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1626:             if (@{$offloadto} == 1) {
                   1627:                 $otherserver = $offloadto->[0];
                   1628:             } elsif (@{$offloadto} > 1) {
                   1629:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1630:                     ($otherserver,$lowest_load) =
                   1631:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1632:                 }
                   1633:             }
                   1634:         }
1.1172.2.88  raeburn  1635:         unless ($caller eq 'login') {
                   1636:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1637:                 $is_balancer = 0;
                   1638:                 if ($uname ne '' && $udom ne '') {
                   1639:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1640:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1641:                                  'user.loadbalcheck.time' => time});
                   1642:                     }
1.1172.2.5  raeburn  1643:                 }
1.1129    raeburn  1644:             }
                   1645:         }
1.1172.2.118.  .11(raeb 1646:-20):     }
                   1647:-20):     if (($is_balancer) && (!$homeintdom)) {
                   1648:-20):         undef($setcookie);
1.1129    raeburn  1649:     }
1.1172.2.107  raeburn  1650:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1651: }
                   1652: 
1.1172.2.12  raeburn  1653: sub check_balancer_result {
                   1654:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1655:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1656:     if (ref($result) eq 'HASH') {
                   1657:         if ($result->{'lonhost'} ne '') {
                   1658:             my $currbalancer = $result->{'lonhost'};
                   1659:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1660:                 $is_balancer = 1;
                   1661:                 $currtargets = $result->{'targets'};
                   1662:                 $currrules = $result->{'rules'};
                   1663:             }
                   1664:         } else {
                   1665:             foreach my $key (keys(%{$result})) {
                   1666:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1667:                     (ref($result->{$key}) eq 'HASH')) {
                   1668:                     $is_balancer = 1;
                   1669:                     $currrules = $result->{$key}{'rules'};
                   1670:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1671:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1672:                     last;
                   1673:                 }
                   1674:             }
                   1675:         }
                   1676:     }
1.1172.2.107  raeburn  1677:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1678: }
                   1679: 
1.1129    raeburn  1680: sub get_loadbalancer_targets {
                   1681:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1682:     my $offloadto;
1.1172.2.4  raeburn  1683:     if ($rule_in_effect eq 'none') {
                   1684:         return [$perlvar{'lonHostID'}];
                   1685:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1686:         $offloadto = $currtargets;
                   1687:     } else {
                   1688:         if ($rule_in_effect eq 'homeserver') {
                   1689:             my $homeserver = &homeserver($uname,$udom);
                   1690:             if ($homeserver ne 'no_host') {
                   1691:                 $offloadto = [$homeserver];
                   1692:             }
                   1693:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1694:             my %domconfig =
                   1695:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1696:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1697:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1698:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1699:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1700:                     }
                   1701:                 }
                   1702:             } else {
1.1172.2.7  raeburn  1703:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1704:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1705:                 if (&hostname($remotebalancer) ne '') {
                   1706:                     $offloadto = [$remotebalancer];
                   1707:                 }
                   1708:             }
                   1709:         } elsif (&hostname($rule_in_effect) ne '') {
                   1710:             $offloadto = [$rule_in_effect];
                   1711:         }
                   1712:     }
                   1713:     return $offloadto;
                   1714: }
                   1715: 
1.1127    raeburn  1716: sub internet_dom_servers {
                   1717:     my ($dom) = @_;
                   1718:     my (%uniqservers,%servers);
                   1719:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1720:     my @machinedoms = &machine_domains($primaryserver);
                   1721:     foreach my $mdom (@machinedoms) {
                   1722:         my %currservers = %servers;
                   1723:         my %server = &get_servers($mdom);
                   1724:         %servers = (%currservers,%server);
                   1725:     }
                   1726:     my %by_hostname;
                   1727:     foreach my $id (keys(%servers)) {
                   1728:         push(@{$by_hostname{$servers{$id}}},$id);
                   1729:     }
                   1730:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1731:         if (@{$by_hostname{$hostname}} > 1) {
                   1732:             my $match = 0;
                   1733:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1734:                 if (&host_domain($id) eq $dom) {
                   1735:                     $uniqservers{$id} = $hostname;
                   1736:                     $match = 1;
                   1737:                 }
                   1738:             }
                   1739:             unless ($match) {
                   1740:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1741:             }
                   1742:         } else {
                   1743:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1744:         }
                   1745:     }
                   1746:     return %uniqservers;
                   1747: }
                   1748: 
1.1       albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1750: 
1.599     albertel 1751: my %homecache;
1.1       albertel 1752: sub homeserver {
1.230     stredwic 1753:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1754:     my $index="$uname:$udom";
1.426     albertel 1755: 
1.599     albertel 1756:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1757: 
                   1758:     my %servers = &get_servers($udom,'library');
                   1759:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1760:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1761: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1762: 
                   1763: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1764: 	if ($answer eq 'found') {
                   1765: 	    delete($badServerCache{$tryserver}); 
                   1766: 	    return $homecache{$index}=$tryserver;
                   1767: 	} elsif ($answer eq 'no_host') {
                   1768: 	    $badServerCache{$tryserver}=1;
                   1769: 	}
1.1       albertel 1770:     }    
                   1771:     return 'no_host';
1.70      www      1772: }
                   1773: 
                   1774: # ------------------------------------- Find the usernames behind a list of IDs
                   1775: 
                   1776: sub idget {
                   1777:     my ($udom,@ids)=@_;
                   1778:     my %returnhash=();
                   1779:     
1.841     albertel 1780:     my %servers = &get_servers($udom,'library');
                   1781:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1782: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1783: 	$idlist=~tr/A-Z/a-z/; 
                   1784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1785: 	my @answer=();
                   1786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1787: 	    @answer=split(/\&/,$reply);
                   1788: 	}                    ;
                   1789: 	my $i;
                   1790: 	for ($i=0;$i<=$#ids;$i++) {
                   1791: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1792: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1793: 	    } 
                   1794: 	}
                   1795:     } 
1.70      www      1796:     return %returnhash;
                   1797: }
                   1798: 
                   1799: # ------------------------------------- Find the IDs behind a list of usernames
                   1800: 
                   1801: sub idrget {
                   1802:     my ($udom,@unames)=@_;
                   1803:     my %returnhash=();
1.800     albertel 1804:     foreach my $uname (@unames) {
                   1805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1806:     }
1.70      www      1807:     return %returnhash;
                   1808: }
                   1809: 
                   1810: # ------------------------------- Store away a list of names and associated IDs
                   1811: 
                   1812: sub idput {
                   1813:     my ($udom,%ids)=@_;
                   1814:     my %servers=();
1.800     albertel 1815:     foreach my $uname (keys(%ids)) {
                   1816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1817:         my $uhom=&homeserver($uname,$udom);
1.70      www      1818:         if ($uhom ne 'no_host') {
1.800     albertel 1819:             my $id=&escape($ids{$uname});
1.70      www      1820:             $id=~tr/A-Z/a-z/;
1.800     albertel 1821:             my $esc_unam=&escape($uname);
1.70      www      1822: 	    if ($servers{$uhom}) {
1.800     albertel 1823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1824:             } else {
1.800     albertel 1825:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1826:             }
                   1827:         }
1.191     harris41 1828:     }
1.800     albertel 1829:     foreach my $server (keys(%servers)) {
                   1830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1831:     }
1.344     www      1832: }
                   1833: 
1.1172.2.30  raeburn  1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1835: 
                   1836: sub iddel {
                   1837:     my ($udom,$idshashref,$uhome)=@_;
                   1838:     my %result=();
                   1839:     unless (ref($idshashref) eq 'HASH') {
                   1840:         return %result;
                   1841:     }
                   1842:     my %servers=();
                   1843:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1844:         my $uhom;
                   1845:         if ($uhome) {
                   1846:             $uhom = $uhome;
                   1847:         } else {
                   1848:             $uhom=&homeserver($uname,$udom);
                   1849:         }
                   1850:         if ($uhom ne 'no_host') {
                   1851:             if ($servers{$uhom}) {
                   1852:                 $servers{$uhom}.='&'.&escape($id);
                   1853:             } else {
                   1854:                 $servers{$uhom}=&escape($id);
                   1855:             }
                   1856:         }
                   1857:     }
                   1858:     foreach my $server (keys(%servers)) {
                   1859:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1860:     }
                   1861:     return %result;
                   1862: }
                   1863: 
1.1023    raeburn  1864: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1865: sub dump_dom {
1.1165    droeschl 1866:     my ($namespace, $udom, $regexp) = @_;
                   1867: 
                   1868:     $udom ||= $env{'user.domain'};
                   1869: 
                   1870:     return () unless $udom;
                   1871: 
                   1872:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1873: }
                   1874: 
1.1023    raeburn  1875: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1876: 
                   1877: sub get_dom {
1.860     raeburn  1878:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1879:     return if ($udom eq 'public');
1.806     raeburn  1880:     my $items='';
                   1881:     foreach my $item (@$storearr) {
                   1882:         $items.=&escape($item).'&';
                   1883:     }
                   1884:     $items=~s/\&$//;
1.860     raeburn  1885:     if (!$udom) {
                   1886:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1887:         return if ($udom eq 'public');
1.860     raeburn  1888:         if (defined(&domain($udom,'primary'))) {
                   1889:             $uhome=&domain($udom,'primary');
                   1890:         } else {
1.874     albertel 1891:             undef($uhome);
1.860     raeburn  1892:         }
                   1893:     } else {
                   1894:         if (!$uhome) {
                   1895:             if (defined(&domain($udom,'primary'))) {
                   1896:                 $uhome=&domain($udom,'primary');
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1901:20):         my $rep;
          .18(raeb 1902:-21):         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   1903:-21):             # domain information is hosted on this machine
                   1904:-21):             my $cmd = 'getdom';
                   1905:-21):             if ($namespace =~ /^enc/) {
                   1906:-21):                 $cmd = 'egetdom';
                   1907:-21):             }
                   1908:-21):             $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
          .1(raebu 1909:20):         } else {
          .18(raeb 1910:-21):             if ($namespace =~ /^enc/) {
                   1911:-21):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1912:-21):             } else {
                   1913:-21):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1914:-21):             }
          .1(raebu 1915:20):         }
1.866     raeburn  1916:         my %returnhash;
1.875     albertel 1917:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1918:             return %returnhash;
                   1919:         }
1.806     raeburn  1920:         my @pairs=split(/\&/,$rep);
                   1921:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1922:             return @pairs;
                   1923:         }
                   1924:         my $i=0;
                   1925:         foreach my $item (@$storearr) {
                   1926:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1927:             $i++;
                   1928:         }
                   1929:         return %returnhash;
                   1930:     } else {
1.880     banghart 1931:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1932:     }
                   1933: }
                   1934: 
                   1935: # -------------------------------------------- put items in domain db files 
                   1936: 
                   1937: sub put_dom {
1.860     raeburn  1938:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1939:     if (!$udom) {
                   1940:         $udom=$env{'user.domain'};
                   1941:         if (defined(&domain($udom,'primary'))) {
                   1942:             $uhome=&domain($udom,'primary');
                   1943:         } else {
1.874     albertel 1944:             undef($uhome);
1.860     raeburn  1945:         }
                   1946:     } else {
                   1947:         if (!$uhome) {
                   1948:             if (defined(&domain($udom,'primary'))) {
                   1949:                 $uhome=&domain($udom,'primary');
                   1950:             }
                   1951:         }
                   1952:     } 
                   1953:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1954:         my $items='';
                   1955:         foreach my $item (keys(%$storehash)) {
                   1956:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1957:         }
                   1958:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1959:20):         if ($namespace =~ /^enc/) {
                   1960:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1961:20):         } else {
                   1962:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1963:20):         }
1.806     raeburn  1964:     } else {
1.860     raeburn  1965:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1966:     }
                   1967: }
                   1968: 
1.1023    raeburn  1969: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1970: sub newput_dom {
1.1023    raeburn  1971:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1972:     my $result;
                   1973:     if (!$udom) {
                   1974:         $udom=$env{'user.domain'};
                   1975:     }
1.1023    raeburn  1976:     if ($udom) {
                   1977:         my $uname = &get_domainconfiguser($udom);
                   1978:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1979:     }
                   1980:     return $result;
                   1981: }
                   1982: 
1.1023    raeburn  1983: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1984: sub del_dom {
1.1023    raeburn  1985:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1986:     if (ref($storearr) eq 'ARRAY') {
                   1987:         if (!$udom) {
                   1988:             $udom=$env{'user.domain'};
                   1989:         }
1.1023    raeburn  1990:         if ($udom) {
                   1991:             my $uname = &get_domainconfiguser($udom); 
                   1992:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1993:         }
                   1994:     }
                   1995: }
                   1996: 
1.1023    raeburn  1997: # ----------------------------------construct domainconfig user for a domain 
                   1998: sub get_domainconfiguser {
                   1999:     my ($udom) = @_;
                   2000:     return $udom.'-domainconfig';
                   2001: }
                   2002: 
1.837     raeburn  2003: sub retrieve_inst_usertypes {
                   2004:     my ($udom) = @_;
                   2005:     my (%returnhash,@order);
1.989     raeburn  2006:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2007:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2008:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2009:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2010:     } else {
                   2011:         if (defined(&domain($udom,'primary'))) {
                   2012:             my $uhome=&domain($udom,'primary');
                   2013:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2014:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2015:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2016:                 return (\%returnhash,\@order);
                   2017:             }
                   2018:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2019:             my @pairs=split(/\&/,$hashitems);
                   2020:             foreach my $item (@pairs) {
                   2021:                 my ($key,$value)=split(/=/,$item,2);
                   2022:                 $key = &unescape($key);
                   2023:                 next if ($key =~ /^error: 2 /);
                   2024:                 $returnhash{$key}=&thaw_unescape($value);
                   2025:             }
                   2026:             my @esc_order = split(/\&/,$orderitems);
                   2027:             foreach my $item (@esc_order) {
                   2028:                 push(@order,&unescape($item));
                   2029:             }
                   2030:         } else {
1.1172.2.44  raeburn  2031:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2032:         }
1.1172.2.44  raeburn  2033:         return (\%returnhash,\@order);
1.837     raeburn  2034:     }
                   2035: }
                   2036: 
1.868     raeburn  2037: sub is_domainimage {
                   2038:     my ($url) = @_;
1.1172.2.74  raeburn  2039:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2040:         if (&domain($1) ne '') {
                   2041:             return '1';
                   2042:         }
                   2043:     }
                   2044:     return;
                   2045: }
                   2046: 
1.899     raeburn  2047: sub inst_directory_query {
                   2048:     my ($srch) = @_;
                   2049:     my $udom = $srch->{'srchdomain'};
                   2050:     my %results;
                   2051:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2052:     my $outcome;
1.899     raeburn  2053:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2054:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2055:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2056:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2057:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2058:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2059:                     (($major == 2) && ($minor < 11)) ||
                   2060:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2061:                     return;
                   2062:                 }
                   2063:             }
                   2064:         }
1.904     albertel 2065: 	my $queryid=&reply("querysend:instdirsearch:".
                   2066: 			   &escape($srch->{'srchby'}).':'.
                   2067: 			   &escape($srch->{'srchterm'}).':'.
                   2068: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2069: 	my $host=&hostname($homeserver);
                   2070: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2071: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2072: 	    return;
                   2073: 	}
                   2074: 	my $response = &get_query_reply($queryid);
                   2075: 	my $maxtries = 5;
                   2076: 	my $tries = 1;
                   2077: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2078: 	    $response = &get_query_reply($queryid);
                   2079: 	    $tries ++;
                   2080: 	}
                   2081: 
                   2082:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2083:             if ($response eq 'unavailable') {
                   2084:                 $outcome = $response;
                   2085:             } else {
                   2086:                 $outcome = 'ok';
                   2087:                 my @matches = split(/\n/,$response);
                   2088:                 foreach my $match (@matches) {
                   2089:                     my ($key,$value) = split(/=/,$match);
                   2090:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2091:                 }
1.899     raeburn  2092:             }
                   2093:         }
                   2094:     }
1.909     raeburn  2095:     return ($outcome,%results);
1.899     raeburn  2096: }
                   2097: 
                   2098: sub usersearch {
                   2099:     my ($srch) = @_;
                   2100:     my $dom = $srch->{'srchdomain'};
                   2101:     my %results;
                   2102:     my %libserv = &all_library();
                   2103:     my $query = 'usersearch';
                   2104:     foreach my $tryserver (keys(%libserv)) {
                   2105:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2106:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2107:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2108:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2109:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2110:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2111:                              (($major == 2) && ($minor < 11)) ||
                   2112:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2113:                 }
                   2114:             }
1.899     raeburn  2115:             my $host=&hostname($tryserver);
                   2116:             my $queryid=
1.911     raeburn  2117:                 &reply("querysend:".&escape($query).':'.
                   2118:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2119:                        &escape($srch->{'srchtype'}).':'.
                   2120:                        &escape($srch->{'srchterm'}),$tryserver);
                   2121:             if ($queryid !~/^\Q$host\E\_/) {
                   2122:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2123:                 next;
1.899     raeburn  2124:             }
                   2125:             my $reply = &get_query_reply($queryid);
                   2126:             my $maxtries = 1;
                   2127:             my $tries = 1;
                   2128:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2129:                 $reply = &get_query_reply($queryid);
                   2130:                 $tries ++;
                   2131:             }
                   2132:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2133:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2134:             } else {
1.911     raeburn  2135:                 my @matches;
                   2136:                 if ($reply =~ /\n/) {
                   2137:                     @matches = split(/\n/,$reply);
                   2138:                 } else {
                   2139:                     @matches = split(/\&/,$reply);
                   2140:                 }
1.899     raeburn  2141:                 foreach my $match (@matches) {
                   2142:                     my ($uname,$udom,%userhash);
1.911     raeburn  2143:                     foreach my $entry (split(/:/,$match)) {
                   2144:                         my ($key,$value) =
                   2145:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2146:                         $userhash{$key} = $value;
                   2147:                         if ($key eq 'username') {
                   2148:                             $uname = $value;
                   2149:                         } elsif ($key eq 'domain') {
                   2150:                             $udom = $value;
1.911     raeburn  2151:                         }
1.899     raeburn  2152:                     }
                   2153:                     $results{$uname.':'.$udom} = \%userhash;
                   2154:                 }
                   2155:             }
                   2156:         }
                   2157:     }
                   2158:     return %results;
                   2159: }
                   2160: 
1.912     raeburn  2161: sub get_instuser {
                   2162:     my ($udom,$uname,$id) = @_;
                   2163:     my $homeserver = &domain($udom,'primary');
                   2164:     my ($outcome,%results);
                   2165:     if ($homeserver ne '') {
                   2166:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2167:                            &escape($id).':'.&escape($udom),$homeserver);
                   2168:         my $host=&hostname($homeserver);
                   2169:         if ($queryid !~/^\Q$host\E\_/) {
                   2170:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2171:             return;
                   2172:         }
                   2173:         my $response = &get_query_reply($queryid);
                   2174:         my $maxtries = 5;
                   2175:         my $tries = 1;
                   2176:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2177:             $response = &get_query_reply($queryid);
                   2178:             $tries ++;
                   2179:         }
                   2180:         if (!&error($response) && $response ne 'refused') {
                   2181:             if ($response eq 'unavailable') {
                   2182:                 $outcome = $response;
                   2183:             } else {
                   2184:                 $outcome = 'ok';
                   2185:                 my @matches = split(/\n/,$response);
                   2186:                 foreach my $match (@matches) {
                   2187:                     my ($key,$value) = split(/=/,$match);
                   2188:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2189:                 }
                   2190:             }
                   2191:         }
                   2192:     }
                   2193:     my %userinfo;
                   2194:     if (ref($results{$uname}) eq 'HASH') {
                   2195:         %userinfo = %{$results{$uname}};
                   2196:     } 
                   2197:     return ($outcome,%userinfo);
                   2198: }
                   2199: 
1.1172.2.69  raeburn  2200: sub get_multiple_instusers {
                   2201:     my ($udom,$users,$caller) = @_;
                   2202:     my ($outcome,$results);
                   2203:     if (ref($users) eq 'HASH') {
                   2204:         my $count = keys(%{$users});
                   2205:         my $requested = &freeze_escape($users);
                   2206:         my $homeserver = &domain($udom,'primary');
                   2207:         if ($homeserver ne '') {
                   2208:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2209:             my $host=&hostname($homeserver);
                   2210:             if ($queryid !~/^\Q$host\E\_/) {
                   2211:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2212:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2213:                 return ($outcome,$results);
                   2214:             }
                   2215:             my $response = &get_query_reply($queryid);
                   2216:             my $maxtries = 5;
                   2217:             if ($count > 100) {
                   2218:                 $maxtries = 1+int($count/20);
                   2219:             }
                   2220:             my $tries = 1;
                   2221:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2222:                 $response = &get_query_reply($queryid);
                   2223:                 $tries ++;
                   2224:             }
                   2225:             if ($response eq '') {
                   2226:                 $results = {};
                   2227:                 foreach my $key (keys(%{$users})) {
                   2228:                     my ($uname,$id);
                   2229:                     if ($caller eq 'id') {
                   2230:                         $id = $key;
                   2231:                     } else {
                   2232:                         $uname = $key;
                   2233:                     }
                   2234:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2235:                     $outcome = $resp;
                   2236:                     if ($resp eq 'ok') {
                   2237:                         %{$results} = (%{$results}, %info);
                   2238:                     } else {
                   2239:                         last;
                   2240:                     }
                   2241:                 }
                   2242:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2243:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2244:                     $outcome = $response;
                   2245:                 } else {
                   2246:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2247:                     if ($outcome eq 'ok') {
                   2248:                         $results = &thaw_unescape($userdata);
                   2249:                     }
                   2250:                 }
                   2251:             }
                   2252:         }
                   2253:     }
                   2254:     return ($outcome,$results);
                   2255: }
                   2256: 
1.912     raeburn  2257: sub inst_rulecheck {
1.923     raeburn  2258:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2259:     my %returnhash;
                   2260:     if ($udom ne '') {
                   2261:         if (ref($rules) eq 'ARRAY') {
                   2262:             @{$rules} = map {&escape($_);} (@{$rules});
                   2263:             my $rulestr = join(':',@{$rules});
                   2264:             my $homeserver=&domain($udom,'primary');
                   2265:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2266:                 my $response;
                   2267:                 if ($item eq 'username') {                
                   2268:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2269:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2270:                                               $homeserver));
1.923     raeburn  2271:                 } elsif ($item eq 'id') {
                   2272:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2273:                                               ':'.&escape($id).':'.$rulestr,
                   2274:                                               $homeserver));
1.945     raeburn  2275:                 } elsif ($item eq 'selfcreate') {
                   2276:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2277:                                                &escape($udom).':'.&escape($uname).
                   2278:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2279:                 }
1.912     raeburn  2280:                 if ($response ne 'refused') {
                   2281:                     my @pairs=split(/\&/,$response);
                   2282:                     foreach my $item (@pairs) {
                   2283:                         my ($key,$value)=split(/=/,$item,2);
                   2284:                         $key = &unescape($key);
                   2285:                         next if ($key =~ /^error: 2 /);
                   2286:                         $returnhash{$key}=&thaw_unescape($value);
                   2287:                     }
                   2288:                 }
                   2289:             }
                   2290:         }
                   2291:     }
                   2292:     return %returnhash;
                   2293: }
                   2294: 
                   2295: sub inst_userrules {
1.923     raeburn  2296:     my ($udom,$check) = @_;
1.912     raeburn  2297:     my (%ruleshash,@ruleorder);
                   2298:     if ($udom ne '') {
                   2299:         my $homeserver=&domain($udom,'primary');
                   2300:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2301:             my $response;
                   2302:             if ($check eq 'id') {
                   2303:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2304:                                  $homeserver);
1.943     raeburn  2305:             } elsif ($check eq 'email') {
                   2306:                 $response=&reply('instemailrules:'.&escape($udom),
                   2307:                                  $homeserver);
1.923     raeburn  2308:             } else {
                   2309:                 $response=&reply('instuserrules:'.&escape($udom),
                   2310:                                  $homeserver);
                   2311:             }
1.912     raeburn  2312:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2313:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2314:                 ($response ne 'no_such_host')) {
                   2315:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2316:                 my @pairs=split(/\&/,$hashitems);
                   2317:                 foreach my $item (@pairs) {
                   2318:                     my ($key,$value)=split(/=/,$item,2);
                   2319:                     $key = &unescape($key);
                   2320:                     next if ($key =~ /^error: 2 /);
                   2321:                     $ruleshash{$key}=&thaw_unescape($value);
                   2322:                 }
                   2323:                 my @esc_order = split(/\&/,$orderitems);
                   2324:                 foreach my $item (@esc_order) {
                   2325:                     push(@ruleorder,&unescape($item));
                   2326:                 }
                   2327:             }
                   2328:         }
                   2329:     }
                   2330:     return (\%ruleshash,\@ruleorder);
                   2331: }
                   2332: 
1.976     raeburn  2333: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2334: 
                   2335: sub get_domain_defaults {
1.1172.2.35  raeburn  2336:     my ($domain,$ignore_cache) = @_;
                   2337:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2338:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2339:     unless ($ignore_cache) {
                   2340:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2341:         if (defined($cached)) {
                   2342:             if (ref($result) eq 'HASH') {
                   2343:                 return %{$result};
                   2344:             }
1.943     raeburn  2345:         }
                   2346:     }
                   2347:     my %domdefaults;
                   2348:     my %domconfig =
1.989     raeburn  2349:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2350:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2351:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2352:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2353:                                   'coursecategories','autoenroll',
                   2354:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2355:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2356:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2357:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2358:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2359:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2360:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2361:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2362:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2363:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2364:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2365:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2366:     } else {
                   2367:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2368:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2369:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2370:     }
1.976     raeburn  2371:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2372:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2373:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2374:         } else {
                   2375:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2376:         }
1.1172.2.6  raeburn  2377:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2378:         foreach my $item (@usertools) {
                   2379:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2380:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2381:             }
                   2382:         }
1.1172.2.29  raeburn  2383:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2384:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2385:         }
1.976     raeburn  2386:     }
1.985     raeburn  2387:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2388:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2389:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2390:         }
                   2391:     }
1.1172.2.9  raeburn  2392:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2393:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2394:     }
1.989     raeburn  2395:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2396:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2397:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2398:         }
                   2399:     }
1.1047    raeburn  2400:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2401:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2402:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2403:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2404:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2405:         }
1.1172.2.41  raeburn  2406:         foreach my $type (@coursetypes) {
                   2407:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2408:                 unless ($type eq 'community') {
                   2409:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2410:                 }
                   2411:             }
                   2412:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2413:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2414:             }
1.1172.2.60  raeburn  2415:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2416:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2417:                     $domdefaults{$type.'postsubtimeout'} =
                   2418:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2419:                 }
                   2420:             }
1.1172.2.30  raeburn  2421:         }
1.1172.2.67  raeburn  2422:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2423:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2424:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2425:                 if (@clonecodes) {
                   2426:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2427:                 }
                   2428:             }
                   2429:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2430:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2431:         }
1.1172.2.103  raeburn  2432:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2433:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2434:         }
1.1047    raeburn  2435:     }
1.1073    raeburn  2436:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2437:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2438:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2439:         }
                   2440:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2441:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2442:         }
1.1172.2.62  raeburn  2443:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2444:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2445:         }
1.1172.2.118.  .16(raeb 2446:-21):         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
          .15(raeb 2447:-21):             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2448:-21):         }
1.1073    raeburn  2449:     }
1.1172.2.41  raeburn  2450:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2451:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2452:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2453:                             'approval','limit');
                   2454:             foreach my $type (@coursetypes) {
                   2455:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2456:                     my @mgrdc = ();
                   2457:                     foreach my $item (@settings) {
                   2458:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2459:                             push(@mgrdc,$item);
                   2460:                         }
                   2461:                     }
                   2462:                     if (@mgrdc) {
                   2463:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2464:                     }
                   2465:                 }
                   2466:             }
                   2467:         }
                   2468:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2469:             foreach my $type (@coursetypes) {
                   2470:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2471:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2472:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2473:                     }
                   2474:                 }
                   2475:             }
                   2476:         }
                   2477:     }
1.1172.2.46  raeburn  2478:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2479:         $domdefaults{'catauth'} = 'std';
                   2480:         $domdefaults{'catunauth'} = 'std';
                   2481:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2482:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2483:         }
                   2484:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2485:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2486:         }
                   2487:     }
1.1172.2.76  raeburn  2488:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2489:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2490:     }
1.1172.2.89  raeburn  2491:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2492:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2493:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2494:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2495:         }
                   2496:     }
1.1172.2.23  raeburn  2497:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2498:     return %domdefaults;
                   2499: }
                   2500: 
1.1172.2.106  raeburn  2501: sub get_dom_cats {
                   2502:     my ($dom) = @_;
                   2503:     return unless (&domain($dom));
                   2504:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2505:     unless (defined($cached)) {
                   2506:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2507:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2508:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2509:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2510:             } else {
                   2511:                 $cats = {};
                   2512:             }
                   2513:         } else {
                   2514:             $cats = {};
                   2515:         }
                   2516:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2517:     }
                   2518:     return $cats;
                   2519: }
                   2520: 
                   2521: sub get_dom_instcats {
                   2522:     my ($dom) = @_;
                   2523:     return unless (&domain($dom));
                   2524:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2525:     unless (defined($cached)) {
                   2526:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2527:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2528:         if ($totcodes > 0) {
                   2529:             my $caller = 'global';
                   2530:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2531:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2532:                 $instcats = {
                   2533:                                 codes => \%codes,
                   2534:                                 codetitles => \@codetitles,
                   2535:                                 cat_titles => \%cat_titles,
                   2536:                                 cat_order => \%cat_order,
                   2537:                             };
                   2538:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2539:             }
                   2540:         }
                   2541:     }
                   2542:     return $instcats;
                   2543: }
                   2544: 
                   2545: sub retrieve_instcodes {
                   2546:     my ($coursecodes,$dom) = @_;
                   2547:     my $totcodes;
                   2548:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2549:     foreach my $course (keys(%courses)) {
                   2550:         if (ref($courses{$course}) eq 'HASH') {
                   2551:             if ($courses{$course}{'inst_code'} ne '') {
                   2552:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2553:                 $totcodes ++;
                   2554:             }
                   2555:         }
                   2556:     }
                   2557:     return $totcodes;
                   2558: }
                   2559: 
1.1172.2.113  raeburn  2560: # --------------------------------------------- Get domain config for passwords
                   2561: 
                   2562: sub get_passwdconf {
                   2563:     my ($dom) = @_;
                   2564:     my (%passwdconf,$gotconf,$lookup);
                   2565:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2566:     if (defined($cached)) {
                   2567:         if (ref($result) eq 'HASH') {
                   2568:             %passwdconf = %{$result};
                   2569:             $gotconf = 1;
                   2570:         }
                   2571:     }
                   2572:     unless ($gotconf) {
                   2573:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2574:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2575:             %passwdconf = %{$domconfig{'passwords'}};
                   2576:         }
                   2577:         my $cachetime = 24*60*60;
                   2578:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2579:     }
                   2580:     return %passwdconf;
                   2581: }
                   2582: 
1.1172.2.118.  .1(raebu 2583:20): sub course_portal_url {
                   2584:20):     my ($cnum,$cdom) = @_;
                   2585:20):     my $chome = &homeserver($cnum,$cdom);
                   2586:20):     my $hostname = &hostname($chome);
                   2587:20):     my $protocol = $protocol{$chome};
                   2588:20):     $protocol = 'http' if ($protocol ne 'https');
                   2589:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2590:20):     my $firsturl;
                   2591:20):     if ($domdefaults{'portal_def'}) {
                   2592:20):         $firsturl = $domdefaults{'portal_def'};
                   2593:20):     } else {
                   2594:20):         $firsturl = $protocol.'://'.$hostname;
                   2595:20):     }
                   2596:20):     return $firsturl;
                   2597:20): }
                   2598:20): 
1.344     www      2599: # --------------------------------------------------- Assign a key to a student
                   2600: 
                   2601: sub assign_access_key {
1.364     www      2602: #
                   2603: # a valid key looks like uname:udom#comments
                   2604: # comments are being appended
                   2605: #
1.498     www      2606:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2607:     $kdom=
1.620     albertel 2608:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2609:     $knum=
1.620     albertel 2610:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2611:     $cdom=
1.620     albertel 2612:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2613:     $cnum=
1.620     albertel 2614:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2615:     $udom=$env{'user.name'} unless (defined($udom));
                   2616:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2617:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2618:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2619:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2620:                                                   # assigned to this person
                   2621:                                                   # - this should not happen,
1.345     www      2622:                                                   # unless something went wrong
                   2623:                                                   # the first time around
                   2624: # ready to assign
1.364     www      2625:         $logentry=$1.'; '.$logentry;
1.496     www      2626:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2627:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2628: # key now belongs to user
1.346     www      2629: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2630:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2631:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2632:                 return 'ok';
                   2633:             } else {
                   2634:                 return 
                   2635:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2636: 	    }
                   2637:         } else {
                   2638:             return 'error: Could not assign key, try again later.';
                   2639:         }
1.364     www      2640:     } elsif (!$existing{$ckey}) {
1.345     www      2641: # the key does not exist
                   2642: 	return 'error: The key does not exist';
                   2643:     } else {
                   2644: # the key is somebody else's
                   2645: 	return 'error: The key is already in use';
                   2646:     }
1.344     www      2647: }
                   2648: 
1.364     www      2649: # ------------------------------------------ put an additional comment on a key
                   2650: 
                   2651: sub comment_access_key {
                   2652: #
                   2653: # a valid key looks like uname:udom#comments
                   2654: # comments are being appended
                   2655: #
                   2656:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2657:     $cdom=
1.620     albertel 2658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2659:     $cnum=
1.620     albertel 2660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2661:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2662:     if ($existing{$ckey}) {
                   2663:         $existing{$ckey}.='; '.$logentry;
                   2664: # ready to assign
1.367     www      2665:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2666:                                                  $cdom,$cnum) eq 'ok') {
                   2667: 	    return 'ok';
                   2668:         } else {
                   2669: 	    return 'error: Count not store comment.';
                   2670:         }
                   2671:     } else {
                   2672: # the key does not exist
                   2673: 	return 'error: The key does not exist';
                   2674:     }
                   2675: }
                   2676: 
1.344     www      2677: # ------------------------------------------------------ Generate a set of keys
                   2678: 
                   2679: sub generate_access_keys {
1.364     www      2680:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2681:     $cdom=
1.620     albertel 2682:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2683:     $cnum=
1.620     albertel 2684:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2685:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2686:     unless (($cdom) && ($cnum)) { return 0; }
                   2687:     if ($number>10000) { return 0; }
                   2688:     sleep(2); # make sure don't get same seed twice
                   2689:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2690:     my $total=0;
                   2691:     for (my $i=1;$i<=$number;$i++) {
                   2692:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2693:                   sprintf("%lx",int(100000*rand)).'-'.
                   2694:                   sprintf("%lx",int(100000*rand));
                   2695:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2696:        $newkey=~s/0/h/g; # and also 0 and O
                   2697:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2698:        if ($existing{$newkey}) {
                   2699:            $i--;
                   2700:        } else {
1.364     www      2701: 	  if (&put('accesskeys',
                   2702:               { $newkey => '# generated '.localtime().
1.620     albertel 2703:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2704:                            '; '.$logentry },
                   2705: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2706:               $total++;
                   2707: 	  }
                   2708:        }
                   2709:     }
1.620     albertel 2710:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2711:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2712:     return $total;
                   2713: }
                   2714: 
                   2715: # ------------------------------------------------------- Validate an accesskey
                   2716: 
                   2717: sub validate_access_key {
                   2718:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2719:     $cdom=
1.620     albertel 2720:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2721:     $cnum=
1.620     albertel 2722:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2723:     $udom=$env{'user.domain'} unless (defined($udom));
                   2724:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2725:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2726:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2727: }
                   2728: 
                   2729: # ------------------------------------- Find the section of student in a course
1.652     albertel 2730: sub devalidate_getsection_cache {
                   2731:     my ($udom,$unam,$courseid)=@_;
                   2732:     my $hashid="$udom:$unam:$courseid";
                   2733:     &devalidate_cache_new('getsection',$hashid);
                   2734: }
1.298     matthew  2735: 
1.815     albertel 2736: sub courseid_to_courseurl {
                   2737:     my ($courseid) = @_;
                   2738:     #already url style courseid
                   2739:     return $courseid if ($courseid =~ m{^/});
                   2740: 
                   2741:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2742: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2743: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2744: 	return "/$cdom/$cnum";
                   2745:     }
                   2746: 
                   2747:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2748:     if (exists($courseinfo{'num'})) {
                   2749: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2750:     }
                   2751: 
                   2752:     return undef;
                   2753: }
                   2754: 
1.298     matthew  2755: sub getsection {
                   2756:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2757:     my $cachetime=1800;
1.551     albertel 2758: 
                   2759:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2760:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2761:     if (defined($cached)) { return $result; }
                   2762: 
1.298     matthew  2763:     my %Pending; 
                   2764:     my %Expired;
                   2765:     #
                   2766:     # Each role can either have not started yet (pending), be active, 
                   2767:     #    or have expired.
                   2768:     #
                   2769:     # If there is an active role, we are done.
                   2770:     #
                   2771:     # If there is more than one role which has not started yet, 
                   2772:     #     choose the one which will start sooner
                   2773:     # If there is one role which has not started yet, return it.
                   2774:     #
                   2775:     # If there is more than one expired role, choose the one which ended last.
                   2776:     # If there is a role which has expired, return it.
                   2777:     #
1.815     albertel 2778:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2779:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2780:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2781:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2782:         my $section=$1;
                   2783:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2784:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2785:         my $now=time;
1.548     albertel 2786:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2787:             $Expired{$end}=$section;
                   2788:             next;
                   2789:         }
1.548     albertel 2790:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2791:             $Pending{$start}=$section;
                   2792:             next;
                   2793:         }
1.599     albertel 2794:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2795:     }
                   2796:     #
                   2797:     # Presumedly there will be few matching roles from the above
                   2798:     # loop and the sorting time will be negligible.
                   2799:     if (scalar(keys(%Pending))) {
                   2800:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2801:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2802:     } 
                   2803:     if (scalar(keys(%Expired))) {
                   2804:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2805:         my $time = pop(@sorted);
1.599     albertel 2806:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2807:     }
1.599     albertel 2808:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2809: }
1.70      www      2810: 
1.599     albertel 2811: sub save_cache {
                   2812:     &purge_remembered();
1.722     albertel 2813:     #&Apache::loncommon::validate_page();
1.620     albertel 2814:     undef(%env);
1.780     albertel 2815:     undef($env_loaded);
1.599     albertel 2816: }
1.452     albertel 2817: 
1.599     albertel 2818: my $to_remember=-1;
                   2819: my %remembered;
                   2820: my %accessed;
                   2821: my $kicks=0;
                   2822: my $hits=0;
1.849     albertel 2823: sub make_key {
                   2824:     my ($name,$id) = @_;
1.872     albertel 2825:     if (length($id) > 65 
                   2826: 	&& length(&escape($id)) > 200) {
                   2827: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2828:     }
1.849     albertel 2829:     return &escape($name.':'.$id);
                   2830: }
                   2831: 
1.599     albertel 2832: sub devalidate_cache_new {
                   2833:     my ($name,$id,$debug) = @_;
                   2834:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2835:     my $remembered_id=$name.':'.$id;
1.849     albertel 2836:     $id=&make_key($name,$id);
1.599     albertel 2837:     $memcache->delete($id);
1.1172.2.81  raeburn  2838:     delete($remembered{$remembered_id});
                   2839:     delete($accessed{$remembered_id});
1.599     albertel 2840: }
                   2841: 
                   2842: sub is_cached_new {
                   2843:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2844:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2845:                                      # keys in %remembered hash, which persists for
                   2846:                                      # duration of request (no restriction on key length).
                   2847:     if (exists($remembered{$remembered_id})) {
                   2848: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2849: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2850: 	$hits++;
1.1172.2.81  raeburn  2851: 	return ($remembered{$remembered_id},1);
1.599     albertel 2852:     }
1.1172.2.81  raeburn  2853:     $id=&make_key($name,$id);
1.599     albertel 2854:     my $value = $memcache->get($id);
                   2855:     if (!(defined($value))) {
                   2856: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2857: 	return (undef,undef);
1.416     albertel 2858:     }
1.599     albertel 2859:     if ($value eq '__undef__') {
                   2860: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2861: 	$value=undef;
                   2862:     }
1.1172.2.81  raeburn  2863:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2864:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2865:     return ($value,1);
                   2866: }
                   2867: 
                   2868: sub do_cache_new {
                   2869:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2870:     my $remembered_id=$name.':'.$id;
1.849     albertel 2871:     $id=&make_key($name,$id);
1.599     albertel 2872:     my $setvalue=$value;
                   2873:     if (!defined($setvalue)) {
                   2874: 	$setvalue='__undef__';
                   2875:     }
1.623     albertel 2876:     if (!defined($time) ) {
                   2877: 	$time=600;
                   2878:     }
1.599     albertel 2879:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2880:     my $result = $memcache->set($id,$setvalue,$time);
                   2881:     if (! $result) {
1.872     albertel 2882: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2883: 	$memcache->disconnect_all();
1.872     albertel 2884:     }
1.600     albertel 2885:     # need to make a copy of $value
1.1172.2.81  raeburn  2886:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2887:     return $value;
                   2888: }
                   2889: 
                   2890: sub make_room {
1.1172.2.81  raeburn  2891:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2892: 
1.1172.2.81  raeburn  2893:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2894:                                     : $value;
1.599     albertel 2895:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2896:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2897:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2898:     my $to_kick;
                   2899:     my $max_time=0;
                   2900:     foreach my $other (keys(%accessed)) {
                   2901: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2902: 	    $to_kick=$other;
                   2903: 	    $max_time=&tv_interval($accessed{$other});
                   2904: 	}
                   2905:     }
                   2906:     delete($remembered{$to_kick});
                   2907:     delete($accessed{$to_kick});
                   2908:     $kicks++;
                   2909:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2910:     return;
                   2911: }
                   2912: 
1.599     albertel 2913: sub purge_remembered {
1.604     albertel 2914:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2915:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2916:     undef(%remembered);
                   2917:     undef(%accessed);
1.428     albertel 2918: }
1.70      www      2919: # ------------------------------------- Read an entry from a user's environment
                   2920: 
                   2921: sub userenvironment {
                   2922:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2923:     my $items;
                   2924:     foreach my $item (@what) {
                   2925:         $items.=&escape($item).'&';
                   2926:     }
                   2927:     $items=~s/\&$//;
1.70      www      2928:     my %returnhash=();
1.1009    raeburn  2929:     my $uhome = &homeserver($unam,$udom);
                   2930:     unless ($uhome eq 'no_host') {
                   2931:         my @answer=split(/\&/, 
                   2932:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2933:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2934:             return %returnhash;
                   2935:         }
1.1009    raeburn  2936:         my $i;
                   2937:         for ($i=0;$i<=$#what;$i++) {
                   2938: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2939:         }
1.70      www      2940:     }
                   2941:     return %returnhash;
1.1       albertel 2942: }
                   2943: 
1.617     albertel 2944: # ---------------------------------------------------------- Get a studentphoto
                   2945: sub studentphoto {
                   2946:     my ($udom,$unam,$ext) = @_;
                   2947:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2948:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2949:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2950:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2951:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2952:             } else {
                   2953:                 my ($result,$perm_reqd)=
1.707     albertel 2954: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2955:                 if ($result eq 'ok') {
                   2956:                     if (!($perm_reqd eq 'yes')) {
                   2957:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2958:                     }
                   2959:                 }
                   2960:             }
                   2961:         }
                   2962:     } else {
                   2963:         my ($result,$perm_reqd) = 
1.707     albertel 2964: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2965:         if ($result eq 'ok') {
                   2966:             if (!($perm_reqd eq 'yes')) {
                   2967:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2968:             }
                   2969:         }
                   2970:     }
                   2971:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2972: }
                   2973: 
                   2974: sub retrievestudentphoto {
                   2975:     my ($udom,$unam,$ext,$type) = @_;
                   2976:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2977:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2978:     if ($ret eq 'ok') {
                   2979:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2980:         if ($type eq 'thumbnail') {
                   2981:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2982:         }
                   2983:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2984:         return $tokenurl;
                   2985:     } else {
                   2986:         if ($type eq 'thumbnail') {
                   2987:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2988:         } else { 
                   2989:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2990:         }
1.617     albertel 2991:     }
                   2992: }
                   2993: 
1.263     www      2994: # -------------------------------------------------------------------- New chat
                   2995: 
                   2996: sub chatsend {
1.724     raeburn  2997:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2998:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2999:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3000:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3001:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3002: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3003: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3004: }
                   3005: 
                   3006: # ------------------------------------------ Find current version of a resource
                   3007: 
                   3008: sub getversion {
                   3009:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3010:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3011:     return &currentversion(&filelocation('',$fname));
                   3012: }
                   3013: 
                   3014: sub currentversion {
                   3015:     my $fname=shift;
                   3016:     my $author=$fname;
                   3017:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3018:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3019:     my $home=&homeserver($uname,$udom);
1.292     www      3020:     if ($home eq 'no_host') { 
                   3021:         return -1; 
                   3022:     }
1.1112    www      3023:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3024:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3025: 	return -1;
                   3026:     }
1.1112    www      3027:     return $answer;
1.263     www      3028: }
                   3029: 
1.1111    www      3030: #
                   3031: # Return special version number of resource if set by override, empty otherwise
                   3032: #
                   3033: sub usedversion {
                   3034:     my $fname=shift;
                   3035:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3036:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3037:     if ($urlversion) { return $urlversion; }
                   3038:     return '';
                   3039: }
                   3040: 
1.1       albertel 3041: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3042: 
1.1       albertel 3043: sub subscribe {
                   3044:     my $fname=shift;
1.761     raeburn  3045:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3046:     $fname=~s/[\n\r]//g;
1.1       albertel 3047:     my $author=$fname;
                   3048:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3049:     my ($udom,$uname)=split(/\//,$author);
                   3050:     my $home=homeserver($uname,$udom);
1.335     albertel 3051:     if ($home eq 'no_host') {
                   3052:         return 'not_found';
1.1       albertel 3053:     }
                   3054:     my $answer=reply("sub:$fname",$home);
1.64      www      3055:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3056: 	$answer.=' by '.$home;
                   3057:     }
1.1       albertel 3058:     return $answer;
                   3059: }
                   3060:     
1.8       www      3061: # -------------------------------------------------------------- Replicate file
                   3062: 
                   3063: sub repcopy {
                   3064:     my $filename=shift;
1.23      www      3065:     $filename=~s/\/+/\//g;
1.1142    raeburn  3066:     my $londocroot = $perlvar{'lonDocRoot'};
                   3067:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3068:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3069:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3070: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3071: 	return &repcopy_userfile($filename);
                   3072:     }
1.532     albertel 3073:     $filename=~s/[\n\r]//g;
1.8       www      3074:     my $transname="$filename.in.transfer";
1.828     www      3075: # FIXME: this should flock
1.607     raeburn  3076:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3077:     my $remoteurl=subscribe($filename);
1.64      www      3078:     if ($remoteurl =~ /^con_lost by/) {
                   3079: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3080:            return 'unavailable';
1.8       www      3081:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3082: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3083: 	   return 'not_found';
1.64      www      3084:     } elsif ($remoteurl =~ /^rejected by/) {
                   3085: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3086:            return 'forbidden';
1.20      www      3087:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3088:            return 'ok';
1.8       www      3089:     } else {
1.290     www      3090:         my $author=$filename;
                   3091:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3092:         my ($udom,$uname)=split(/\//,$author);
                   3093:         my $home=homeserver($uname,$udom);
                   3094:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3095:            my @parts=split(/\//,$filename);
                   3096:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3097:            if ($path ne "$londocroot/res") {
1.8       www      3098:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3099: 	       return 'bad_request';
1.8       www      3100:            }
                   3101:            my $count;
                   3102:            for ($count=5;$count<$#parts;$count++) {
                   3103:                $path.="/$parts[$count]";
                   3104:                if ((-e $path)!=1) {
                   3105: 		   mkdir($path,0777);
                   3106:                }
                   3107:            }
                   3108:            my $ua=new LWP::UserAgent;
                   3109:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3110:            my $response=$ua->request($request,$transname);
                   3111:            if ($response->is_error()) {
                   3112: 	       unlink($transname);
                   3113:                my $message=$response->status_line;
1.672     albertel 3114:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3115:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3116:                return 'unavailable';
1.8       www      3117:            } else {
1.16      www      3118: 	       if ($remoteurl!~/\.meta$/) {
                   3119:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3120:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3121:                   if ($mresponse->is_error()) {
                   3122: 		      unlink($filename.'.meta');
                   3123:                       &logthis(
1.672     albertel 3124:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3125:                   }
                   3126: 	       }
1.8       www      3127:                rename($transname,$filename);
1.607     raeburn  3128:                return 'ok';
1.8       www      3129:            }
1.290     www      3130:        }
1.8       www      3131:     }
1.330     www      3132: }
                   3133: 
1.1172.2.118.  .5(raebu 3134:20): # ------------------------------------------------- Unsubscribe from a resource
                   3135:20): 
                   3136:20): sub unsubscribe {
                   3137:20):     my ($fname) = @_;
                   3138:20):     my $answer;
                   3139:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3140:20):     $fname=~s/[\n\r]//g;
                   3141:20):     my $author=$fname;
                   3142:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3143:20):     my ($udom,$uname)=split(/\//,$author);
                   3144:20):     my $home=homeserver($uname,$udom);
                   3145:20):     if ($home eq 'no_host') {
                   3146:20):         $answer = 'no_host';
                   3147:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3148:20):         $answer = 'home';
                   3149:20):     } else {
          .7(raebu 3150:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3151:20):     }
                   3152:20):     return $answer;
                   3153:20): }
                   3154:20): 
1.330     www      3155: # ------------------------------------------------ Get server side include body
                   3156: sub ssi_body {
1.381     albertel 3157:     my ($filelink,%form)=@_;
1.606     matthew  3158:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3159:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3160:     }
1.953     www      3161:     my $output='';
                   3162:     my $response;
1.980     raeburn  3163:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3164:        ($output,$response)=&externalssi($filelink);
1.953     www      3165:     } else {
1.1004    droeschl 3166:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3167:        $filelink .= 'inhibitmenu=yes';
1.953     www      3168:        ($output,$response)=&ssi($filelink,%form);
                   3169:     }
1.778     albertel 3170:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3171:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3172:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3173:     if (wantarray) {
                   3174:         return ($output, $response);
                   3175:     } else {
                   3176:         return $output;
                   3177:     }
1.8       www      3178: }
                   3179: 
1.15      www      3180: # --------------------------------------------------------- Server Side Include
                   3181: 
1.782     albertel 3182: sub absolute_url {
                   3183:     my ($host_name) = @_;
                   3184:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3185:     if ($host_name eq '') {
                   3186: 	$host_name = $ENV{'SERVER_NAME'};
                   3187:     }
                   3188:     return $protocol.$host_name;
                   3189: }
                   3190: 
1.942     foxr     3191: #
                   3192: #   Server side include.
                   3193: # Parameters:
                   3194: #  fn     Possibly encrypted resource name/id.
                   3195: #  form   Hash that describes how the rendering should be done
                   3196: #         and other things.
1.944     foxr     3197: # Returns:
1.950     raeburn  3198: #   Scalar context: The content of the response.
                   3199: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3200: #     
1.15      www      3201: sub ssi {
                   3202: 
1.944     foxr     3203:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3204:     my ($request,$response);
1.711     albertel 3205: 
                   3206:     $form{'no_update_last_known'}=1;
1.895     albertel 3207:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3208:     if (%form) {
1.782     albertel 3209:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3210:       $request->content(join('&',map {
                   3211:             my $name = escape($_);
                   3212:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3213:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3214:             : &escape($form{$_}) );
                   3215:         } keys(%form)));
1.23      www      3216:     } else {
1.782     albertel 3217:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3218:     }
                   3219: 
1.15      www      3220:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3221: 
1.1172.2.101  raeburn  3222:     if (($env{'request.course.id'}) &&
                   3223:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3224:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3225:         ($form{'grade_symb'} ne '') &&
                   3226:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3227:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3228:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3229:             my $ua=new LWP::UserAgent;
                   3230:             $ua->local_address('127.0.0.1');
                   3231:             $response = $ua->request($request);
                   3232:         } else {
                   3233:             {
                   3234:                 require LWP::Protocol::http;
                   3235:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3236:                 my $ua=new LWP::UserAgent;
                   3237:                 $response = $ua->request($request);
                   3238:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3239:             }
                   3240:         }
                   3241:     } else {
                   3242:         my $ua=new LWP::UserAgent;
                   3243:         $response = $ua->request($request);
                   3244:     }
1.944     foxr     3245:     if (wantarray) {
1.1172.2.3  raeburn  3246: 	return ($response->content, $response);
1.944     foxr     3247:     } else {
1.1172.2.3  raeburn  3248: 	return $response->content;
1.942     foxr     3249:     }
1.324     www      3250: }
                   3251: 
                   3252: sub externalssi {
                   3253:     my ($url)=@_;
                   3254:     my $ua=new LWP::UserAgent;
                   3255:     my $request=new HTTP::Request('GET',$url);
                   3256:     my $response=$ua->request($request);
1.954     raeburn  3257:     if (wantarray) {
                   3258:         return ($response->content, $response);
                   3259:     } else {
                   3260:         return $response->content;
                   3261:     }
1.15      www      3262: }
1.254     www      3263: 
1.1172.2.98  raeburn  3264: # If the local copy of a replicated resource is outdated, trigger a
                   3265: # connection from the homeserver to flush the delayed queue. If no update
                   3266: # happens, remove local copies of outdated resource (and corresponding
                   3267: # metadata file).
                   3268: 
                   3269: sub remove_stale_resfile {
                   3270:     my ($url) = @_;
                   3271:     my $removed;
                   3272:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3273:         my $audom = $1;
                   3274:         my $auname = $2;
                   3275:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3276:             my $homeserver = &homeserver($auname,$audom);
                   3277:             unless (($homeserver eq 'no_host') ||
                   3278:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3279:                 my $fname = &filelocation('',$url);
                   3280:                 if (-e $fname) {
                   3281:                     my $hostname = &hostname($homeserver);
                   3282:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3283:20):                         my $protocol = $protocol{$homeserver};
                   3284:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3285:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3286:20):                         my $ua=new LWP::UserAgent;
                   3287:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3288:                         my $request=new HTTP::Request('HEAD',$uri);
                   3289:                         my $response=$ua->request($request);
                   3290:                         if ($response->is_success()) {
                   3291:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3292:                             my $locmodtime = (stat($fname))[9];
                   3293:                             if ($locmodtime < $remmodtime) {
                   3294:                                 my $stale;
                   3295:                                 my $answer = &reply('pong',$homeserver);
                   3296:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3297:                                     sleep(0.2);
                   3298:                                     $locmodtime = (stat($fname))[9];
                   3299:                                     if ($locmodtime < $remmodtime) {
                   3300:                                         my $posstransfer = $fname.'.in.transfer';
                   3301:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3302:                                             $removed = 1;
                   3303:                                         } else {
                   3304:                                             $stale = 1;
                   3305:                                         }
                   3306:                                     } else {
                   3307:                                         $removed = 1;
                   3308:                                     }
                   3309:                                 } else {
                   3310:                                     $stale = 1;
                   3311:                                 }
                   3312:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3313:20):                                     if (unlink($fname)) {
                   3314:20):                                         if ($uri!~/\.meta$/) {
                   3315:20):                                             if (-e $fname.'.meta') {
                   3316:20):                                                 unlink($fname.'.meta');
                   3317:20):                                             }
                   3318:20):                                         }
                   3319:20):                                         my $unsubresult = &unsubscribe($fname);
                   3320:20):                                         unless ($unsubresult eq 'ok') {
                   3321:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3322:20):                                         }
                   3323:20):                                         $removed = 1;
1.1172.2.98  raeburn  3324:                                     }
                   3325:                                 }
                   3326:                             }
                   3327:                         }
                   3328:                     }
                   3329:                 }
                   3330:             }
                   3331:         }
                   3332:     }
                   3333:     return $removed;
                   3334: }
                   3335: 
1.492     albertel 3336: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3337: 
                   3338: sub allowuploaded {
                   3339:     my ($srcurl,$url)=@_;
                   3340:     $url=&clutter(&declutter($url));
                   3341:     my $dir=$url;
                   3342:     $dir=~s/\/[^\/]+$//;
                   3343:     my %httpref=();
                   3344:     my $httpurl=&hreflocation('',$url);
                   3345:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3346:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3347: }
1.477     raeburn  3348: 
1.1172.2.13  raeburn  3349: #
                   3350: # Determine if the current user should be able to edit a particular resource,
                   3351: # when viewing in course context.
                   3352: # (a) When viewing resource used to determine if "Edit" item is included in
                   3353: #     Functions.
                   3354: # (b) When displaying folder contents in course editor, used to determine if
                   3355: #     "Edit" link will be displayed alongside resource.
                   3356: #
                   3357: #  input: six args -- filename (decluttered), course number, course domain,
                   3358: #                   url, symb (if registered) and group (if this is a group
                   3359: #                   item -- e.g., bulletin board, group page etc.).
                   3360: #  output: array of five scalars --
                   3361: #          $cfile -- url for file editing if editable on current server
                   3362: #          $home -- homeserver of resource (i.e., for author if published,
                   3363: #                                           or course if uploaded.).
                   3364: #          $switchserver --  1 if server switch will be needed.
                   3365: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3366: #          $forceview -- 1 if icon/link should be to go to view mode
                   3367: #
                   3368: 
                   3369: sub can_edit_resource {
                   3370:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3371:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3372: #
                   3373: # For aboutme pages user can only edit his/her own.
                   3374: #
                   3375:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3376:         my ($sdom,$sname) = ($1,$2);
                   3377:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3378:             $home = $env{'user.home'};
                   3379:             $cfile = $resurl;
                   3380:             if ($env{'form.forceedit'}) {
                   3381:                 $forceview = 1;
                   3382:             } else {
                   3383:                 $forceedit = 1;
                   3384:             }
                   3385:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3386:         } else {
                   3387:             return;
                   3388:         }
                   3389:     }
                   3390: 
                   3391:     if ($env{'request.course.id'}) {
                   3392:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3393:         if ($group ne '') {
                   3394: # if this is a group homepage or group bulletin board, check group privs
                   3395:             my $allowed = 0;
                   3396:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3397:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3398:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3399:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3400:                     $allowed = 1;
                   3401:                 }
                   3402:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3403:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3404:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3405:                     $allowed = 1;
                   3406:                 }
                   3407:             }
                   3408:             if ($allowed) {
                   3409:                 $home=&homeserver($cnum,$cdom);
                   3410:                 if ($env{'form.forceedit'}) {
                   3411:                     $forceview = 1;
                   3412:                 } else {
                   3413:                     $forceedit = 1;
                   3414:                 }
                   3415:                 $cfile = $resurl;
                   3416:             } else {
                   3417:                 return;
                   3418:             }
                   3419:         } else {
1.1172.2.15  raeburn  3420:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3421:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3422:                     return;
                   3423:                 }
                   3424:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3425: #
                   3426: # No edit allowed where CC has switched to student role.
                   3427: #
                   3428:                 return;
                   3429:             }
                   3430:         }
                   3431:     }
                   3432: 
                   3433:     if ($file ne '') {
                   3434:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3435:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3436:                 $uploaded = 1;
                   3437:                 $incourse = 1;
                   3438:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3439:                     $cfile = &hreflocation('',$file);
                   3440:                     if ($env{'form.forceedit'}) {
                   3441:                         $forceview = 1;
                   3442:                     } else {
                   3443:                         $forceedit = 1;
                   3444:                     }
                   3445:                 }
                   3446:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3447:                 $incourse = 1;
                   3448:                 if ($env{'form.forceedit'}) {
                   3449:                     $forceview = 1;
                   3450:                 } else {
                   3451:                     $forceedit = 1;
                   3452:                 }
                   3453:                 $cfile = $resurl;
                   3454:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3455:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3456:                     $incourse = 1;
                   3457:                     if ($env{'form.forceedit'}) {
                   3458:                         $forceview = 1;
                   3459:                     } else {
                   3460:                         $forceedit = 1;
                   3461:                     }
                   3462:                     $cfile = $resurl;
                   3463:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3464:                     $incourse = 1;
                   3465:                     $cfile = $resurl.'/smpedit';
                   3466:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3467:                     $incourse = 1;
                   3468:                     if ($env{'form.forceedit'}) {
                   3469:                         $forceview = 1;
                   3470:                     } else {
                   3471:                         $forceedit = 1;
                   3472:                     }
                   3473:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3474:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3475:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3476:20):                     if ($map =~ /\.page$/) {
                   3477:20):                         $incourse = 1;
                   3478:20):                         if ($env{'form.forceedit'}) {
                   3479:20):                             $forceview = 1;
                   3480:20):                             $cfile = $map;
                   3481:20):                         } else {
                   3482:20):                             $forceedit = 1;
                   3483:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3484:20):                         }
                   3485:20):                     }
          .1(raebu 3486:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3487:20):                     $incourse = 1;
                   3488:20):                     if ($env{'form.forceedit'}) {
                   3489:20):                         $forceview = 1;
                   3490:20):                     } else {
                   3491:20):                         $forceedit = 1;
                   3492:20):                     }
                   3493:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3494:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3495:                     $incourse = 1;
                   3496:                     if ($env{'form.forceedit'}) {
                   3497:                         $forceview = 1;
                   3498:                     } else {
                   3499:                         $forceedit = 1;
                   3500:                     }
                   3501:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3502:                 }
                   3503:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3504:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3505:                 if (&is_on_map($template)) {
                   3506:                     $incourse = 1;
                   3507:                     $forceview = 1;
                   3508:                     $cfile = $template;
                   3509:                 }
                   3510:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3511:                 $incourse = 1;
                   3512:                 if ($env{'form.forceedit'}) {
                   3513:                     $forceview = 1;
                   3514:                 } else {
                   3515:                     $forceedit = 1;
                   3516:                 }
                   3517:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3518:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3519:20):                 $incourse = 1;
                   3520:20):                 if ($env{'form.forceedit'}) {
                   3521:20):                     $forceview = 1;
                   3522:20):                 } else {
                   3523:20):                     $forceedit = 1;
                   3524:20):                 }
                   3525:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3526:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3527:                 $incourse = 1;
                   3528:                 $forceview = 1;
                   3529:                 if ($symb) {
                   3530:                     my ($map,$id,$res)=&decode_symb($symb);
                   3531:                     $env{'request.symb'} = $symb;
                   3532:                     $cfile = &clutter($res);
                   3533:                 } else {
                   3534:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3535:20):                     my $escfile = &unescape($cfile);
                   3536:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3537:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3538:20):                     } else {
                   3539:20):                         $escfile =~ s{^http://}{};
                   3540:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3541:20):                     }
1.1172.2.13  raeburn  3542:                 }
1.1172.2.31  raeburn  3543:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3544:                 if ($env{'form.forceedit'}) {
                   3545:                     $forceview = 1;
                   3546:                 } else {
                   3547:                     $forceedit = 1;
                   3548:                 }
                   3549:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3550:             }
                   3551:         }
                   3552:         if ($uploaded || $incourse) {
                   3553:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3554:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3555:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3556:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3557:             # Check that the user has permission to edit this resource
                   3558:             my $setpriv = 1;
                   3559:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3560:             if (defined($cfudom)) {
                   3561:                 $home=&homeserver($cfuname,$cfudom);
                   3562:                 $cfile=$file;
                   3563:             }
                   3564:         }
                   3565:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3566:             (($home ne '') && ($home ne 'no_host'))) {
                   3567:             my @ids=&current_machine_ids();
                   3568:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3569:                 $switchserver=1;
                   3570:             }
                   3571:         }
                   3572:     }
                   3573:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3574: }
                   3575: 
                   3576: sub is_course_upload {
                   3577:     my ($file,$cnum,$cdom) = @_;
                   3578:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3579:     $uploadpath =~ s{^\/}{};
                   3580:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3581:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3582:         return 1;
                   3583:     }
                   3584:     return;
                   3585: }
                   3586: 
                   3587: sub in_course {
                   3588:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3589:     if ($hideprivileged) {
                   3590:         my $skipuser;
1.1172.2.23  raeburn  3591:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3592:         my @possdoms = ($cdom);
                   3593:         if ($coursehash{'checkforpriv'}) {
                   3594:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3595:         }
                   3596:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3597:             $skipuser = 1;
                   3598:             if ($coursehash{'nothideprivileged'}) {
                   3599:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3600:                     my $user;
                   3601:                     if ($item =~ /:/) {
                   3602:                         $user = $item;
                   3603:                     } else {
                   3604:                         $user = join(':',split(/[\@]/,$item));
                   3605:                     }
                   3606:                     if ($user eq $uname.':'.$udom) {
                   3607:                         undef($skipuser);
                   3608:                         last;
                   3609:                     }
                   3610:                 }
                   3611:             }
                   3612:             if ($skipuser) {
                   3613:                 return 0;
                   3614:             }
                   3615:         }
                   3616:     }
                   3617:     $type ||= 'any';
                   3618:     if (!defined($cdom) || !defined($cnum)) {
                   3619:         my $cid  = $env{'request.course.id'};
                   3620:         $cdom = $env{'course.'.$cid.'.domain'};
                   3621:         $cnum = $env{'course.'.$cid.'.num'};
                   3622:     }
                   3623:     my $typesref;
                   3624:     if (($type eq 'any') || ($type eq 'all')) {
                   3625:         $typesref = ['active','previous','future'];
                   3626:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3627:         $typesref = [$type];
                   3628:     }
                   3629:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3630:                               $typesref,undef,[$cdom]);
                   3631:     my ($tmp) = keys(%roles);
                   3632:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3633:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3634:     if (@course_roles > 0) {
                   3635:         return 1;
                   3636:     }
                   3637:     return 0;
                   3638: }
                   3639: 
1.478     albertel 3640: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3641: # input: action, courseID, current domain, intended
1.637     raeburn  3642: #        path to file, source of file, instruction to parse file for objects,
                   3643: #        ref to hash for embedded objects,
                   3644: #        ref to hash for codebase of java objects.
1.1095    raeburn  3645: #        reference to scalar to accommodate mime type determined
                   3646: #          from File::MMagic if $parser = parse.
1.637     raeburn  3647: #
1.485     raeburn  3648: # output: url to file (if action was uploaddoc), 
                   3649: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3650: #
1.478     albertel 3651: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3652: # course.
1.477     raeburn  3653: #
1.478     albertel 3654: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3655: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3656: #          course's home server.
1.477     raeburn  3657: #
1.478     albertel 3658: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3659: #          be copied from $source (current location) to 
                   3660: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3661: #         and will then be copied to
                   3662: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3663: #         course's home server.
1.485     raeburn  3664: #
1.481     raeburn  3665: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3666: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3667: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3668: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3669: #         in course's home server.
1.637     raeburn  3670: #
1.477     raeburn  3671: 
                   3672: sub process_coursefile {
1.1095    raeburn  3673:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3674:         $mimetype)=@_;
1.477     raeburn  3675:     my $fetchresult;
1.638     albertel 3676:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3677:     if ($action eq 'propagate') {
1.638     albertel 3678:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3679: 			     $home);
1.481     raeburn  3680:     } else {
1.477     raeburn  3681:         my $fpath = '';
                   3682:         my $fname = $file;
1.478     albertel 3683:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3684:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3685:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3686:         if ($action eq 'copy') {
                   3687:             if ($source eq '') {
                   3688:                 $fetchresult = 'no source file';
                   3689:                 return $fetchresult;
                   3690:             } else {
                   3691:                 my $destination = $filepath.'/'.$fname;
                   3692:                 rename($source,$destination);
                   3693:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3694:                                  $home);
1.481     raeburn  3695:             }
                   3696:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3697:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3698:             print $fh $env{'form.'.$source};
1.481     raeburn  3699:             close($fh);
1.637     raeburn  3700:             if ($parser eq 'parse') {
1.1024    raeburn  3701:                 my $mm = new File::MMagic;
1.1095    raeburn  3702:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3703:                 if ($type eq 'text/html') {
1.1024    raeburn  3704:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3705:                     unless ($parse_result eq 'ok') {
                   3706:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3707:                     }
1.637     raeburn  3708:                 }
1.1095    raeburn  3709:                 if (ref($mimetype)) {
                   3710:                     $$mimetype = $type;
                   3711:                 } 
1.637     raeburn  3712:             }
1.477     raeburn  3713:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3714:                                  $home);
1.481     raeburn  3715:             if ($fetchresult eq 'ok') {
                   3716:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3717:             } else {
                   3718:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3719:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3720:                 return '/adm/notfound.html';
                   3721:             }
1.477     raeburn  3722:         }
                   3723:     }
1.485     raeburn  3724:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3725:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3726:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3727:     }
                   3728:     return $fetchresult;
                   3729: }
                   3730: 
1.637     raeburn  3731: sub build_filepath {
                   3732:     my ($fpath) = @_;
                   3733:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3734:     unless ($fpath eq '') {
                   3735:         my @parts=split('/',$fpath);
                   3736:         foreach my $part (@parts) {
                   3737:             $filepath.= '/'.$part;
                   3738:             if ((-e $filepath)!=1) {
                   3739:                 mkdir($filepath,0777);
                   3740:             }
                   3741:         }
                   3742:     }
                   3743:     return $filepath;
                   3744: }
                   3745: 
                   3746: sub store_edited_file {
1.638     albertel 3747:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3748:     my $file = $primary_url;
                   3749:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3750:     my $fpath = '';
                   3751:     my $fname = $file;
                   3752:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3753:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3754:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3755:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3756:     print $fh $content;
                   3757:     close($fh);
1.638     albertel 3758:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3759:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3760: 			  $home);
1.637     raeburn  3761:     if ($$fetchresult eq 'ok') {
                   3762:         return '/uploaded/'.$fpath.'/'.$fname;
                   3763:     } else {
1.638     albertel 3764:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3765: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3766:         return '/adm/notfound.html';
                   3767:     }
                   3768: }
                   3769: 
1.531     albertel 3770: sub clean_filename {
1.831     albertel 3771:     my ($fname,$args)=@_;
1.315     www      3772: # Replace Windows backslashes by forward slashes
1.257     www      3773:     $fname=~s/\\/\//g;
1.831     albertel 3774:     if (!$args->{'keep_path'}) {
                   3775:         # Get rid of everything but the actual filename
                   3776: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3777:     }
1.315     www      3778: # Replace spaces by underscores
                   3779:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3780: # Transliterate non-ascii text to ascii
                   3781:     my $lang = &Apache::lonlocal::current_language();
                   3782:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3783: # Replace all other weird characters by nothing
1.831     albertel 3784:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3785: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3786: # numbers
                   3787:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3788:     return $fname;
                   3789: }
1.1172.2.110  raeburn  3790: 
1.1051    raeburn  3791: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3792: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3793: # image with the same aspect ratio as the original, but with dimensions which do 
                   3794: # not exceed $resizewidth and $resizeheight.
                   3795:  
1.984     neumanie 3796: sub resizeImage {
1.1051    raeburn  3797:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3798:     my $ima = Image::Magick->new;
                   3799:     my $resized;
                   3800:     if (-e $img_path) {
                   3801:         $ima->Read($img_path);
                   3802:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3803:             my $width = $ima->Get('width');
                   3804:             my $height = $ima->Get('height');
                   3805:             if ($width > $resizewidth) {
                   3806: 	        my $factor = $width/$resizewidth;
                   3807:                 my $newheight = $height/$factor;
                   3808:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3809:                 $resized = 1;
                   3810:             }
                   3811:         }
                   3812:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3813:             my $width = $ima->Get('width');
                   3814:             my $height = $ima->Get('height');
                   3815:             if ($height > $resizeheight) {
                   3816:                 my $factor = $height/$resizeheight;
                   3817:                 my $newwidth = $width/$factor;
                   3818:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3819:                 $resized = 1;
                   3820:             }
                   3821:         }
                   3822:         if ($resized) {
                   3823:             $ima->Write($img_path);
                   3824:         }
                   3825:     }
                   3826:     return;
1.977     amueller 3827: }
                   3828: 
1.608     albertel 3829: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3830: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3831: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3832: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3833: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3834: #                   if 'coursedoc': upload to the current course
                   3835: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3836: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3837: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3838: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3839: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3840: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3841: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3842: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3843: #        $allfiles - reference to hash for embedded objects
                   3844: #        $codebase - reference to hash for codebase of java objects
                   3845: #        $desuname - username for permanent storage of uploaded file
                   3846: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3847: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3848: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3849: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3850: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3851: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3852: #                    from File::MMagic.
1.858     raeburn  3853: # 
1.686     albertel 3854: # output: url of file in userspace, or error: <message> 
                   3855: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3856: 
1.531     albertel 3857: sub userfileupload {
1.1090    raeburn  3858:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3859:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3860:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3861:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3862:     $fname=&clean_filename($fname);
1.1090    raeburn  3863:     # See if there is anything left
1.257     www      3864:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3865:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3866:     if ($fname =~ /^\./) {
                   3867:         my ($s,$usec) = &gettimeofday();
                   3868:         while (length($usec) < 6) {
                   3869:             $usec = '0'.$usec;
                   3870:         }
                   3871:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3872:     }
1.1090    raeburn  3873:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3874:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3875:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3876:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3877:         my $now = time;
1.1090    raeburn  3878:         my $filepath;
1.1095    raeburn  3879:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3880:              $filepath = 'tmp/helprequests/'.$now;
                   3881:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3882:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3883:                          '_'.$env{'user.domain'}.'/pending';
                   3884:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3885:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3886:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3887:                 $docudom = $destudom;
                   3888:             } else {
                   3889:                 $docudom = $env{'user.domain'};
                   3890:             }
1.1172.2.96  raeburn  3891:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3892:                 $docuname = $destuname;
                   3893:             } else {
                   3894:                 $docuname = $env{'user.name'};
                   3895:             }
                   3896:             if (exists($env{'form.group'})) {
                   3897:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3898:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3899:             }
                   3900:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3901:             if ($context eq 'canceloverwrite') {
                   3902:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3903:                 if (-e  $tempfile) {
                   3904:                     my @info = stat($tempfile);
                   3905:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3906:                         unlink($tempfile);
                   3907:                     }
                   3908:                 }
                   3909:                 return;
1.523     raeburn  3910:             }
                   3911:         }
1.1090    raeburn  3912:         # Create the directory if not present
1.741     raeburn  3913:         my @parts=split(/\//,$filepath);
                   3914:         my $fullpath = $perlvar{'lonDaemons'};
                   3915:         for (my $i=0;$i<@parts;$i++) {
                   3916:             $fullpath .= '/'.$parts[$i];
                   3917:             if ((-e $fullpath)!=1) {
                   3918:                 mkdir($fullpath,0777);
                   3919:             }
                   3920:         }
1.1172.2.96  raeburn  3921:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3922:         print $fh $env{'form.'.$formname};
                   3923:         close($fh);
1.1090    raeburn  3924:         if ($context eq 'existingfile') {
                   3925:             my @info = stat($fullpath.'/'.$fname);
                   3926:             return ($fullpath.'/'.$fname,$info[9]);
                   3927:         } else {
                   3928:             return $fullpath.'/'.$fname;
                   3929:         }
1.523     raeburn  3930:     }
1.995     raeburn  3931:     if ($subdir eq 'scantron') {
                   3932:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3933:     } else {
1.995     raeburn  3934:         $fname="$subdir/$fname";
                   3935:     }
1.1090    raeburn  3936:     if ($context eq 'coursedoc') {
1.638     albertel 3937: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3938: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3939:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3940:             return &finishuserfileupload($docuname,$docudom,
                   3941: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3942: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3943:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3944:         } else {
1.1172.2.21  raeburn  3945:             if ($env{'form.folder'}) {
                   3946:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3947:             }
1.638     albertel 3948:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3949: 				       $fname,$formname,$parser,
1.1095    raeburn  3950: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3951:         }
1.719     banghart 3952:     } elsif (defined($destuname)) {
                   3953:         my $docuname=$destuname;
                   3954:         my $docudom=$destudom;
1.860     raeburn  3955: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3956: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3957:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3958:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3959:     } else {
1.638     albertel 3960:         my $docuname=$env{'user.name'};
                   3961:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3962:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3963:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3964:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3965:         }
1.860     raeburn  3966: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3967: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3968:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3969:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3970:     }
1.271     www      3971: }
                   3972: 
                   3973: sub finishuserfileupload {
1.860     raeburn  3974:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3975:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3976:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3977:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3978:   
1.860     raeburn  3979:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3980:     $file=$fname;
                   3981:     if ($fname=~m|/|) {
                   3982:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3983: 	$path.=$fnamepath.'/';
                   3984:     }
1.259     www      3985:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3986:     my $count;
                   3987:     for ($count=4;$count<=$#parts;$count++) {
                   3988:         $filepath.="/$parts[$count]";
                   3989:         if ((-e $filepath)!=1) {
                   3990: 	    mkdir($filepath,0777);
                   3991:         }
                   3992:     }
1.984     neumanie 3993: 
1.258     www      3994: # Save the file
                   3995:     {
1.1172.2.96  raeburn  3996: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3997: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3998: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3999: 	    return '/adm/notfound.html';
                   4000: 	}
1.1090    raeburn  4001:         if ($context eq 'overwrite') {
1.1117    foxr     4002:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4003:             my $target = $filepath.'/'.$file;
                   4004:             if (-e $source) {
                   4005:                 my @info = stat($source);
                   4006:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4007:                     unless (&File::Copy::move($source,$target)) {
                   4008:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4009:                         return "Moving from $source failed";
                   4010:                     }
                   4011:                 } else {
                   4012:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4013:                 }
                   4014:             } else {
                   4015:                 return "Temporary file: $source missing";
                   4016:             }
                   4017:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4018: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4019: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4020: 	    return '/adm/notfound.html';
                   4021: 	}
1.570     albertel 4022: 	close(FH);
1.1051    raeburn  4023:         if ($resizewidth && $resizeheight) {
                   4024:             my $mm = new File::MMagic;
                   4025:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4026:             if ($mime_type =~ m{^image/}) {
                   4027: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4028:             }  
1.977     amueller 4029: 	}
1.258     www      4030:     }
1.1152    raeburn  4031:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4032:         if (ref($mimetype)) {
                   4033:             if ($$mimetype eq '') {
                   4034:                 my $mm = new File::MMagic;
                   4035:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4036:                 $$mimetype = $type;
                   4037:             }
                   4038:         }
                   4039:     }
1.1172.2.109  raeburn  4040:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4041:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4042:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4043:                                                        $allfiles,$codebase);
                   4044:             unless ($parse_result eq 'ok') {
                   4045:                 &logthis('Failed to parse '.$filepath.$file.
                   4046: 	   	         ' for embedded media: '.$parse_result); 
                   4047:             }
1.637     raeburn  4048:         }
1.1172.2.109  raeburn  4049:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4050:         my $format = $env{'form.scantron_format'};
                   4051:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4052:     }
1.860     raeburn  4053:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4054:         my $input = $filepath.'/'.$file;
                   4055:         my $output = $filepath.'/'.'tn-'.$file;
                   4056:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4057:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4058:         system({$args[0]} @args);
1.860     raeburn  4059:         if (-e $filepath.'/'.'tn-'.$file) {
                   4060:             $fetchthumb  = 1; 
                   4061:         }
                   4062:     }
1.858     raeburn  4063:  
1.259     www      4064: # Notify homeserver to grep it
                   4065: #
1.984     neumanie 4066:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4067:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4068:     if ($fetchresult eq 'ok') {
1.860     raeburn  4069:         if ($fetchthumb) {
                   4070:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4071:             if ($thumbresult ne 'ok') {
                   4072:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4073:                          $docuhome.': '.$thumbresult);
                   4074:             }
                   4075:         }
1.259     www      4076: #
1.258     www      4077: # Return the URL to it
1.494     albertel 4078:         return '/uploaded/'.$path.$file;
1.263     www      4079:     } else {
1.494     albertel 4080:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4081: 		 ': '.$fetchresult);
1.263     www      4082:         return '/adm/notfound.html';
1.858     raeburn  4083:     }
1.493     albertel 4084: }
                   4085: 
1.637     raeburn  4086: sub extract_embedded_items {
1.961     raeburn  4087:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4088:     my @state = ();
1.1164    raeburn  4089:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4090:     my %javafiles = (
                   4091:                       codebase => '',
                   4092:                       code => '',
                   4093:                       archive => ''
                   4094:                     );
                   4095:     my %mediafiles = (
                   4096:                       src => '',
                   4097:                       movie => '',
                   4098:                      );
1.648     raeburn  4099:     my $p;
                   4100:     if ($content) {
                   4101:         $p = HTML::LCParser->new($content);
                   4102:     } else {
1.961     raeburn  4103:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4104:     }
1.641     albertel 4105:     while (my $t=$p->get_token()) {
1.640     albertel 4106: 	if ($t->[0] eq 'S') {
                   4107: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4108: 	    push(@state, $tagname);
1.648     raeburn  4109:             if (lc($tagname) eq 'allow') {
                   4110:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4111:             }
1.640     albertel 4112: 	    if (lc($tagname) eq 'img') {
                   4113: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4114: 	    }
1.886     albertel 4115: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4116:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4117: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4118:                 }
1.886     albertel 4119: 	    }
1.645     raeburn  4120:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4121:                 my $src;
1.645     raeburn  4122:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4123:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4124:                 } else {
1.1164    raeburn  4125:                     if ($attr->{'src'} ne '') {
                   4126:                         $src = $attr->{'src'};
                   4127:                         &add_filetype($allfiles,$src,'src');
                   4128:                     }
                   4129:                 }
                   4130:                 my $text = $p->get_trimmed_text();
                   4131:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4132:                     my @swfargs = split(/,/,$1);
                   4133:                     foreach my $item (@swfargs) {
                   4134:                         $item =~ s/["']//g;
                   4135:                         $item =~ s/^\s+//;
                   4136:                         $item =~ s/\s+$//;
                   4137:                     }
                   4138:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4139:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4140:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4141:                         } else {
                   4142:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4143:                         }
                   4144:                     }
1.645     raeburn  4145:                 }
                   4146:             }
                   4147:             if (lc($tagname) eq 'link') {
                   4148:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4149:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4150:                 }
                   4151:             }
1.640     albertel 4152: 	    if (lc($tagname) eq 'object' ||
                   4153: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4154: 		foreach my $item (keys(%javafiles)) {
                   4155: 		    $javafiles{$item} = '';
                   4156: 		}
1.1164    raeburn  4157:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4158:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4159:                 }
1.640     albertel 4160: 	    }
                   4161: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4162: 		my $name = lc($attr->{'name'});
                   4163: 		foreach my $item (keys(%javafiles)) {
                   4164: 		    if ($name eq $item) {
                   4165: 			$javafiles{$item} = $attr->{'value'};
                   4166: 			last;
                   4167: 		    }
                   4168: 		}
1.1164    raeburn  4169:                 my $pathfrom;
1.640     albertel 4170: 		foreach my $item (keys(%mediafiles)) {
                   4171: 		    if ($name eq $item) {
1.1164    raeburn  4172:                         $pathfrom = $attr->{'value'};
                   4173:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4174: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4175: 			last;
                   4176: 		    }
                   4177: 		}
1.1164    raeburn  4178:                 if ($name eq 'flashvars') {
                   4179:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4180:                 }
                   4181:                 if ($pathfrom ne '') {
                   4182:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4183:                                          $pathfrom);
                   4184:                 }
1.640     albertel 4185: 	    }
                   4186: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4187: 		foreach my $item (keys(%javafiles)) {
                   4188: 		    if ($attr->{$item}) {
                   4189: 			$javafiles{$item} = $attr->{$item};
                   4190: 			last;
                   4191: 		    }
                   4192: 		}
                   4193: 		foreach my $item (keys(%mediafiles)) {
                   4194: 		    if ($attr->{$item}) {
                   4195: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4196: 			last;
                   4197: 		    }
                   4198: 		}
1.1164    raeburn  4199:                 if (lc($tagname) eq 'embed') {
                   4200:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4201:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4202:                                              $attr->{'src'});
                   4203:                     }
                   4204:                 }
1.640     albertel 4205: 	    }
1.1172.2.35  raeburn  4206:             if (lc($tagname) eq 'iframe') {
                   4207:                 my $src = $attr->{'src'} ;
                   4208:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4209:                     &add_filetype($allfiles,$src,'src');
                   4210:                 } elsif ($src =~ m{^/}) {
                   4211:                     if ($env{'request.course.id'}) {
                   4212:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4213:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4214:                         my $url = &hreflocation('',$fullpath);
                   4215:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4216:                             my $relpath = $1;
                   4217:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4218:                                 &add_filetype($allfiles,$1,'src');
                   4219:                             }
                   4220:                         }
                   4221:                     }
                   4222:                 }
                   4223:             }
1.1164    raeburn  4224:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4225:                 pop(@state);
1.1164    raeburn  4226:             }
1.640     albertel 4227: 	} elsif ($t->[0] eq 'E') {
                   4228: 	    my ($tagname) = ($t->[1]);
                   4229: 	    if ($javafiles{'codebase'} ne '') {
                   4230: 		$javafiles{'codebase'} .= '/';
                   4231: 	    }  
                   4232: 	    if (lc($tagname) eq 'applet' ||
                   4233: 		lc($tagname) eq 'object' ||
                   4234: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4235: 		) {
                   4236: 		foreach my $item (keys(%javafiles)) {
                   4237: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4238: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4239: 			&add_filetype($allfiles,$file,$item);
                   4240: 		    }
                   4241: 		}
                   4242: 	    } 
                   4243: 	    pop @state;
                   4244: 	}
                   4245:     }
1.1164    raeburn  4246:     foreach my $id (sort(keys(%flashvars))) {
                   4247:         if ($shockwave{$id} ne '') {
                   4248:             my @pairs = split(/\&/,$flashvars{$id});
                   4249:             foreach my $pair (@pairs) {
                   4250:                 my ($key,$value) = split(/\=/,$pair);
                   4251:                 if ($key eq 'thumb') {
                   4252:                     &add_filetype($allfiles,$value,$key);
                   4253:                 } elsif ($key eq 'content') {
                   4254:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4255:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4256:                     if ($ext ne '') {
                   4257:                         &add_filetype($allfiles,$path.$value,$ext);
                   4258:                     }
                   4259:                 }
                   4260:             }
                   4261:         }
                   4262:     }
1.637     raeburn  4263:     return 'ok';
                   4264: }
                   4265: 
1.639     albertel 4266: sub add_filetype {
                   4267:     my ($allfiles,$file,$type)=@_;
                   4268:     if (exists($allfiles->{$file})) {
                   4269: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4270: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4271: 	}
                   4272:     } else {
                   4273: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4274:     }
                   4275: }
                   4276: 
1.1164    raeburn  4277: sub embedded_dependency {
                   4278:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4279:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4280:         if (($identifier ne '') &&
                   4281:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4282:             ($pathfrom ne '')) {
                   4283:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4284:             foreach my $dep (@{$related->{$identifier}}) {
                   4285:                 &add_filetype($allfiles,$path.$dep,'object');
                   4286:             }
                   4287:         }
                   4288:     }
                   4289:     return;
                   4290: }
                   4291: 
1.1172.2.109  raeburn  4292: sub bubblesheet_converter {
                   4293:     my ($cdom,$fullpath,$config,$format) = @_;
                   4294:     if ((&domain($cdom) ne '') &&
                   4295:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4296:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4297:         my (%csvcols,%csvoptions);
                   4298:         if (ref($config->{'fields'}) eq 'HASH') {
                   4299:             %csvcols = %{$config->{'fields'}};
                   4300:         }
                   4301:         if (ref($config->{'options'}) eq 'HASH') {
                   4302:             %csvoptions = %{$config->{'options'}};
                   4303:         }
                   4304:         my %csvbynum = reverse(%csvcols);
                   4305:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4306:         if (keys(%scantronconf)) {
                   4307:             my %bynum = (
                   4308:                           $scantronconf{CODEstart} => 'CODEstart',
                   4309:                           $scantronconf{IDstart}   => 'IDstart',
                   4310:                           $scantronconf{PaperID}   => 'PaperID',
                   4311:                           $scantronconf{FirstName} => 'FirstName',
                   4312:                           $scantronconf{LastName}  => 'LastName',
                   4313:                           $scantronconf{Qstart}    => 'Qstart',
                   4314:                         );
                   4315:             my @ordered;
                   4316:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4317:                 push(@ordered,$bynum{$item});
                   4318:             }
                   4319:             my %mapstart = (
                   4320:                               CODEstart => 'CODE',
                   4321:                               IDstart   => 'ID',
                   4322:                               PaperID   => 'PaperID',
                   4323:                               FirstName => 'FirstName',
                   4324:                               LastName  => 'LastName',
                   4325:                               Qstart    => 'FirstQuestion',
                   4326:                            );
                   4327:             my %maplength = (
                   4328:                               CODEstart => 'CODElength',
                   4329:                               IDstart   => 'IDlength',
                   4330:                               PaperID   => 'PaperIDlength',
                   4331:                               FirstName => 'FirstNamelength',
                   4332:                               LastName  => 'LastNamelength',
                   4333:             );
                   4334:             if (open(my $fh,'<',$fullpath)) {
                   4335:                 my $output;
                   4336:                 my %lettdig = &letter_to_digits();
                   4337:                 my %diglett = reverse(%lettdig);
                   4338:                 my $numletts = scalar(keys(%lettdig));
                   4339:                 my $num = 0;
                   4340:                 while (my $line=<$fh>) {
                   4341:                     $num ++;
                   4342:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4343:                     $line =~ s{[\r\n]+$}{};
                   4344:                     my %found;
                   4345:                     my @values = split(/,/,$line);
                   4346:                     my ($qstart,$record);
                   4347:                     for (my $i=0; $i<@values; $i++) {
                   4348:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4349:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4350:                             if ($values[$i] eq '') {
                   4351:                                 $values[$i] = $scantronconf{'Qoff'};
                   4352:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4353:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4354:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4355:                                 }
                   4356:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4357:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4358:                                     $values[$i] = $diglett{$values[$i]};
                   4359:                                 }
                   4360:                             } else {
                   4361:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4362:                                     my $digit;
                   4363:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4364:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4365:                                         if ($values[$i] eq 'J') {
                   4366:                                             $digit += $numletts;
                   4367:                                         }
                   4368:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4369:                                         $digit = $values[$i]-1;
                   4370:                                         if ($values[$i] eq '0') {
                   4371:                                             $digit += $numletts;
                   4372:                                         }
                   4373:                                     }
                   4374:                                     my $qval='';
                   4375:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4376:                                         if ($j == $digit) {
                   4377:                                             $qval .= $scantronconf{'Qon'};
                   4378:                                         } else {
                   4379:                                             $qval .= $scantronconf{'Qoff'};
                   4380:                                         }
                   4381:                                     }
                   4382:                                     $values[$i] = $qval;
                   4383:                                 }
                   4384:                             }
                   4385:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4386:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4387:                             }
                   4388:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4389:                             if ($numblank > 0) {
                   4390:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4391:                             }
                   4392:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4393:                                 $qstart = $i;
                   4394:                                 $found{$csvbynum{$i}} = $values[$i];
                   4395:                             } else {
                   4396:                                 $found{'FirstQuestion'} .= $values[$i];
                   4397:                             }
                   4398:                         } elsif (exists($csvbynum{$i})) {
                   4399:                             if ($csvoptions{'rem'}) {
                   4400:                                 $values[$i] =~ s/^\s+//;
                   4401:                             }
                   4402:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4403:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4404:                                     $values[$i] = '0'.$values[$i];
                   4405:                                 }
                   4406:                             }
                   4407:                             $found{$csvbynum{$i}} = $values[$i];
                   4408:                         }
                   4409:                     }
                   4410:                     foreach my $item (@ordered) {
                   4411:                         my $currlength = 1+length($record);
                   4412:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4413:                         if ($numspaces > 0) {
                   4414:                             $record .= (' ' x $numspaces);
                   4415:                         }
                   4416:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4417:                             unless ($item eq 'Qstart') {
                   4418:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4419:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4420:                                 }
                   4421:                             }
                   4422:                             $record .= $found{$mapstart{$item}};
                   4423:                         }
                   4424:                     }
                   4425:                     $output .= "$record\n";
                   4426:                 }
                   4427:                 close($fh);
                   4428:                 if ($output) {
                   4429:                     if (open(my $fh,'>',$fullpath)) {
                   4430:                         print $fh $output;
                   4431:                         close($fh);
                   4432:                     }
                   4433:                 }
                   4434:             }
                   4435:         }
                   4436:         return;
                   4437:     }
                   4438: }
                   4439: 
                   4440: sub letter_to_digits {
                   4441:     my %lettdig = (
                   4442:                     A => 1,
                   4443:                     B => 2,
                   4444:                     C => 3,
                   4445:                     D => 4,
                   4446:                     E => 5,
                   4447:                     F => 6,
                   4448:                     G => 7,
                   4449:                     H => 8,
                   4450:                     I => 9,
                   4451:                     J => 0,
                   4452:                   );
                   4453:     return %lettdig;
                   4454: }
                   4455: 
                   4456: sub get_scantron_config {
                   4457:     my ($which,$cdom) = @_;
                   4458:     my @lines = &get_scantronformat_file($cdom);
                   4459:     my %config;
                   4460:     #FIXME probably should move to XML it has already gotten a bit much now
                   4461:     foreach my $line (@lines) {
                   4462:         my ($name,$descrip)=split(/:/,$line);
                   4463:         if ($name ne $which ) { next; }
                   4464:         chomp($line);
                   4465:         my @config=split(/:/,$line);
                   4466:         $config{'name'}=$config[0];
                   4467:         $config{'description'}=$config[1];
                   4468:         $config{'CODElocation'}=$config[2];
                   4469:         $config{'CODEstart'}=$config[3];
                   4470:         $config{'CODElength'}=$config[4];
                   4471:         $config{'IDstart'}=$config[5];
                   4472:         $config{'IDlength'}=$config[6];
                   4473:         $config{'Qstart'}=$config[7];
                   4474:         $config{'Qlength'}=$config[8];
                   4475:         $config{'Qoff'}=$config[9];
                   4476:         $config{'Qon'}=$config[10];
                   4477:         $config{'PaperID'}=$config[11];
                   4478:         $config{'PaperIDlength'}=$config[12];
                   4479:         $config{'FirstName'}=$config[13];
                   4480:         $config{'FirstNamelength'}=$config[14];
                   4481:         $config{'LastName'}=$config[15];
                   4482:         $config{'LastNamelength'}=$config[16];
                   4483:         $config{'BubblesPerRow'}=$config[17];
                   4484:         last;
                   4485:     }
                   4486:     return %config;
                   4487: }
                   4488: 
                   4489: sub get_scantronformat_file {
                   4490:     my ($cdom) = @_;
                   4491:     if ($cdom eq '') {
                   4492:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4493:     }
                   4494:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4495:     my $gottab = 0;
                   4496:     my @lines;
                   4497:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4498:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4499:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4500:             if ($formatfile ne '-1') {
                   4501:                 @lines = split("\n",$formatfile,-1);
                   4502:                 $gottab = 1;
                   4503:             }
                   4504:         }
                   4505:     }
                   4506:     if (!$gottab) {
                   4507:         my $confname = $cdom.'-domainconfig';
                   4508:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4509:         my $formatfile = &getfile($default);
                   4510:         if ($formatfile ne '-1') {
                   4511:             @lines = split("\n",$formatfile,-1);
                   4512:             $gottab = 1;
                   4513:         }
                   4514:     }
                   4515:     if (!$gottab) {
                   4516:         my @domains = &current_machine_domains();
                   4517:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4518:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4519:                 @lines = <$fh>;
                   4520:                 close($fh);
                   4521:             }
                   4522:         } else {
                   4523:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4524:                 @lines = <$fh>;
                   4525:                 close($fh);
                   4526:             }
                   4527:         }
                   4528:     }
                   4529:     return @lines;
                   4530: }
                   4531: 
1.493     albertel 4532: sub removeuploadedurl {
1.984     neumanie 4533:     my ($url)=@_;	
                   4534:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4535:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4536: }
                   4537: 
                   4538: sub removeuserfile {
                   4539:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4540:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4541:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4542:     if ($result eq 'ok') {	
1.798     raeburn  4543:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4544:             my $metafile = $fname.'.meta';
                   4545:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4546: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4547:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4548:             my $sqlresult = 
1.823     albertel 4549:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4550:                                         'portfolio_metadata',$group,
                   4551:                                         'delete');
1.798     raeburn  4552:         }
                   4553:     }
                   4554:     return $result;
1.257     www      4555: }
1.15      www      4556: 
1.530     albertel 4557: sub mkdiruserfile {
                   4558:     my ($docuname,$docudom,$dir)=@_;
                   4559:     my $home=&homeserver($docuname,$docudom);
                   4560:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4561: }
                   4562: 
1.531     albertel 4563: sub renameuserfile {
                   4564:     my ($docuname,$docudom,$old,$new)=@_;
                   4565:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4566:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4567:                         &escape("$old").':'.&escape("$new"),$home);
                   4568:     if ($result eq 'ok') {
                   4569:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4570:             my $oldmeta = $old.'.meta';
                   4571:             my $newmeta = $new.'.meta';
                   4572:             my $metaresult = 
                   4573:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4574: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4575:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4576:             my $sqlresult = 
1.823     albertel 4577:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4578:                                         'portfolio_metadata',$group,
                   4579:                                         'delete');
1.798     raeburn  4580:         }
                   4581:     }
                   4582:     return $result;
1.531     albertel 4583: }
                   4584: 
1.14      www      4585: # ------------------------------------------------------------------------- Log
                   4586: 
                   4587: sub log {
                   4588:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4589:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4590: }
                   4591: 
                   4592: # ------------------------------------------------------------------ Course Log
1.352     www      4593: #
                   4594: # This routine flushes several buffers of non-mission-critical nature
                   4595: #
1.157     www      4596: 
                   4597: sub flushcourselogs {
1.352     www      4598:     &logthis('Flushing log buffers');
                   4599: #
                   4600: # course logs
                   4601: # This is a log of all transactions in a course, which can be used
                   4602: # for data mining purposes
                   4603: #
                   4604: # It also collects the courseid database, which lists last transaction
                   4605: # times and course titles for all courseids
                   4606: #
                   4607:     my %courseidbuffer=();
1.921     raeburn  4608:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4609:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4610: 		          &escape($courselogs{$crsid}),
                   4611: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4612: 	    delete $courselogs{$crsid};
                   4613:         } else {
                   4614:             &logthis('Failed to flush log buffer for '.$crsid);
                   4615:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4616:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4617:                         " exceeded maximum size, deleting.</font>");
                   4618:                delete $courselogs{$crsid};
                   4619:             }
1.352     www      4620:         }
1.920     raeburn  4621:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4622:             'description' => $coursedescrbuf{$crsid},
                   4623:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4624:             'type'        => $coursetypebuf{$crsid},
                   4625:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4626:         };
1.191     harris41 4627:     }
1.352     www      4628: #
                   4629: # Write course id database (reverse lookup) to homeserver of courses 
                   4630: # Is used in pickcourse
                   4631: #
1.840     albertel 4632:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4633:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4634:                                     $courseidbuffer{$crs_home},
                   4635:                                     $crs_home,'timeonly');
1.352     www      4636:     }
                   4637: #
                   4638: # File accesses
                   4639: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4640: #
1.449     matthew  4641:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4642:         if ($entry =~ /___count$/) {
                   4643:             my ($dom,$name);
1.807     albertel 4644:             ($dom,$name,undef)=
1.811     albertel 4645: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4646:             if (! defined($dom) || $dom eq '' || 
                   4647:                 ! defined($name) || $name eq '') {
1.620     albertel 4648:                 my $cid = $env{'request.course.id'};
                   4649:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4650:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4651:             }
1.450     matthew  4652:             my $value = $accesshash{$entry};
                   4653:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4654:             my %temphash=($url => $value);
1.449     matthew  4655:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4656:             if ($result eq 'ok') {
                   4657:                 delete $accesshash{$entry};
                   4658:             }
                   4659:         } else {
1.811     albertel 4660:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4661:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4662:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4663:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4664:                 delete $accesshash{$entry};
                   4665:             }
1.185     www      4666:         }
1.191     harris41 4667:     }
1.352     www      4668: #
                   4669: # Roles
                   4670: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4671: #
1.800     albertel 4672:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4673:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4674: 	    split(/\:/,$entry);
                   4675:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4676:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4677:                 $rudom,$runame) eq 'ok') {
                   4678: 	    delete $userrolehash{$entry};
                   4679:         }
                   4680:     }
1.662     raeburn  4681: #
1.1172.2.90  raeburn  4682: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4683: #
                   4684:     my %domrolebuffer = ();
1.1000    raeburn  4685:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4686:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4687:         if ($domrolebuffer{$rudom}) {
                   4688:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4689:                       '='.&escape($domainrolehash{$entry});
                   4690:         } else {
                   4691:             $domrolebuffer{$rudom}.=&escape($entry).
                   4692:                       '='.&escape($domainrolehash{$entry});
                   4693:         }
                   4694:         delete $domainrolehash{$entry};
                   4695:     }
                   4696:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4697:         my %servers;
                   4698:         if (defined(&domain($dom,'primary'))) {
                   4699:             my $primary=&domain($dom,'primary');
                   4700:             my $hostname=&hostname($primary);
                   4701:             $servers{$primary} = $hostname;
                   4702:         } else {
                   4703:             %servers = &get_servers($dom,'library');
                   4704:         }
1.841     albertel 4705: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4706: 	    if (&reply('domroleput:'.$dom.':'.
                   4707: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4708: 	        last;
                   4709: 	    } else {
1.841     albertel 4710: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4711: 	    }
1.662     raeburn  4712:         }
                   4713:     }
1.186     www      4714:     $dumpcount++;
1.157     www      4715: }
                   4716: 
                   4717: sub courselog {
                   4718:     my $what=shift;
1.158     www      4719:     $what=time.':'.$what;
1.620     albertel 4720:     unless ($env{'request.course.id'}) { return ''; }
                   4721:     $coursedombuf{$env{'request.course.id'}}=
                   4722:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4723:     $coursenumbuf{$env{'request.course.id'}}=
                   4724:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4725:     $coursehombuf{$env{'request.course.id'}}=
                   4726:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4727:     $coursedescrbuf{$env{'request.course.id'}}=
                   4728:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4729:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4730:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4731:     $courseownerbuf{$env{'request.course.id'}}=
                   4732:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4733:     $coursetypebuf{$env{'request.course.id'}}=
                   4734:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4735:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4736: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4737:     } else {
1.620     albertel 4738: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4739:     }
1.620     albertel 4740:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4741: 	&flushcourselogs();
                   4742:     }
1.158     www      4743: }
                   4744: 
                   4745: sub courseacclog {
                   4746:     my $fnsymb=shift;
1.620     albertel 4747:     unless ($env{'request.course.id'}) { return ''; }
                   4748:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4749:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4750:         $what.=':POST';
1.583     matthew  4751:         # FIXME: Probably ought to escape things....
1.800     albertel 4752: 	foreach my $key (keys(%env)) {
                   4753:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4754:                 my $formitem = $1;
                   4755:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4756:                     $what.=':'.$formitem.'='.$env{$key};
                   4757:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.118.  .12(raeb 4758:-20):                     if ($formitem eq 'proctorpassword') {
                   4759:-20):                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
                   4760:-20):                     } else {
                   4761:-20):                         $what.=':'.$formitem.'='.$env{$key};
                   4762:-20):                     }
1.975     raeburn  4763:                 }
1.158     www      4764:             }
1.191     harris41 4765:         }
1.583     matthew  4766:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4767:         # FIXME: We should not be depending on a form parameter that someone
                   4768:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4769:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4770:             $what.= ':POST';
                   4771:             # FIXME: Probably ought to escape things....
                   4772:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4773:                                  'crsdiscuss') {
1.620     albertel 4774:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4775:             }
                   4776:         }
1.158     www      4777:     }
                   4778:     &courselog($what);
1.149     www      4779: }
                   4780: 
1.185     www      4781: sub countacc {
                   4782:     my $url=&declutter(shift);
1.458     matthew  4783:     return if (! defined($url) || $url eq '');
1.620     albertel 4784:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4785: #
                   4786: # Mark that this url was used in this course
                   4787: #
1.620     albertel 4788:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4789: #
                   4790: # Increase the access count for this resource in this child process
                   4791: #
1.281     www      4792:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4793:     $accesshash{$key}++;
1.185     www      4794: }
1.349     www      4795: 
1.361     www      4796: sub linklog {
                   4797:     my ($from,$to)=@_;
                   4798:     $from=&declutter($from);
                   4799:     $to=&declutter($to);
                   4800:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4801:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4802: }
1.1160    www      4803: 
                   4804: sub statslog {
                   4805:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4806:     if ($users<2) { return; }
                   4807:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4808:             'course'       => $env{'request.course.id'},
                   4809:             'sections'     => '"all"',
                   4810:             'num_students' => $users,
                   4811:             'part'         => $part,
                   4812:             'symb'         => $symb,
                   4813:             'mean_tries'   => $av_attempts,
                   4814:             'deg_of_diff'  => $degdiff});
                   4815:     foreach my $key (keys(%dynstore)) {
                   4816:         $accesshash{$key}=$dynstore{$key};
                   4817:     }
                   4818: }
1.361     www      4819:   
1.349     www      4820: sub userrolelog {
                   4821:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4822:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4823:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4824:        $userrolehash
                   4825:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4826:                     =$tend.':'.$tstart;
1.662     raeburn  4827:     }
1.1169    droeschl 4828:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4829:        $userrolehash
                   4830:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4831:                     =$tend.':'.$tstart;
                   4832:     }
1.1172.2.90  raeburn  4833:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4834:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4835:        $domainrolehash
                   4836:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4837:                     = $tend.':'.$tstart;
                   4838:     }
1.351     www      4839: }
                   4840: 
1.957     raeburn  4841: sub courserolelog {
                   4842:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4843:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4844:         my $cdom = $1;
                   4845:         my $cnum = $2;
                   4846:         my $sec = $3;
                   4847:         my $namespace = 'rolelog';
                   4848:         my %storehash = (
                   4849:                            role    => $trole,
                   4850:                            start   => $tstart,
                   4851:                            end     => $tend,
                   4852:                            selfenroll => $selfenroll,
                   4853:                            context    => $context,
                   4854:                         );
                   4855:         if ($trole eq 'gr') {
                   4856:             $namespace = 'groupslog';
                   4857:             $storehash{'group'} = $sec;
                   4858:         } else {
                   4859:             $storehash{'section'} = $sec;
                   4860:         }
                   4861:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4862:                    $domain,$cnum,$cdom);
                   4863:         if (($trole ne 'st') || ($sec ne '')) {
                   4864:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4865:         }
                   4866:     }
                   4867:     return;
                   4868: }
                   4869: 
1.1172.2.9  raeburn  4870: sub domainrolelog {
                   4871:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4872:     if ($area =~ m{^/($match_domain)/$}) {
                   4873:         my $cdom = $1;
                   4874:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4875:         my $namespace = 'rolelog';
                   4876:         my %storehash = (
                   4877:                            role    => $trole,
                   4878:                            start   => $tstart,
                   4879:                            end     => $tend,
                   4880:                            context => $context,
                   4881:                         );
                   4882:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4883:                    $domain,$domconfiguser,$cdom);
                   4884:     }
                   4885:     return;
                   4886: 
                   4887: }
                   4888: 
                   4889: sub coauthorrolelog {
                   4890:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4891:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4892:         my $audom = $1;
                   4893:         my $auname = $2;
                   4894:         my $namespace = 'rolelog';
                   4895:         my %storehash = (
                   4896:                            role    => $trole,
                   4897:                            start   => $tstart,
                   4898:                            end     => $tend,
                   4899:                            context => $context,
                   4900:                         );
                   4901:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4902:                    $domain,$auname,$audom);
                   4903:     }
                   4904:     return;
                   4905: }
                   4906: 
1.351     www      4907: sub get_course_adv_roles {
1.948     raeburn  4908:     my ($cid,$codes) = @_;
1.620     albertel 4909:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4910:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4911:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4912:     my %nothide=();
1.800     albertel 4913:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4914:         if ($user !~ /:/) {
                   4915: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4916:         } else {
                   4917:             $nothide{$user}=1;
                   4918:         }
1.470     www      4919:     }
1.1172.2.23  raeburn  4920:     my @possdoms = ($coursehash{'domain'});
                   4921:     if ($coursehash{'checkforpriv'}) {
                   4922:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4923:     }
1.351     www      4924:     my %returnhash=();
                   4925:     my %dumphash=
                   4926:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4927:     my $now=time;
1.997     raeburn  4928:     my %privileged;
1.1000    raeburn  4929:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4930: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4931:         if (($tstart) && ($tstart<0)) { next; }
                   4932:         if (($tend) && ($tend<$now)) { next; }
                   4933:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4934:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4935: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4936:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4937:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4938: 	if ($role eq 'cr') { next; }
1.948     raeburn  4939:         if ($codes) {
                   4940:             if ($section) { $role .= ':'.$section; }
                   4941:             if ($returnhash{$role}) {
                   4942:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4943:             } else {
                   4944:                 $returnhash{$role}=$username.':'.$domain;
                   4945:             }
1.351     www      4946:         } else {
1.988     raeburn  4947:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4948:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4949:             if ($returnhash{$key}) {
                   4950: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4951:             } else {
                   4952:                 $returnhash{$key}=$username.':'.$domain;
                   4953:             }
1.351     www      4954:         }
1.948     raeburn  4955:     }
1.400     www      4956:     return %returnhash;
                   4957: }
                   4958: 
                   4959: sub get_my_roles {
1.937     raeburn  4960:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4961:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4962:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4963:     my (%dumphash,%nothide);
1.1086    raeburn  4964:     if ($context eq 'userroles') {
1.1166    raeburn  4965:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4966:     } else {
1.1172.2.23  raeburn  4967:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4968:         if ($hidepriv) {
                   4969:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4970:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4971:                 if ($user !~ /:/) {
                   4972:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4973:                 } else {
                   4974:                     $nothide{$user} = 1;
                   4975:                 }
                   4976:             }
                   4977:         }
1.858     raeburn  4978:     }
1.400     www      4979:     my %returnhash=();
                   4980:     my $now=time;
1.999     raeburn  4981:     my %privileged;
1.800     albertel 4982:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4983:         my ($role,$tend,$tstart);
                   4984:         if ($context eq 'userroles') {
1.1149    raeburn  4985:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4986: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4987:         } else {
                   4988:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4989:         }
1.400     www      4990:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4991:         my $status = 'active';
1.939     raeburn  4992:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4993:             $status = 'previous';
                   4994:         } 
                   4995:         if (($tstart) && ($now<$tstart)) {
                   4996:             $status = 'future';
                   4997:         }
                   4998:         if (ref($types) eq 'ARRAY') {
                   4999:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5000:                 next;
                   5001:             } 
                   5002:         } else {
                   5003:             if ($status ne 'active') {
                   5004:                 next;
                   5005:             }
                   5006:         }
1.867     raeburn  5007:         my ($rolecode,$username,$domain,$section,$area);
                   5008:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5009:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5010:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5011:         } else {
                   5012:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5013:         }
1.832     raeburn  5014:         if (ref($roledoms) eq 'ARRAY') {
                   5015:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5016:                 next;
                   5017:             }
                   5018:         }
                   5019:         if (ref($roles) eq 'ARRAY') {
                   5020:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5021:                 if ($role =~ /^cr\//) {
                   5022:                     if (!grep(/^cr$/,@{$roles})) {
                   5023:                         next;
                   5024:                     }
1.1104    raeburn  5025:                 } elsif ($role =~ /^gr\//) {
                   5026:                     if (!grep(/^gr$/,@{$roles})) {
                   5027:                         next;
                   5028:                     }
1.922     raeburn  5029:                 } else {
                   5030:                     next;
                   5031:                 }
1.832     raeburn  5032:             }
1.867     raeburn  5033:         }
1.937     raeburn  5034:         if ($hidepriv) {
1.1172.2.23  raeburn  5035:             my @privroles = ('dc','su');
1.999     raeburn  5036:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5037:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5038:             } else {
1.1172.2.23  raeburn  5039:                 my $possdoms = [$domain];
                   5040:                 if (ref($roledoms) eq 'ARRAY') {
                   5041:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5042:                 }
1.1172.2.23  raeburn  5043:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5044:                     if (!$nothide{$username.':'.$domain}) {
                   5045:                         next;
                   5046:                     }
                   5047:                 }
1.937     raeburn  5048:             }
                   5049:         }
1.933     raeburn  5050:         if ($withsec) {
                   5051:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5052:                 $tstart.':'.$tend;
                   5053:         } else {
                   5054:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5055:         }
1.832     raeburn  5056:     }
1.373     www      5057:     return %returnhash;
1.399     www      5058: }
                   5059: 
1.1172.2.89  raeburn  5060: sub get_all_adhocroles {
                   5061:     my ($dom) = @_;
                   5062:     my @roles_by_num = ();
                   5063:     my %domdefaults = &get_domain_defaults($dom);
                   5064:     my (%description,%access_in_dom,%access_info);
                   5065:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5066:         my $count = 0;
                   5067:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5068:         my %ordered;
                   5069:         foreach my $role (sort(keys(%domcurrent))) {
                   5070:             my ($order,$desc,$access_in_dom);
                   5071:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5072:                 $order = $domcurrent{$role}{'order'};
                   5073:                 $desc = $domcurrent{$role}{'desc'};
                   5074:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5075:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5076:             }
                   5077:             if ($order eq '') {
                   5078:                 $order = $count;
                   5079:             }
                   5080:             $ordered{$order} = $role;
                   5081:             if ($desc ne '') {
                   5082:                 $description{$role} = $desc;
                   5083:             } else {
                   5084:                 $description{$role}= $role;
                   5085:             }
                   5086:             $count++;
                   5087:         }
                   5088:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5089:             push(@roles_by_num,$ordered{$item});
                   5090:         }
                   5091:     }
                   5092:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5093: }
                   5094: 
                   5095: sub get_my_adhocroles {
                   5096:     my ($cid,$checkreg) = @_;
                   5097:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5098:     if ($env{'request.course.id'} eq $cid) {
                   5099:         $cdom = $env{'course.'.$cid.'.domain'};
                   5100:         $cnum = $env{'course.'.$cid.'.num'};
                   5101:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5102:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5103:         $cdom = $1;
                   5104:         $cnum = $2;
                   5105:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5106:                                      $cdom,$cnum);
                   5107:     }
                   5108:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5109:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5110:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5111:         if ($rosterhash{$user} ne '') {
                   5112:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5113:             return ([],{}) if ($type eq 'auto');
                   5114:         }
                   5115:     }
                   5116:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5117:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5118:             my $then=$env{'user.login.time'};
                   5119:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5120:             if (!$update) {
                   5121:                 $update = $then;
                   5122:             }
                   5123:             my @liveroles;
                   5124:             foreach my $role ('dh','da') {
                   5125:                 if ($env{"user.role.$role./$cdom/"}) {
                   5126:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5127:                     my $limit = $update;
                   5128:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5129:                         $limit = $then;
                   5130:                     }
                   5131:                     my $activerole = 1;
                   5132:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5133:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5134:                     if ($activerole) {
                   5135:                         push(@liveroles,$role);
                   5136:                     }
                   5137:                 }
                   5138:             }
                   5139:             if (@liveroles) {
1.1172.2.89  raeburn  5140:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5141:                     my ($accessref,$accessinfo,%access_in_dom);
                   5142:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5143:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5144:                         if (@{$roles_by_num}) {
                   5145:                             my %settings;
                   5146:                             if ($env{'request.course.id'} eq $cid) {
                   5147:                                 foreach my $envkey (keys(%env)) {
                   5148:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5149:                                         $settings{$1} = $env{$envkey};
                   5150:                                     }
                   5151:                                 }
                   5152:                             } else {
                   5153:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5154:                             }
                   5155:                             my %setincrs;
                   5156:                             if ($settings{'internal.adhocaccess'}) {
                   5157:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5158:                             }
                   5159:                             my @statuses;
                   5160:                             if ($env{'environment.inststatus'}) {
                   5161:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5162:                             }
                   5163:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5164:                             if (ref($accessref) eq 'HASH') {
                   5165:                                 %access_in_dom = %{$accessref};
                   5166:                             }
                   5167:                             foreach my $role (@{$roles_by_num}) {
                   5168:                                 my ($curraccess,@okstatus,@personnel);
                   5169:                                 if ($setincrs{$role}) {
                   5170:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5171:                                     if ($curraccess eq 'status') {
                   5172:                                         @okstatus = split(/\&/,$rest);
                   5173:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5174:                                         @personnel = split(/\&/,$rest);
                   5175:                                     }
                   5176:                                 } else {
                   5177:                                     $curraccess = $access_in_dom{$role};
                   5178:                                     if (ref($accessinfo) eq 'HASH') {
                   5179:                                         if ($curraccess eq 'status') {
                   5180:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5181:                                                 @okstatus = @{$accessinfo->{$role}};
                   5182:                                             }
                   5183:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5184:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5185:                                                 @personnel = @{$accessinfo->{$role}};
                   5186:                                             }
                   5187:                                         }
                   5188:                                     }
                   5189:                                 }
                   5190:                                 if ($curraccess eq 'none') {
                   5191:                                     next;
                   5192:                                 } elsif ($curraccess eq 'all') {
                   5193:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5194:                                 } elsif ($curraccess eq 'dh') {
                   5195:                                     if (grep(/^dh$/,@liveroles)) {
                   5196:                                         push(@possroles,$role);
                   5197:                                     } else {
                   5198:                                         next;
                   5199:                                     }
                   5200:                                 } elsif ($curraccess eq 'da') {
                   5201:                                     if (grep(/^da$/,@liveroles)) {
                   5202:                                         push(@possroles,$role);
                   5203:                                     } else {
                   5204:                                         next;
                   5205:                                     }
1.1172.2.89  raeburn  5206:                                 } elsif ($curraccess eq 'status') {
                   5207:                                     if (@okstatus) {
                   5208:                                         if (!@statuses) {
                   5209:                                             if (grep(/^default$/,@okstatus)) {
                   5210:                                                 push(@possroles,$role);
                   5211:                                             }
                   5212:                                         } else {
                   5213:                                             foreach my $status (@okstatus) {
                   5214:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5215:                                                     push(@possroles,$role);
                   5216:                                                     last;
                   5217:                                                 }
                   5218:                                             }
                   5219:                                         }
                   5220:                                     }
                   5221:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5222:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5223:                                         if ($curraccess eq 'exc') {
                   5224:                                             push(@possroles,$role);
                   5225:                                         }
                   5226:                                     } elsif ($curraccess eq 'inc') {
                   5227:                                         push(@possroles,$role);
                   5228:                                     }
                   5229:                                 }
                   5230:                             }
                   5231:                         }
                   5232:                     }
                   5233:                 }
                   5234:             }
                   5235:         }
                   5236:     }
                   5237:     unless (ref($description) eq 'HASH') {
                   5238:         if (ref($roles_by_num) eq 'ARRAY') {
                   5239:             my %desc;
                   5240:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5241:             $description = \%desc;
                   5242:         } else {
                   5243:             $description = {};
                   5244:         }
                   5245:     }
                   5246:     return (\@possroles,$description);
                   5247: }
                   5248: 
1.399     www      5249: # ----------------------------------------------------- Frontpage Announcements
                   5250: #
                   5251: #
                   5252: 
                   5253: sub postannounce {
                   5254:     my ($server,$text)=@_;
1.844     albertel 5255:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5256:     unless ($text=~/\w/) { $text=''; }
                   5257:     return &reply('setannounce:'.&escape($text),$server);
                   5258: }
                   5259: 
                   5260: sub getannounce {
1.448     albertel 5261: 
1.1172.2.96  raeburn  5262:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5263: 	my $announcement='';
1.800     albertel 5264: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5265: 	close($fh);
1.399     www      5266: 	if ($announcement=~/\w/) { 
                   5267: 	    return 
                   5268:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5269:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5270: 	} else {
                   5271: 	    return '';
                   5272: 	}
                   5273:     } else {
                   5274: 	return '';
                   5275:     }
1.351     www      5276: }
1.353     www      5277: 
                   5278: # ---------------------------------------------------------- Course ID routines
                   5279: # Deal with domain's nohist_courseid.db files
                   5280: #
                   5281: 
                   5282: sub courseidput {
1.921     raeburn  5283:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5284:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5285:     my $outcome;
                   5286:     if ($caller eq 'timeonly') {
                   5287:         my $cids = '';
                   5288:         foreach my $item (keys(%$storehash)) {
                   5289:             $cids.=&escape($item).'&';
                   5290:         }
                   5291:         $cids=~s/\&$//;
                   5292:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5293:                           $coursehome);       
                   5294:     } else {
                   5295:         my $items = '';
                   5296:         foreach my $item (keys(%$storehash)) {
                   5297:             $items.= &escape($item).'='.
                   5298:                      &freeze_escape($$storehash{$item}).'&';
                   5299:         }
                   5300:         $items=~s/\&$//;
                   5301:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5302:                           $coursehome);
1.918     raeburn  5303:     }
                   5304:     if ($outcome eq 'unknown_cmd') {
                   5305:         my $what;
                   5306:         foreach my $cid (keys(%$storehash)) {
                   5307:             $what .= &escape($cid).'=';
1.921     raeburn  5308:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5309:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5310:             }
                   5311:             $what =~ s/\:$/&/;
                   5312:         }
                   5313:         $what =~ s/\&$//;  
                   5314:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5315:     } else {
                   5316:         return $outcome;
                   5317:     }
1.353     www      5318: }
                   5319: 
                   5320: sub courseiddump {
1.921     raeburn  5321:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5322:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5323:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5324:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5325:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5326:     my $as_hash = 1;
                   5327:     my %returnhash;
                   5328:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5329:     my %libserv = &all_library();
                   5330:     foreach my $tryserver (keys(%libserv)) {
                   5331:         if ( (  $hostidflag == 1 
                   5332: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5333: 	     || (!defined($hostidflag)) ) {
                   5334: 
1.918     raeburn  5335: 	    if (($domfilter eq '') ||
                   5336: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5337:                 my $rep;
                   5338:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5339:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5340:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5341:                                 &escape($descfilter), &escape($instcodefilter),
                   5342:                                 &escape($ownerfilter), &escape($coursefilter),
                   5343:                                 &escape($typefilter), &escape($regexp_ok),
                   5344:                                 $as_hash, &escape($selfenrollonly),
                   5345:                                 &escape($catfilter), $showhidden, $caller,
                   5346:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5347:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5348:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5349:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5350:                 } else {
                   5351:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5352:                              $sincefilter.':'.&escape($descfilter).':'.
                   5353:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5354:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5355:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5356:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5357:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5358:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5359:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5360:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5361:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5362:                 }
                   5363: 
1.918     raeburn  5364:                 my @pairs=split(/\&/,$rep);
                   5365:                 foreach my $item (@pairs) {
                   5366:                     my ($key,$value)=split(/\=/,$item,2);
                   5367:                     $key = &unescape($key);
                   5368:                     next if ($key =~ /^error: 2 /);
                   5369:                     my $result = &thaw_unescape($value);
                   5370:                     if (ref($result) eq 'HASH') {
                   5371:                         $returnhash{$key}=$result;
                   5372:                     } else {
1.921     raeburn  5373:                         my @responses = split(/:/,$value);
                   5374:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5375:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5376:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5377:                         }
1.1008    raeburn  5378:                     }
1.353     www      5379:                 }
                   5380:             }
                   5381:         }
                   5382:     }
                   5383:     return %returnhash;
                   5384: }
                   5385: 
1.1055    raeburn  5386: sub courselastaccess {
                   5387:     my ($cdom,$cnum,$hostidref) = @_;
                   5388:     my %returnhash;
                   5389:     if ($cdom && $cnum) {
                   5390:         my $chome = &homeserver($cnum,$cdom);
                   5391:         if ($chome ne 'no_host') {
                   5392:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5393:             &extract_lastaccess(\%returnhash,$rep);
                   5394:         }
                   5395:     } else {
                   5396:         if (!$cdom) { $cdom=''; }
                   5397:         my %libserv = &all_library();
                   5398:         foreach my $tryserver (keys(%libserv)) {
                   5399:             if (ref($hostidref) eq 'ARRAY') {
                   5400:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5401:             } 
                   5402:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5403:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5404:                 &extract_lastaccess(\%returnhash,$rep);
                   5405:             }
                   5406:         }
                   5407:     }
                   5408:     return %returnhash;
                   5409: }
                   5410: 
                   5411: sub extract_lastaccess {
                   5412:     my ($returnhash,$rep) = @_;
                   5413:     if (ref($returnhash) eq 'HASH') {
                   5414:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5415:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5416:                  $rep eq '') {
                   5417:             my @pairs=split(/\&/,$rep);
                   5418:             foreach my $item (@pairs) {
                   5419:                 my ($key,$value)=split(/\=/,$item,2);
                   5420:                 $key = &unescape($key);
                   5421:                 next if ($key =~ /^error: 2 /);
                   5422:                 $returnhash->{$key} = &thaw_unescape($value);
                   5423:             }
                   5424:         }
                   5425:     }
                   5426:     return;
                   5427: }
                   5428: 
1.658     raeburn  5429: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5430: 
                   5431: sub dcmailput {
1.685     raeburn  5432:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5433:     my $status = &Apache::lonnet::critical(
1.740     www      5434:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5435:        &escape($message),$server);
1.662     raeburn  5436:     return $status;
                   5437: }
                   5438: 
1.658     raeburn  5439: sub dcmaildump {
                   5440:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5441:     my %returnhash=();
1.846     albertel 5442: 
                   5443:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5444:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5445:                                                          &escape($enddate).':';
                   5446: 	my @esc_senders=map { &escape($_)} @$senders;
                   5447: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5448: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5449:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5450:             if (($key) && ($value)) {
                   5451:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5452:             }
                   5453:         }
                   5454:     }
                   5455:     return %returnhash;
                   5456: }
1.662     raeburn  5457: # ---------------------------------------------------------- Domain roles
                   5458: 
                   5459: sub get_domain_roles {
                   5460:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5461:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5462:         $startdate = '.';
                   5463:     }
1.1018    raeburn  5464:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5465:         $enddate = '.';
                   5466:     }
1.922     raeburn  5467:     my $rolelist;
                   5468:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5469:         $rolelist = join('&',@{$roles});
1.922     raeburn  5470:     }
1.662     raeburn  5471:     my %personnel = ();
1.841     albertel 5472: 
                   5473:     my %servers = &get_servers($dom,'library');
                   5474:     foreach my $tryserver (keys(%servers)) {
                   5475: 	%{$personnel{$tryserver}}=();
                   5476: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5477: 					    &escape($startdate).':'.
                   5478: 					    &escape($enddate).':'.
                   5479: 					    &escape($rolelist), $tryserver))) {
                   5480: 	    my ($key,$value) = split(/\=/,$line,2);
                   5481: 	    if (($key) && ($value)) {
                   5482: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5483: 	    }
                   5484: 	}
1.662     raeburn  5485:     }
                   5486:     return %personnel;
                   5487: }
1.658     raeburn  5488: 
1.1172.2.89  raeburn  5489: sub get_active_domroles {
                   5490:     my ($dom,$roles) = @_;
                   5491:     return () unless (ref($roles) eq 'ARRAY');
                   5492:     my $now = time;
                   5493:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5494:     my %domroles;
                   5495:     foreach my $server (keys(%dompersonnel)) {
                   5496:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5497:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5498:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5499:         }
                   5500:     }
                   5501:     return %domroles;
                   5502: }
                   5503: 
1.1057    www      5504: # ----------------------------------------------------------- Interval timing 
1.149     www      5505: 
1.1153    www      5506: {
                   5507: # Caches needed for speedup of navmaps
                   5508: # We don't want to cache this for very long at all (5 seconds at most)
                   5509: # 
                   5510: # The user for whom we cache
                   5511: my $cachedkey='';
                   5512: # The cached times for this user
                   5513: my %cachedtimes=();
                   5514: # When this was last done
1.1172.2.66  raeburn  5515: my $cachedtime='';
1.1153    www      5516: 
                   5517: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5518:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5519:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5520:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5521:20):         (!$ignorecache)) {
1.1154    raeburn  5522:         return;
                   5523:     }
                   5524:     $cachedtime=time;
                   5525:     $cachedkey=$uname.':'.$udom;
                   5526:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5527: }
                   5528: 
1.504     albertel 5529: sub get_first_access {
1.1172.2.118.  .1(raebu 5530:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5531:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5532:     if ($argsymb) { $symb=$argsymb; }
                   5533:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5534:     if ($argmap) { $map = $argmap; }
1.926     albertel 5535:     if ($type eq 'course') {
                   5536: 	$res='course';
                   5537:     } elsif ($type eq 'map') {
1.588     albertel 5538: 	$res=&symbread($map);
                   5539:     } else {
                   5540: 	$res=$symb;
                   5541:     }
1.1172.2.118.  .1(raebu 5542:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5543:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5544: }
                   5545: 
                   5546: sub set_first_access {
1.1162    raeburn  5547:     my ($type,$interval)=@_;
1.790     albertel 5548:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5549:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5550:     if ($type eq 'course') {
                   5551: 	$res='course';
                   5552:     } elsif ($type eq 'map') {
1.588     albertel 5553: 	$res=&symbread($map);
                   5554:     } else {
                   5555: 	$res=$symb;
                   5556:     }
1.1153    www      5557:     $cachedkey='';
1.1162    raeburn  5558:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5559:     if ($firstaccess) {
                   5560:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5561:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5562:                  "in $courseid");
                   5563:         return 'already_set';
                   5564:     } else {
1.1162    raeburn  5565:         my $start = time;
                   5566: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5567:                           $udom,$uname);
                   5568:         if ($putres eq 'ok') {
                   5569:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5570:                  $udom,$uname); 
                   5571:             &appenv(
                   5572:                      {
                   5573:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5574:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5575:                      }
                   5576:                   );
1.1172.2.97  raeburn  5577:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5578:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5579:             }
1.1172.2.102  raeburn  5580:         } elsif ($putres ne 'refused') {
                   5581:             &logthis("Result: $putres when attempting to set first access time ".
                   5582:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5583:         }
                   5584:         return $putres;
1.505     albertel 5585:     }
                   5586:     return 'already_set';
1.504     albertel 5587: }
1.1153    www      5588: }
1.1172.2.32  raeburn  5589: 
                   5590: sub checkout {
                   5591:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5592:     my $now=time;
                   5593:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.118.  .14(raeb 5594:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5595:     my $infostr=&escape(
                   5596:                  'CHECKOUTTOKEN&'.
                   5597:                  $tuname.'&'.
                   5598:                  $tudom.'&'.
                   5599:                  $tcrsid.'&'.
                   5600:                  $symb.'&'.
1.1172.2.118.  .14(raeb 5601:-21):                  $now.'&'.$ip);
1.1172.2.32  raeburn  5602:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5603:     if ($token=~/^error\:/) {
                   5604:         &logthis("<font color=\"blue\">WARNING: ".
                   5605:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5606:                  "</font>");
                   5607:         return '';
                   5608:     }
                   5609: 
                   5610:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5611:     $token=~tr/a-z/A-Z/;
                   5612: 
                   5613:     my %infohash=('resource.0.outtoken' => $token,
                   5614:                   'resource.0.checkouttime' => $now,
1.1172.2.118.  .14(raeb 5615:-21):                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5616: 
                   5617:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5618:        return '';
                   5619:     } else {
                   5620:         &logthis("<font color=\"blue\">WARNING: ".
                   5621:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5622:                  "</font>");
                   5623:     }
                   5624: 
                   5625:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5626:                          &escape('Checkout '.$infostr.' - '.
                   5627:                                                  $token)) ne 'ok') {
                   5628:         return '';
                   5629:     } else {
                   5630:         &logthis("<font color=\"blue\">WARNING: ".
                   5631:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5632:                  "</font>");
                   5633:     }
                   5634:     return $token;
                   5635: }
                   5636: 
                   5637: # ------------------------------------------------------------ Check in an item
                   5638: 
                   5639: sub checkin {
                   5640:     my $token=shift;
                   5641:     my $now=time;
                   5642:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5643:     $lonhost=~tr/A-Z/a-z/;
                   5644:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5645:     $dtoken=~s/\W/\_/g;
1.1172.2.118.  .14(raeb 5646:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5647:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5648:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5649: 
                   5650:     unless (($tuname) && ($tudom)) {
                   5651:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5652:         return '';
                   5653:     }
                   5654: 
                   5655:     unless (&allowed('mgr',$tcrsid)) {
                   5656:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5657:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5658:         return '';
                   5659:     }
                   5660: 
                   5661:     my %infohash=('resource.0.intoken' => $token,
                   5662:                   'resource.0.checkintime' => $now,
1.1172.2.118.  .14(raeb 5663:-21):                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5664: 
                   5665:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5666:        return '';
                   5667:     }
                   5668: 
                   5669:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5670:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5671:         return '';
                   5672:     }
                   5673: 
                   5674:     return ($symb,$tuname,$tudom,$tcrsid);
                   5675: }
                   5676: 
1.110     www      5677: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5678: 
                   5679: sub expirespread {
                   5680:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5681:     my $cid=$env{'request.course.id'}; 
1.110     www      5682:     if ($cid) {
                   5683:        my $now=time;
                   5684:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5685:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5686:                             $env{'course.'.$cid.'.num'}.
1.110     www      5687: 	        	    ':nohist_expirationdates:'.
                   5688:                             &escape($key).'='.$now,
1.620     albertel 5689:                             $env{'course.'.$cid.'.home'})
1.110     www      5690:     }
                   5691:     return 'ok';
1.14      www      5692: }
                   5693: 
1.109     www      5694: # ----------------------------------------------------- Devalidate Spreadsheets
                   5695: 
                   5696: sub devalidate {
1.325     www      5697:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5698:     my $cid=$env{'request.course.id'}; 
1.109     www      5699:     if ($cid) {
1.391     matthew  5700:         # delete the stored spreadsheets for
                   5701:         # - the student level sheet of this user in course's homespace
                   5702:         # - the assessment level sheet for this resource 
                   5703:         #   for this user in user's homespace
1.553     albertel 5704: 	# - current conditional state info
1.325     www      5705: 	my $key=$uname.':'.$udom.':';
1.109     www      5706:         my $status=
1.299     matthew  5707: 	    &del('nohist_calculatedsheets',
1.391     matthew  5708: 		 [$key.'studentcalc:'],
1.620     albertel 5709: 		 $env{'course.'.$cid.'.domain'},
                   5710: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5711: 		.' '.
                   5712: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5713: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5714:         unless ($status eq 'ok ok') {
                   5715:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5716:                     $uname.' at '.$udom.' for '.
1.109     www      5717: 		    $symb.': '.$status);
1.133     albertel 5718:         }
1.553     albertel 5719: 	&delenv('user.state.'.$cid);
1.109     www      5720:     }
                   5721: }
                   5722: 
1.265     albertel 5723: sub get_scalar {
                   5724:     my ($string,$end) = @_;
                   5725:     my $value;
                   5726:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5727: 	$value = $1;
                   5728:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5729: 	$value = $1;
                   5730:     }
                   5731:     return &unescape($value);
                   5732: }
                   5733: 
                   5734: sub array2str {
                   5735:   my (@array) = @_;
                   5736:   my $result=&arrayref2str(\@array);
                   5737:   $result=~s/^__ARRAY_REF__//;
                   5738:   $result=~s/__END_ARRAY_REF__$//;
                   5739:   return $result;
                   5740: }
                   5741: 
1.204     albertel 5742: sub arrayref2str {
                   5743:   my ($arrayref) = @_;
1.265     albertel 5744:   my $result='__ARRAY_REF__';
1.204     albertel 5745:   foreach my $elem (@$arrayref) {
1.265     albertel 5746:     if(ref($elem) eq 'ARRAY') {
                   5747:       $result.=&arrayref2str($elem).'&';
                   5748:     } elsif(ref($elem) eq 'HASH') {
                   5749:       $result.=&hashref2str($elem).'&';
                   5750:     } elsif(ref($elem)) {
                   5751:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5752:     } else {
                   5753:       $result.=&escape($elem).'&';
                   5754:     }
                   5755:   }
                   5756:   $result=~s/\&$//;
1.265     albertel 5757:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5758:   return $result;
                   5759: }
                   5760: 
1.168     albertel 5761: sub hash2str {
1.204     albertel 5762:   my (%hash) = @_;
                   5763:   my $result=&hashref2str(\%hash);
1.265     albertel 5764:   $result=~s/^__HASH_REF__//;
                   5765:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5766:   return $result;
                   5767: }
                   5768: 
                   5769: sub hashref2str {
                   5770:   my ($hashref)=@_;
1.265     albertel 5771:   my $result='__HASH_REF__';
1.800     albertel 5772:   foreach my $key (sort(keys(%$hashref))) {
                   5773:     if (ref($key) eq 'ARRAY') {
                   5774:       $result.=&arrayref2str($key).'=';
                   5775:     } elsif (ref($key) eq 'HASH') {
                   5776:       $result.=&hashref2str($key).'=';
                   5777:     } elsif (ref($key)) {
1.265     albertel 5778:       $result.='=';
1.800     albertel 5779:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5780:     } else {
1.1132    raeburn  5781: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5782:     }
                   5783: 
1.800     albertel 5784:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5785:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5786:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5787:       $result.=&hashref2str($hashref->{$key}).'&';
                   5788:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5789:        $result.='&';
1.800     albertel 5790:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5791:     } else {
1.800     albertel 5792:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5793:     }
                   5794:   }
1.168     albertel 5795:   $result=~s/\&$//;
1.265     albertel 5796:   $result .= '__END_HASH_REF__';
1.168     albertel 5797:   return $result;
                   5798: }
                   5799: 
                   5800: sub str2hash {
1.265     albertel 5801:     my ($string)=@_;
                   5802:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5803:     return %$hash;
                   5804: }
                   5805: 
                   5806: sub str2hashref {
1.168     albertel 5807:   my ($string) = @_;
1.265     albertel 5808: 
                   5809:   my %hash;
                   5810: 
                   5811:   if($string !~ /^__HASH_REF__/) {
                   5812:       if (! ($string eq '' || !defined($string))) {
                   5813: 	  $hash{'error'}='Not hash reference';
                   5814:       }
                   5815:       return (\%hash, $string);
                   5816:   }
                   5817: 
                   5818:   $string =~ s/^__HASH_REF__//;
                   5819: 
                   5820:   while($string !~ /^__END_HASH_REF__/) {
                   5821:       #key
                   5822:       my $key='';
                   5823:       if($string =~ /^__HASH_REF__/) {
                   5824:           ($key, $string)=&str2hashref($string);
                   5825:           if(defined($key->{'error'})) {
                   5826:               $hash{'error'}='Bad data';
                   5827:               return (\%hash, $string);
                   5828:           }
                   5829:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5830:           ($key, $string)=&str2arrayref($string);
                   5831:           if($key->[0] eq 'Array reference error') {
                   5832:               $hash{'error'}='Bad data';
                   5833:               return (\%hash, $string);
                   5834:           }
                   5835:       } else {
                   5836:           $string =~ s/^(.*?)=//;
1.267     albertel 5837: 	  $key=&unescape($1);
1.265     albertel 5838:       }
                   5839:       $string =~ s/^=//;
                   5840: 
                   5841:       #value
                   5842:       my $value='';
                   5843:       if($string =~ /^__HASH_REF__/) {
                   5844:           ($value, $string)=&str2hashref($string);
                   5845:           if(defined($value->{'error'})) {
                   5846:               $hash{'error'}='Bad data';
                   5847:               return (\%hash, $string);
                   5848:           }
                   5849:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5850:           ($value, $string)=&str2arrayref($string);
                   5851:           if($value->[0] eq 'Array reference error') {
                   5852:               $hash{'error'}='Bad data';
                   5853:               return (\%hash, $string);
                   5854:           }
                   5855:       } else {
                   5856: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5857:       }
                   5858:       $string =~ s/^&//;
                   5859: 
                   5860:       $hash{$key}=$value;
1.204     albertel 5861:   }
1.265     albertel 5862: 
                   5863:   $string =~ s/^__END_HASH_REF__//;
                   5864: 
                   5865:   return (\%hash, $string);
1.204     albertel 5866: }
                   5867: 
                   5868: sub str2array {
1.265     albertel 5869:     my ($string)=@_;
                   5870:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5871:     return @$array;
                   5872: }
                   5873: 
                   5874: sub str2arrayref {
1.204     albertel 5875:   my ($string) = @_;
1.265     albertel 5876:   my @array;
                   5877: 
                   5878:   if($string !~ /^__ARRAY_REF__/) {
                   5879:       if (! ($string eq '' || !defined($string))) {
                   5880: 	  $array[0]='Array reference error';
                   5881:       }
                   5882:       return (\@array, $string);
                   5883:   }
                   5884: 
                   5885:   $string =~ s/^__ARRAY_REF__//;
                   5886: 
                   5887:   while($string !~ /^__END_ARRAY_REF__/) {
                   5888:       my $value='';
                   5889:       if($string =~ /^__HASH_REF__/) {
                   5890:           ($value, $string)=&str2hashref($string);
                   5891:           if(defined($value->{'error'})) {
                   5892:               $array[0] ='Array reference error';
                   5893:               return (\@array, $string);
                   5894:           }
                   5895:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5896:           ($value, $string)=&str2arrayref($string);
                   5897:           if($value->[0] eq 'Array reference error') {
                   5898:               $array[0] ='Array reference error';
                   5899:               return (\@array, $string);
                   5900:           }
                   5901:       } else {
                   5902: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5903:       }
                   5904:       $string =~ s/^&//;
                   5905: 
                   5906:       push(@array, $value);
1.191     harris41 5907:   }
1.265     albertel 5908: 
                   5909:   $string =~ s/^__END_ARRAY_REF__//;
                   5910: 
                   5911:   return (\@array, $string);
1.168     albertel 5912: }
                   5913: 
1.167     albertel 5914: # -------------------------------------------------------------------Temp Store
                   5915: 
1.168     albertel 5916: sub tmpreset {
                   5917:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5918:   if (!$symb) {
                   5919:     $symb=&symbread();
1.620     albertel 5920:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5921:   }
                   5922:   $symb=escape($symb);
                   5923: 
1.620     albertel 5924:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5925:   $namespace=~s/\//\_/g;
                   5926:   $namespace=~s/\W//g;
                   5927: 
1.620     albertel 5928:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5929:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5930:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118.  .17(raeb 5931:-21):       $stuname=&get_requestor_ip();
1.591     albertel 5932:   }
1.1117    foxr     5933:   my $path=LONCAPA::tempdir();
1.168     albertel 5934:   my %hash;
                   5935:   if (tie(%hash,'GDBM_File',
                   5936: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5937: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5938:     foreach my $key (keys(%hash)) {
1.180     albertel 5939:       if ($key=~ /:$symb/) {
1.168     albertel 5940: 	delete($hash{$key});
                   5941:       }
                   5942:     }
                   5943:   }
                   5944: }
                   5945: 
1.167     albertel 5946: sub tmpstore {
1.168     albertel 5947:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5948: 
                   5949:   if (!$symb) {
                   5950:     $symb=&symbread();
1.620     albertel 5951:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5952:   }
                   5953:   $symb=escape($symb);
                   5954: 
                   5955:   if (!$namespace) {
                   5956:     # I don't think we would ever want to store this for a course.
                   5957:     # it seems this will only be used if we don't have a course.
1.620     albertel 5958:     #$namespace=$env{'request.course.id'};
1.168     albertel 5959:     #if (!$namespace) {
1.620     albertel 5960:       $namespace=$env{'request.state'};
1.168     albertel 5961:     #}
                   5962:   }
                   5963:   $namespace=~s/\//\_/g;
                   5964:   $namespace=~s/\W//g;
1.620     albertel 5965:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5966:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5967:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118.  .17(raeb 5968:-21):       $stuname=&get_requestor_ip();
1.591     albertel 5969:   }
1.168     albertel 5970:   my $now=time;
                   5971:   my %hash;
1.1117    foxr     5972:   my $path=LONCAPA::tempdir();
1.168     albertel 5973:   if (tie(%hash,'GDBM_File',
                   5974: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5975: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5976:     $hash{"version:$symb"}++;
                   5977:     my $version=$hash{"version:$symb"};
                   5978:     my $allkeys=''; 
                   5979:     foreach my $key (keys(%$storehash)) {
                   5980:       $allkeys.=$key.':';
1.591     albertel 5981:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5982:     }
                   5983:     $hash{"$version:$symb:timestamp"}=$now;
                   5984:     $allkeys.='timestamp';
                   5985:     $hash{"$version:keys:$symb"}=$allkeys;
                   5986:     if (untie(%hash)) {
                   5987:       return 'ok';
                   5988:     } else {
                   5989:       return "error:$!";
                   5990:     }
                   5991:   } else {
                   5992:     return "error:$!";
                   5993:   }
                   5994: }
1.167     albertel 5995: 
1.168     albertel 5996: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5997: 
1.168     albertel 5998: sub tmprestore {
                   5999:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6000: 
1.168     albertel 6001:   if (!$symb) {
                   6002:     $symb=&symbread();
1.620     albertel 6003:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6004:   }
                   6005:   $symb=escape($symb);
                   6006: 
1.620     albertel 6007:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6008: 
1.620     albertel 6009:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6010:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6011:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118.  .17(raeb 6012:-21):       $stuname=&get_requestor_ip();
1.591     albertel 6013:   }
1.168     albertel 6014:   my %returnhash;
                   6015:   $namespace=~s/\//\_/g;
                   6016:   $namespace=~s/\W//g;
                   6017:   my %hash;
1.1117    foxr     6018:   my $path=LONCAPA::tempdir();
1.168     albertel 6019:   if (tie(%hash,'GDBM_File',
                   6020: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6021: 	  &GDBM_READER(),0640)) {
1.168     albertel 6022:     my $version=$hash{"version:$symb"};
                   6023:     $returnhash{'version'}=$version;
                   6024:     my $scope;
                   6025:     for ($scope=1;$scope<=$version;$scope++) {
                   6026:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6027:       my @keys=split(/:/,$vkeys);
                   6028:       my $key;
                   6029:       $returnhash{"$scope:keys"}=$vkeys;
                   6030:       foreach $key (@keys) {
1.591     albertel 6031: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6032: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6033:       }
                   6034:     }
1.168     albertel 6035:     if (!(untie(%hash))) {
                   6036:       return "error:$!";
                   6037:     }
                   6038:   } else {
                   6039:     return "error:$!";
                   6040:   }
                   6041:   return %returnhash;
1.167     albertel 6042: }
                   6043: 
1.9       www      6044: # ----------------------------------------------------------------------- Store
                   6045: 
                   6046: sub store {
1.1172.2.64  raeburn  6047:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6048:     my $home='';
                   6049: 
1.168     albertel 6050:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6051: 
1.213     www      6052:     $symb=&symbclean($symb);
1.122     albertel 6053:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6054: 
1.620     albertel 6055:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6056:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6057: 
                   6058:     &devalidate($symb,$stuname,$domain);
1.109     www      6059: 
                   6060:     $symb=escape($symb);
1.187     www      6061:     if (!$namespace) { 
1.620     albertel 6062:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6063:           return ''; 
                   6064:        } 
                   6065:     }
1.620     albertel 6066:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6067: 
1.1172.2.118.  .17(raeb 6068:-21):     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6069:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6070: 
1.12      www      6071:     my $namevalue='';
1.800     albertel 6072:     foreach my $key (keys(%$storehash)) {
                   6073:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6074:     }
1.12      www      6075:     $namevalue=~s/\&$//;
1.187     www      6076:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6077:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6078: }
                   6079: 
1.47      www      6080: # -------------------------------------------------------------- Critical Store
                   6081: 
                   6082: sub cstore {
1.1172.2.64  raeburn  6083:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6084:     my $home='';
                   6085: 
1.168     albertel 6086:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6087: 
1.213     www      6088:     $symb=&symbclean($symb);
1.122     albertel 6089:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6090: 
1.620     albertel 6091:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6092:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6093: 
                   6094:     &devalidate($symb,$stuname,$domain);
1.109     www      6095: 
                   6096:     $symb=escape($symb);
1.187     www      6097:     if (!$namespace) { 
1.620     albertel 6098:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6099:           return ''; 
                   6100:        } 
                   6101:     }
1.620     albertel 6102:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6103: 
1.1172.2.118.  .17(raeb 6104:-21):     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6105:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6106: 
1.47      www      6107:     my $namevalue='';
1.800     albertel 6108:     foreach my $key (keys(%$storehash)) {
                   6109:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6110:     }
1.47      www      6111:     $namevalue=~s/\&$//;
1.187     www      6112:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6113:     return critical
1.1172.2.64  raeburn  6114:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6115: }
                   6116: 
1.9       www      6117: # --------------------------------------------------------------------- Restore
                   6118: 
                   6119: sub restore {
1.124     www      6120:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6121:     my $home='';
                   6122: 
1.168     albertel 6123:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6124: 
1.122     albertel 6125:     if (!$symb) {
1.1172.2.26  raeburn  6126:         return if ($namespace eq 'courserequests');
                   6127:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6128:     } else {
1.1172.2.26  raeburn  6129:         unless ($namespace eq 'courserequests') {
                   6130:             $symb=&escape(&symbclean($symb));
                   6131:         }
1.122     albertel 6132:     }
1.188     www      6133:     if (!$namespace) { 
1.620     albertel 6134:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6135:           return ''; 
                   6136:        } 
                   6137:     }
1.620     albertel 6138:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6139:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6140:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6141:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6142: 
1.12      www      6143:     my %returnhash=();
1.800     albertel 6144:     foreach my $line (split(/\&/,$answer)) {
                   6145: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6146:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6147:     }
1.75      www      6148:     my $version;
                   6149:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6150:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6151:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6152:        }
1.75      www      6153:     }
1.13      www      6154:     return %returnhash;
1.34      www      6155: }
                   6156: 
                   6157: # ---------------------------------------------------------- Course Description
1.1118    foxr     6158: #
                   6159: #  
1.34      www      6160: 
                   6161: sub coursedescription {
1.731     albertel 6162:     my ($courseid,$args)=@_;
1.34      www      6163:     $courseid=~s/^\///;
1.49      www      6164:     $courseid=~s/\_/\//g;
1.34      www      6165:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6166:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6167:     my $normalid=$cdomain.'_'.$cnum;
                   6168:     # need to always cache even if we get errors otherwise we keep 
                   6169:     # trying and trying and trying to get the course description.
                   6170:     my %envhash=();
                   6171:     my %returnhash=();
1.731     albertel 6172:     
                   6173:     my $expiretime=600;
                   6174:     if ($env{'request.course.id'} eq $normalid) {
                   6175: 	$expiretime=120;
                   6176:     }
                   6177: 
                   6178:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6179:     if (!$args->{'freshen_cache'}
                   6180: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6181: 	foreach my $key (keys(%env)) {
                   6182: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6183: 	    my ($setting) = $1;
                   6184: 	    $returnhash{$setting} = $env{$key};
                   6185: 	}
                   6186: 	return %returnhash;
                   6187:     }
                   6188: 
1.1118    foxr     6189:     # get the data again
                   6190: 
1.731     albertel 6191:     if (!$args->{'one_time'}) {
                   6192: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6193:     }
1.811     albertel 6194: 
1.34      www      6195:     if ($chome ne 'no_host') {
1.302     albertel 6196:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6197:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6198: 	   my $username = $env{'user.name'}; # Defult username
                   6199: 	   if(defined $args->{'user'}) {
                   6200: 	       $username = $args->{'user'};
                   6201: 	   }
1.129     albertel 6202:            $returnhash{'home'}= $chome;
                   6203: 	   $returnhash{'domain'} = $cdomain;
                   6204: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6205:            if (!defined($returnhash{'type'})) {
                   6206:                $returnhash{'type'} = 'Course';
                   6207:            }
1.130     albertel 6208:            while (my ($name,$value) = each %returnhash) {
1.53      www      6209:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6210:            }
1.270     www      6211:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6212:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6213: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6214:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6215:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6216:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6217:        }
                   6218:     }
1.731     albertel 6219:     if (!$args->{'one_time'}) {
1.949     raeburn  6220: 	&appenv(\%envhash);
1.731     albertel 6221:     }
1.302     albertel 6222:     return %returnhash;
1.461     www      6223: }
                   6224: 
1.1080    raeburn  6225: sub update_released_required {
                   6226:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6227:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6228:         $cid = $env{'request.course.id'};
                   6229:         $cdom = $env{'course.'.$cid.'.domain'};
                   6230:         $cnum = $env{'course.'.$cid.'.num'};
                   6231:         $chome = $env{'course.'.$cid.'.home'};
                   6232:     }
                   6233:     if ($needsrelease) {
                   6234:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6235:         my $needsupdate;
                   6236:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6237:             $needsupdate = 1;
                   6238:         } else {
                   6239:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6240:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6241:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6242:                 $needsupdate = 1;
                   6243:             }
                   6244:         }
                   6245:         if ($needsupdate) {
                   6246:             my %needshash = (
                   6247:                              'internal.releaserequired' => $needsrelease,
                   6248:                             );
                   6249:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6250:             if ($putresult eq 'ok') {
                   6251:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6252:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6253:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6254:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6255:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6256:                 }
                   6257:             }
                   6258:         }
                   6259:     }
                   6260:     return;
                   6261: }
                   6262: 
1.461     www      6263: # -------------------------------------------------See if a user is privileged
                   6264: 
                   6265: sub privileged {
1.1172.2.23  raeburn  6266:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6267:     my $now = time;
1.1172.2.23  raeburn  6268:     my $roles;
                   6269:     if (ref($possroles) eq 'ARRAY') {
                   6270:         $roles = $possroles;
                   6271:     } else {
                   6272:         $roles = ['dc','su'];
                   6273:     }
                   6274:     if (ref($possdomains) eq 'ARRAY') {
                   6275:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6276:         foreach my $dom (@{$possdomains}) {
                   6277:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6278:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6279:                 foreach my $role (@{$roles}) {
                   6280:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6281:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6282:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6283:                             return 1 unless (($end && $end < $now) ||
                   6284:                                              ($start && $start > $now));
                   6285:                         }
                   6286:                     }
                   6287:                 }
                   6288:             }
                   6289:         }
                   6290:     } else {
                   6291:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6292:         my $now = time;
1.1170    droeschl 6293: 
1.1172.2.58  raeburn  6294:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6295:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6296:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6297:                 return 1 unless ($tend && $tend < $now)
                   6298:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6299:             }
1.1172.2.23  raeburn  6300:         }
                   6301:     }
1.461     www      6302:     return 0;
1.9       www      6303: }
1.1       albertel 6304: 
1.1172.2.23  raeburn  6305: sub privileged_by_domain {
                   6306:     my ($domains,$roles) = @_;
                   6307:     my %privileged = ();
                   6308:     my $cachetime = 60*60*24;
                   6309:     my $now = time;
                   6310:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6311:         return %privileged;
                   6312:     }
                   6313:     foreach my $dom (@{$domains}) {
                   6314:         next if (ref($privileged{$dom}) eq 'HASH');
                   6315:         my $needroles;
                   6316:         foreach my $role (@{$roles}) {
                   6317:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6318:             if (defined($cached)) {
                   6319:                 if (ref($result) eq 'HASH') {
                   6320:                     $privileged{$dom}{$role} = $result;
                   6321:                 }
                   6322:             } else {
                   6323:                 $needroles = 1;
                   6324:             }
                   6325:         }
                   6326:         if ($needroles) {
                   6327:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6328:             $privileged{$dom} = {};
                   6329:             foreach my $server (keys(%dompersonnel)) {
                   6330:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6331:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6332:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6333:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6334:                         next if ($end && $end < $now);
                   6335:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6336:                             $dompersonnel{$server}{$item};
                   6337:                     }
                   6338:                 }
                   6339:             }
                   6340:             if (ref($privileged{$dom}) eq 'HASH') {
                   6341:                 foreach my $role (@{$roles}) {
                   6342:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6343:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6344:                     } else {
                   6345:                         my %hash = ();
                   6346:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6347:                     }
                   6348:                 }
                   6349:             }
                   6350:         }
                   6351:     }
                   6352:     return %privileged;
                   6353: }
                   6354: 
1.103     harris41 6355: # -------------------------------------------------------- Get user privileges
1.11      www      6356: 
                   6357: sub rolesinit {
1.1169    droeschl 6358:     my ($domain, $username) = @_;
                   6359:     my %userroles = ('user.login.time' => time);
                   6360:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6361: 
                   6362:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6363:     # also, blocking can be triggered by an activating timer
                   6364:     # it's saved in the user's %env.
                   6365:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6366:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6367:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6368:         %timerintchk, %timerintenv);
                   6369: 
1.1162    raeburn  6370:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6371:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6372:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6373:     }
1.1169    droeschl 6374: 
1.1162    raeburn  6375:     foreach my $key (keys(%timerinterval)) {
                   6376:         my ($cid,$rest) = split(/\0/,$key);
                   6377:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6378:     }
1.1169    droeschl 6379: 
1.11      www      6380:     my %allroles=();
1.1162    raeburn  6381:     my %allgroups=();
1.11      www      6382: 
1.1172.2.58  raeburn  6383:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6384:         my $role = $rolesdump{$area};
                   6385:         $area =~ s/\_\w\w$//;
                   6386: 
                   6387:         my ($trole, $tend, $tstart, $group_privs);
                   6388: 
                   6389:         if ($role =~ /^cr/) {
                   6390:         # Custom role, defined by a user 
                   6391:         # e.g., user.role.cr/msu/smith/mynewrole
                   6392:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6393:                 $trole = $1;
                   6394:                 ($tend, $tstart) = split('_', $2);
                   6395:             } else {
                   6396:                 $trole = $role;
                   6397:             }
                   6398:         } elsif ($role =~ m|^gr/|) {
                   6399:         # Role of member in a group, defined within a course/community
                   6400:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6401:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6402:             next if $tstart eq '-1';
                   6403:             ($trole, $group_privs) = split(/\//, $trole);
                   6404:             $group_privs = &unescape($group_privs);
                   6405:         } else {
                   6406:         # Just a normal role, defined in roles.tab
                   6407:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6408:         }
                   6409: 
                   6410:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6411:                  $username);
                   6412:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6413: 
                   6414:         # role expired or not available yet?
                   6415:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6416:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6417: 
                   6418:         next if $area eq '' or $trole eq '';
                   6419: 
                   6420:         my $spec = "$trole.$area";
                   6421:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6422: 
                   6423:         if ($trole =~ /^cr\//) {
                   6424:         # Custom role, defined by a user
                   6425:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6426:         } elsif ($trole eq 'gr') {
                   6427:         # Role of a member in a group, defined within a course/community
                   6428:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6429:             next;
                   6430:         } else {
                   6431:         # Normal role, defined in roles.tab
                   6432:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6433:         }
                   6434: 
                   6435:         my $cid = $tdomain.'_'.$trest;
                   6436:         unless ($firstaccchk{$cid}) {
                   6437:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6438:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6439:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6440:                         $coursetimerstarts{$cid}{$item}; 
                   6441:                 }
                   6442:             }
                   6443:             $firstaccchk{$cid} = 1;
                   6444:         }
                   6445:         unless ($timerintchk{$cid}) {
                   6446:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6447:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6448:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6449:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6450:                 }
1.12      www      6451:             }
1.1169    droeschl 6452:             $timerintchk{$cid} = 1;
1.191     harris41 6453:         }
1.11      www      6454:     }
1.1169    droeschl 6455: 
1.1172.2.91  raeburn  6456:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6457:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6458:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6459:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6460: 
1.1162    raeburn  6461:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6462: }
                   6463: 
1.567     raeburn  6464: sub set_arearole {
1.1172.2.19  raeburn  6465:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6466:     unless ($nolog) {
1.567     raeburn  6467: # log the associated role with the area
1.1172.2.19  raeburn  6468:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6469:     }
1.743     albertel 6470:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6471: }
                   6472: 
                   6473: sub custom_roleprivs {
                   6474:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6475:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6476:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6477:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6478:         my ($rdummy,$roledef)=
                   6479:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6480:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6481:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6482:             if (defined($syspriv)) {
1.1043    raeburn  6483:                 if ($trest =~ /^$match_community$/) {
                   6484:                     $syspriv =~ s/bre\&S//; 
                   6485:                 }
1.567     raeburn  6486:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6487:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6488:             }
                   6489:             if ($tdomain ne '') {
                   6490:                 if (defined($dompriv)) {
                   6491:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6492:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6493:                 }
                   6494:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6495:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6496:                         my $rolename = $1;
                   6497:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6498:                     }
1.567     raeburn  6499:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6500:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6501:                 }
                   6502:             }
                   6503:         }
                   6504:     }
                   6505: }
                   6506: 
1.1172.2.89  raeburn  6507: sub course_adhocrole_privs {
                   6508:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6509:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6510:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6511:         my (%currprivs,%storeprivs);
                   6512:         foreach my $item (split(/:/,$coursepriv)) {
                   6513:             my ($priv,$restrict) = split(/\&/,$item);
                   6514:             $currprivs{$priv} = $restrict;
                   6515:         }
                   6516:         my (%possadd,%possremove,%full);
                   6517:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6518:             my ($priv,$restrict)=split(/\&/,$item);
                   6519:             $full{$priv} = $restrict;
                   6520:         }
                   6521:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6522:              next if ($item eq '');
                   6523:              my ($rule,$rest) = split(/=/,$item);
                   6524:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6525:              foreach my $priv (split(/:/,$rest)) {
                   6526:                  if ($priv ne '') {
                   6527:                      if ($rule eq 'off') {
                   6528:                          $possremove{$priv} = 1;
                   6529:                      } else {
                   6530:                          $possadd{$priv} = 1;
                   6531:                      }
                   6532:                  }
                   6533:              }
                   6534:          }
                   6535:          foreach my $priv (sort(keys(%full))) {
                   6536:              if (exists($currprivs{$priv})) {
                   6537:                  unless (exists($possremove{$priv})) {
                   6538:                      $storeprivs{$priv} = $currprivs{$priv};
                   6539:                  }
                   6540:              } elsif (exists($possadd{$priv})) {
                   6541:                  $storeprivs{$priv} = $full{$priv};
                   6542:              }
                   6543:          }
                   6544:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6545:      }
                   6546:      return $coursepriv;
                   6547: }
                   6548: 
1.678     raeburn  6549: sub group_roleprivs {
                   6550:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6551:     my $access = 1;
                   6552:     my $now = time;
                   6553:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6554:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6555:     if ($access) {
1.811     albertel 6556:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6557:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6558:     }
                   6559: }
1.567     raeburn  6560: 
                   6561: sub standard_roleprivs {
                   6562:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6563:     if (defined($pr{$trole.':s'})) {
                   6564:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6565:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6566:     }
                   6567:     if ($tdomain ne '') {
                   6568:         if (defined($pr{$trole.':d'})) {
                   6569:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6570:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6571:         }
                   6572:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6573:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6574:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6575:         }
                   6576:     }
                   6577: }
                   6578: 
                   6579: sub set_userprivs {
1.1064    raeburn  6580:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6581:     my $author=0;
                   6582:     my $adv=0;
1.1172.2.91  raeburn  6583:     my $rar=0;
1.678     raeburn  6584:     my %grouproles = ();
                   6585:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6586:         my @groupkeys; 
1.1000    raeburn  6587:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6588:             push(@groupkeys,$role);
                   6589:         }
                   6590:         if (ref($groups_roles) eq 'HASH') {
                   6591:             foreach my $key (keys(%{$groups_roles})) {
                   6592:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6593:                     push(@groupkeys,$key);
                   6594:                 }
                   6595:             }
                   6596:         }
                   6597:         if (@groupkeys > 0) {
                   6598:             foreach my $role (@groupkeys) {
                   6599:                 my ($trole,$area,$sec,$extendedarea);
                   6600:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6601:                     $trole = $1;
                   6602:                     $area = $2;
                   6603:                     $sec = $3;
                   6604:                     $extendedarea = $area.$sec;
                   6605:                     if (exists($$allgroups{$area})) {
                   6606:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6607:                             my $spec = $trole.'.'.$extendedarea;
                   6608:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6609:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6610:                         }
1.678     raeburn  6611:                     }
                   6612:                 }
                   6613:             }
                   6614:         }
                   6615:     }
1.800     albertel 6616:     foreach my $group (keys(%grouproles)) {
                   6617:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6618:     }
1.800     albertel 6619:     foreach my $role (keys(%{$allroles})) {
                   6620:         my %thesepriv;
1.941     raeburn  6621:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6622:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6623:             if ($item ne '') {
                   6624:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6625:                 if ($restrictions eq '') {
                   6626:                     $thesepriv{$privilege}='F';
                   6627:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6628:                     $thesepriv{$privilege}.=$restrictions;
                   6629:                 }
                   6630:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6631:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6632:             }
                   6633:         }
                   6634:         my $thesestr='';
1.1104    raeburn  6635:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6636: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6637: 	}
                   6638:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6639:     }
1.1172.2.91  raeburn  6640:     return ($author,$adv,$rar);
1.567     raeburn  6641: }
                   6642: 
1.994     raeburn  6643: sub role_status {
1.1104    raeburn  6644:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6645:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6646:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6647:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6648:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6649:             $$where = '/'.$two;
1.994     raeburn  6650:             $$trolecode=$$role.'.'.$$where;
                   6651:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6652:             $$tstatus='is';
1.1104    raeburn  6653:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6654:                 $$tstatus='future';
1.1034    raeburn  6655:                 if ($$tstart<$now) {
                   6656:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6657:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6658:                             my (%allroles,%allgroups,$group_privs,
                   6659:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6660:                             my %userroles = (
                   6661:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6662:                             );
1.1064    raeburn  6663:                             @rolecodes = ('cm'); 
1.1002    raeburn  6664:                             my $spec=$$role.'.'.$$where;
                   6665:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6666:                             if ($$role =~ /^cr\//) {
                   6667:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6668:                                 push(@rolecodes,'cr');
1.1002    raeburn  6669:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6670:                                 push(@rolecodes,$$role);
1.1002    raeburn  6671:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6672:                                                     $env{'user.name'});
1.1064    raeburn  6673:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6674:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6675:                                 $group_privs = &unescape($group_privs);
                   6676:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6677:                                 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  6678:                                 &get_groups_roles($tdomain,$trest,
                   6679:                                                   \%course_roles,\@rolecodes,
                   6680:                                                   \%groups_roles);
1.1002    raeburn  6681:                             } else {
1.1064    raeburn  6682:                                 push(@rolecodes,$$role);
1.1002    raeburn  6683:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6684:                             }
1.1172.2.91  raeburn  6685:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6686:                                                                    \%groups_roles);
1.1064    raeburn  6687:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6688:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6689:                         }
                   6690:                     }
1.1034    raeburn  6691:                     $$tstatus = 'is';
1.1002    raeburn  6692:                 }
1.994     raeburn  6693:             }
                   6694:             if ($$tend) {
1.1104    raeburn  6695:                 if ($$tend<$update) {
1.994     raeburn  6696:                     $$tstatus='expired';
                   6697:                 } elsif ($$tend<$now) {
                   6698:                     $$tstatus='will_not';
                   6699:                 }
                   6700:             }
                   6701:         }
                   6702:     }
                   6703: }
                   6704: 
1.1104    raeburn  6705: sub get_groups_roles {
                   6706:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6707:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6708:                   (ref($rolecodes) eq 'ARRAY') && 
                   6709:                   (ref($groups_roles) eq 'HASH')); 
                   6710:     if (keys(%{$cdom_courseroles}) > 0) {
                   6711:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6712:         if ($cdom ne '' && $cnum ne '') {
                   6713:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6714:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6715:                     my $crsrole = $1;
                   6716:                     my $crssec = $2;
                   6717:                     if ($crsrole =~ /^cr/) {
                   6718:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6719:                             push(@{$rolecodes},'cr');
                   6720:                         }
                   6721:                     } else {
                   6722:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6723:                             push(@{$rolecodes},$crsrole);
                   6724:                         }
                   6725:                     }
                   6726:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6727:                     if ($crssec ne '') {
                   6728:                         $rolekey .= "/$crssec";
                   6729:                     }
                   6730:                     $rolekey .= './';
                   6731:                     $groups_roles->{$rolekey} = $rolecodes;
                   6732:                 }
                   6733:             }
                   6734:         }
                   6735:     }
                   6736:     return;
                   6737: }
                   6738: 
                   6739: sub delete_env_groupprivs {
                   6740:     my ($where,$courseroles,$possroles) = @_;
                   6741:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6742:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6743:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6744:         %{$courseroles->{$udom}} =
                   6745:             &get_my_roles('','','userroles',['active'],
                   6746:                           $possroles,[$udom],1);
                   6747:     }
                   6748:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6749:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6750:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6751:             my $area = '/'.$cdom.'/'.$cnum;
                   6752:             my $privkey = "user.priv.$crsrole.$area";
                   6753:             if ($crssec ne '') {
                   6754:                 $privkey .= '/'.$crssec;
                   6755:             }
                   6756:             $privkey .= ".$area/$group";
                   6757:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6758:         }
                   6759:     }
                   6760:     return;
                   6761: }
                   6762: 
1.994     raeburn  6763: sub check_adhoc_privs {
1.1172.2.86  raeburn  6764:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6765:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6766:     if ($sec) {
                   6767:         $cckey .= '/'.$sec;
                   6768:     }
1.1172.2.9  raeburn  6769:     my $setprivs;
1.994     raeburn  6770:     if ($env{$cckey}) {
                   6771:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6772:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6773:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6774:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6775:             $setprivs = 1;
1.994     raeburn  6776:         }
                   6777:     } else {
1.1172.2.87  raeburn  6778:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6779:         $setprivs = 1;
1.994     raeburn  6780:     }
1.1172.2.9  raeburn  6781:     return $setprivs;
1.994     raeburn  6782: }
                   6783: 
                   6784: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6785: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6786:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6787:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6788:     if ($sec ne '') {
                   6789:         $area .= '/'.$sec;
                   6790:     }
1.994     raeburn  6791:     my $spec = $role.'.'.$area;
                   6792:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6793:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6794:     my %rolehash = ();
1.1172.2.89  raeburn  6795:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6796:         my $rolename = $1;
1.1172.2.84  raeburn  6797:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6798:         my %domdef = &get_domain_defaults($dcdom);
                   6799:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6800:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6801:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6802:             }
                   6803:         }
1.1172.2.84  raeburn  6804:     } else {
                   6805:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6806:     }
1.1172.2.91  raeburn  6807:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6808:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6809:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6810:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6811:         &appenv( {'request.role'        => $spec,
                   6812:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6813:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6814:                  }
                   6815:                );
                   6816:         my $tadv=0;
                   6817:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6818:         &appenv({'request.role.adv'    => $tadv});
                   6819:     }
1.994     raeburn  6820: }
                   6821: 
1.12      www      6822: # --------------------------------------------------------------- get interface
                   6823: 
                   6824: sub get {
1.131     albertel 6825:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6826:    my $items='';
1.800     albertel 6827:    foreach my $item (@$storearr) {
                   6828:        $items.=&escape($item).'&';
1.191     harris41 6829:    }
1.12      www      6830:    $items=~s/\&$//;
1.620     albertel 6831:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6832:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6833:    my $uhome=&homeserver($uname,$udomain);
                   6834: 
1.133     albertel 6835:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6836:    my @pairs=split(/\&/,$rep);
1.273     albertel 6837:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6838:      return @pairs;
                   6839:    }
1.15      www      6840:    my %returnhash=();
1.42      www      6841:    my $i=0;
1.800     albertel 6842:    foreach my $item (@$storearr) {
                   6843:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6844:       $i++;
1.191     harris41 6845:    }
1.15      www      6846:    return %returnhash;
1.27      www      6847: }
                   6848: 
                   6849: # --------------------------------------------------------------- del interface
                   6850: 
                   6851: sub del {
1.133     albertel 6852:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6853:    my $items='';
1.800     albertel 6854:    foreach my $item (@$storearr) {
                   6855:        $items.=&escape($item).'&';
1.191     harris41 6856:    }
1.984     neumanie 6857: 
1.27      www      6858:    $items=~s/\&$//;
1.620     albertel 6859:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6860:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6861:    my $uhome=&homeserver($uname,$udomain);
                   6862:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6863: }
                   6864: 
                   6865: # -------------------------------------------------------------- dump interface
                   6866: 
1.1172.2.22  raeburn  6867: sub unserialize {
                   6868:     my ($rep, $escapedkeys) = @_;
                   6869: 
                   6870:     return {} if $rep =~ /^error/;
                   6871: 
                   6872:     my %returnhash=();
                   6873:     foreach my $item (split(/\&/,$rep)) {
                   6874:         my ($key, $value) = split(/=/, $item, 2);
                   6875:         $key = unescape($key) unless $escapedkeys;
                   6876:         next if $key =~ /^error: 2 /;
                   6877:         $returnhash{$key} = &thaw_unescape($value);
                   6878:     }
                   6879:     return \%returnhash;
                   6880: }
                   6881: 
                   6882: # see Lond::dump_with_regexp
                   6883: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6884: sub dump {
1.1172.2.22  raeburn  6885:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6886:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6887:     if (!$uname) { $uname=$env{'user.name'}; }
                   6888:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6889: 
1.1172.2.55  raeburn  6890:     if ($regexp) {
                   6891:         $regexp=&escape($regexp);
                   6892:     } else {
                   6893:         $regexp='.';
                   6894:     }
1.1172.2.22  raeburn  6895:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6896:         # user is hosted on this machine
1.1172.2.55  raeburn  6897:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6898:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6899:         return %{&unserialize($reply, $escapedkeys)};
                   6900:     }
1.1166    raeburn  6901:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6902:     my @pairs=split(/\&/,$rep);
                   6903:     my %returnhash=();
1.1098    foxr     6904:     if (!($rep =~ /^error/ )) {
                   6905: 	foreach my $item (@pairs) {
                   6906: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6907:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6908: 	    next if ($key =~ /^error: 2 /);
                   6909: 	    $returnhash{$key}=&thaw_unescape($value);
                   6910: 	}
1.755     albertel 6911:     }
                   6912:     return %returnhash;
1.407     www      6913: }
                   6914: 
1.1098    foxr     6915: 
1.717     albertel 6916: # --------------------------------------------------------- dumpstore interface
                   6917: 
                   6918: sub dumpstore {
                   6919:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6920:    # same as dump but keys must be escaped. They may contain colon separated
                   6921:    # lists of values that may themself contain colons (e.g. symbs).
                   6922:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6923: }
                   6924: 
1.407     www      6925: # -------------------------------------------------------------- keys interface
                   6926: 
                   6927: sub getkeys {
                   6928:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6929:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6930:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6931:    my $uhome=&homeserver($uname,$udomain);
                   6932:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6933:    my @keyarray=();
1.800     albertel 6934:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6935:       next if ($key =~ /^error: 2 /);
1.800     albertel 6936:       push(@keyarray,&unescape($key));
1.407     www      6937:    }
                   6938:    return @keyarray;
1.318     matthew  6939: }
                   6940: 
1.319     matthew  6941: # --------------------------------------------------------------- currentdump
                   6942: sub currentdump {
1.328     matthew  6943:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6944:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6945:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6946:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6947:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6948:    my $rep;
                   6949: 
                   6950:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6951:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6952:                    $courseid)));
                   6953:    } else {
                   6954:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6955:    }
                   6956: 
1.318     matthew  6957:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6958:    #
1.318     matthew  6959:    my %returnhash=();
1.319     matthew  6960:    #
1.1172.2.118.  .1(raebu 6961:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6962:        # an old lond will not know currentdump
                   6963:        # Do a dump and make it look like a currentdump
1.822     albertel 6964:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6965:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6966:        my %hash = @tmp;
                   6967:        @tmp=();
1.424     matthew  6968:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6969:    } else {
                   6970:        my @pairs=split(/\&/,$rep);
1.800     albertel 6971:        foreach my $pair (@pairs) {
                   6972:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6973:            my ($symb,$param) = split(/:/,$key);
                   6974:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6975:                                                         &thaw_unescape($value);
1.319     matthew  6976:        }
1.191     harris41 6977:    }
1.12      www      6978:    return %returnhash;
1.424     matthew  6979: }
                   6980: 
                   6981: sub convert_dump_to_currentdump{
                   6982:     my %hash = %{shift()};
                   6983:     my %returnhash;
                   6984:     # Code ripped from lond, essentially.  The only difference
                   6985:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6986:     # we might run in to problems with parameter names =~ /^v\./
                   6987:     while (my ($key,$value) = each(%hash)) {
                   6988:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6989: 	$symb  = &unescape($symb);
                   6990: 	$param = &unescape($param);
1.424     matthew  6991:         next if ($v eq 'version' || $symb eq 'keys');
                   6992:         next if (exists($returnhash{$symb}) &&
                   6993:                  exists($returnhash{$symb}->{$param}) &&
                   6994:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6995:         $returnhash{$symb}->{$param}=$value;
                   6996:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6997:     }
                   6998:     #
                   6999:     # Remove all of the keys in the hashes which keep track of
                   7000:     # the version of the parameter.
                   7001:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7002:         # use a foreach because we are going to delete from the hash.
                   7003:         foreach my $key (keys(%$param_hash)) {
                   7004:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7005:         }
                   7006:     }
                   7007:     return \%returnhash;
1.12      www      7008: }
                   7009: 
1.627     albertel 7010: # ------------------------------------------------------ critical inc interface
                   7011: 
                   7012: sub cinc {
                   7013:     return &inc(@_,'critical');
                   7014: }
                   7015: 
1.449     matthew  7016: # --------------------------------------------------------------- inc interface
                   7017: 
                   7018: sub inc {
1.627     albertel 7019:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7020:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7021:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7022:     my $uhome=&homeserver($uname,$udomain);
                   7023:     my $items='';
                   7024:     if (! ref($store)) {
                   7025:         # got a single value, so use that instead
                   7026:         $items = &escape($store).'=&';
                   7027:     } elsif (ref($store) eq 'SCALAR') {
                   7028:         $items = &escape($$store).'=&';        
                   7029:     } elsif (ref($store) eq 'ARRAY') {
                   7030:         $items = join('=&',map {&escape($_);} @{$store});
                   7031:     } elsif (ref($store) eq 'HASH') {
                   7032:         while (my($key,$value) = each(%{$store})) {
                   7033:             $items.= &escape($key).'='.&escape($value).'&';
                   7034:         }
                   7035:     }
                   7036:     $items=~s/\&$//;
1.627     albertel 7037:     if ($critical) {
                   7038: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7039:     } else {
                   7040: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7041:     }
1.449     matthew  7042: }
                   7043: 
1.12      www      7044: # --------------------------------------------------------------- put interface
                   7045: 
                   7046: sub put {
1.134     albertel 7047:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7048:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7049:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7050:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7051:    my $items='';
1.800     albertel 7052:    foreach my $item (keys(%$storehash)) {
                   7053:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7054:    }
1.12      www      7055:    $items=~s/\&$//;
1.134     albertel 7056:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7057: }
                   7058: 
1.631     albertel 7059: # ------------------------------------------------------------ newput interface
                   7060: 
                   7061: sub newput {
                   7062:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7063:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7064:    if (!$uname) { $uname=$env{'user.name'}; }
                   7065:    my $uhome=&homeserver($uname,$udomain);
                   7066:    my $items='';
                   7067:    foreach my $key (keys(%$storehash)) {
                   7068:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7069:    }
                   7070:    $items=~s/\&$//;
                   7071:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7072: }
                   7073: 
                   7074: # ---------------------------------------------------------  putstore interface
                   7075: 
1.524     raeburn  7076: sub putstore {
1.1172.2.59  raeburn  7077:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7078:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7079:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7080:    my $uhome=&homeserver($uname,$udomain);
                   7081:    my $items='';
1.715     albertel 7082:    foreach my $key (keys(%$storehash)) {
                   7083:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7084:    }
1.715     albertel 7085:    $items=~s/\&$//;
1.716     albertel 7086:    my $esc_symb=&escape($symb);
                   7087:    my $esc_v=&escape($version);
1.715     albertel 7088:    my $reply =
1.716     albertel 7089:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7090: 	      $uhome);
1.1172.2.59  raeburn  7091:    if (($tolog) && ($reply eq 'ok')) {
                   7092:        my $namevalue='';
                   7093:        foreach my $key (keys(%{$storehash})) {
                   7094:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7095:        }
1.1172.2.118.  .14(raeb 7096:-21):        my $ip = &get_requestor_ip();
                   7097:-21):        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7098:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7099:                      '&version='.$esc_v.
                   7100:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7101:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7102:    }
1.715     albertel 7103:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7104:        # gfall back to way things use to be done
1.715     albertel 7105:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7106: 			    $uname);
1.524     raeburn  7107:    }
1.715     albertel 7108:    return $reply;
                   7109: }
                   7110: 
                   7111: sub old_putstore {
1.716     albertel 7112:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7113:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7114:     if (!$uname) { $uname=$env{'user.name'}; }
                   7115:     my $uhome=&homeserver($uname,$udomain);
                   7116:     my %newstorehash;
1.800     albertel 7117:     foreach my $item (keys(%$storehash)) {
                   7118: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7119: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7120:     }
                   7121:     my $items='';
                   7122:     my %allitems = ();
1.800     albertel 7123:     foreach my $item (keys(%newstorehash)) {
                   7124: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7125: 	    my $key = $1.':keys:'.$2;
                   7126: 	    $allitems{$key} .= $3.':';
                   7127: 	}
1.800     albertel 7128: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7129:     }
1.800     albertel 7130:     foreach my $item (keys(%allitems)) {
                   7131: 	$allitems{$item} =~ s/\:$//;
                   7132: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7133:     }
                   7134:     $items=~s/\&$//;
                   7135:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7136: }
                   7137: 
1.47      www      7138: # ------------------------------------------------------ critical put interface
                   7139: 
                   7140: sub cput {
1.134     albertel 7141:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7142:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7143:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7144:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7145:    my $items='';
1.800     albertel 7146:    foreach my $item (keys(%$storehash)) {
                   7147:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7148:    }
1.47      www      7149:    $items=~s/\&$//;
1.134     albertel 7150:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7151: }
                   7152: 
                   7153: # -------------------------------------------------------------- eget interface
                   7154: 
                   7155: sub eget {
1.133     albertel 7156:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7157:    my $items='';
1.800     albertel 7158:    foreach my $item (@$storearr) {
                   7159:        $items.=&escape($item).'&';
1.191     harris41 7160:    }
1.12      www      7161:    $items=~s/\&$//;
1.620     albertel 7162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7163:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7164:    my $uhome=&homeserver($uname,$udomain);
                   7165:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7166:    my @pairs=split(/\&/,$rep);
                   7167:    my %returnhash=();
1.42      www      7168:    my $i=0;
1.800     albertel 7169:    foreach my $item (@$storearr) {
                   7170:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7171:       $i++;
1.191     harris41 7172:    }
1.12      www      7173:    return %returnhash;
                   7174: }
                   7175: 
1.667     albertel 7176: # ------------------------------------------------------------ tmpput interface
                   7177: sub tmpput {
1.802     raeburn  7178:     my ($storehash,$server,$context)=@_;
1.667     albertel 7179:     my $items='';
1.800     albertel 7180:     foreach my $item (keys(%$storehash)) {
                   7181: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7182:     }
                   7183:     $items=~s/\&$//;
1.802     raeburn  7184:     if (defined($context)) {
                   7185:         $items .= ':'.&escape($context);
                   7186:     }
1.667     albertel 7187:     return &reply("tmpput:$items",$server);
                   7188: }
                   7189: 
                   7190: # ------------------------------------------------------------ tmpget interface
                   7191: sub tmpget {
1.688     albertel 7192:     my ($token,$server)=@_;
                   7193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7194:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7195:     my %returnhash;
1.1172.2.85  raeburn  7196:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7197:         return %returnhash;
                   7198:     }
1.667     albertel 7199:     foreach my $item (split(/\&/,$rep)) {
                   7200: 	my ($key,$value)=split(/=/,$item);
                   7201: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7202:     }
                   7203:     return %returnhash;
                   7204: }
                   7205: 
1.1113    raeburn  7206: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7207: sub tmpdel {
                   7208:     my ($token,$server)=@_;
                   7209:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7210:     return &reply("tmpdel:$token",$server);
                   7211: }
                   7212: 
1.1172.2.13  raeburn  7213: # ------------------------------------------------------------ get_timebased_id
                   7214: 
                   7215: sub get_timebased_id {
                   7216:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7217:         $maxtries) = @_;
                   7218:     my ($newid,$error,$dellock);
                   7219:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7220:         return ('','ok','invalid call to get suffix');
                   7221:     }
                   7222: 
                   7223: # set defaults for any optional args for which values were not supplied
                   7224:     if ($who eq '') {
                   7225:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7226:     }
                   7227:     if (!$locktries) {
                   7228:         $locktries = 3;
                   7229:     }
                   7230:     if (!$maxtries) {
                   7231:         $maxtries = 10;
                   7232:     }
                   7233: 
                   7234:     if (($cdom eq '') || ($cnum eq '')) {
                   7235:         if ($env{'request.course.id'}) {
                   7236:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7237:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7238:         }
                   7239:         if (($cdom eq '') || ($cnum eq '')) {
                   7240:             return ('','ok','call to get suffix not in course context');
                   7241:         }
                   7242:     }
                   7243: 
                   7244: # construct locking item
                   7245:     my $lockhash = {
                   7246:                       $prefix."\0".'locked_'.$keyid => $who,
                   7247:                    };
                   7248:     my $tries = 0;
                   7249: 
                   7250: # attempt to get lock on nohist_$namespace file
                   7251:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7252:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7253:         $tries ++;
                   7254:         sleep 1;
                   7255:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7256:     }
                   7257: 
                   7258: # attempt to get unique identifier, based on current timestamp
                   7259:     if ($gotlock eq 'ok') {
                   7260:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7261:         my $id = time;
                   7262:         $newid = $id;
1.1172.2.56  raeburn  7263:         if ($idtype eq 'addcode') {
                   7264:             $newid .= &sixnum_code();
                   7265:         }
1.1172.2.13  raeburn  7266:         my $idtries = 0;
                   7267:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7268:             if ($idtype eq 'concat') {
                   7269:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7270:             } elsif ($idtype eq 'addcode') {
                   7271:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7272:             } else {
                   7273:                 $newid ++;
                   7274:             }
                   7275:             $idtries ++;
                   7276:         }
                   7277:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7278:             my %new_item =  (
                   7279:                               $prefix."\0".$newid => $who,
                   7280:                             );
                   7281:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7282:                                                  $cdom,$cnum);
                   7283:             if ($putresult ne 'ok') {
                   7284:                 undef($newid);
                   7285:                 $error = 'error saving new item: '.$putresult;
                   7286:             }
                   7287:         } else {
1.1172.2.56  raeburn  7288:              undef($newid);
1.1172.2.13  raeburn  7289:              $error = ('error: no unique suffix available for the new item ');
                   7290:         }
                   7291: #  remove lock
                   7292:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7293:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7294:     } else {
                   7295:         $error = "error: could not obtain lockfile\n";
                   7296:         $dellock = 'ok';
1.1172.2.58  raeburn  7297:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7298:             $dellock = 'nolock';
                   7299:         }
1.1172.2.13  raeburn  7300:     }
                   7301:     return ($newid,$dellock,$error);
                   7302: }
                   7303: 
1.1172.2.56  raeburn  7304: sub sixnum_code {
                   7305:     my $code;
                   7306:     for (0..6) {
                   7307:         $code .= int( rand(9) );
                   7308:     }
                   7309:     return $code;
                   7310: }
                   7311: 
1.765     albertel 7312: # -------------------------------------------------- portfolio access checking
                   7313: 
                   7314: sub portfolio_access {
1.1172.2.77  raeburn  7315:     my ($requrl,$clientip) = @_;
1.765     albertel 7316:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7317:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7318:     if ($result) {
                   7319:         my %setters;
                   7320:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7321:             my ($startblock,$endblock) =
                   7322:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7323:             if ($startblock && $endblock) {
                   7324:                 return 'B';
                   7325:             }
                   7326:         } else {
                   7327:             my ($startblock,$endblock) =
                   7328:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7329:             if ($startblock && $endblock) {
                   7330:                 return 'B';
                   7331:             }
                   7332:         }
                   7333:     }
1.765     albertel 7334:     if ($result eq 'ok') {
1.766     albertel 7335:        return 'F';
1.765     albertel 7336:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7337:        return 'A';
1.765     albertel 7338:     }
1.766     albertel 7339:     return '';
1.765     albertel 7340: }
                   7341: 
                   7342: sub get_portfolio_access {
1.1172.2.77  raeburn  7343:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7344: 
                   7345:     if (!ref($access_hash)) {
                   7346: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7347: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7348: 						   $file_name);
                   7349: 	$access_hash = $access_controls{$file_name};
                   7350:     }
                   7351: 
1.1172.2.77  raeburn  7352:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7353:     my $now = time;
                   7354:     if (ref($access_hash) eq 'HASH') {
                   7355:         foreach my $key (keys(%{$access_hash})) {
                   7356:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7357:             if ($start > $now) {
                   7358:                 next;
                   7359:             }
                   7360:             if ($end && $end<$now) {
                   7361:                 next;
                   7362:             }
                   7363:             if ($scope eq 'public') {
                   7364:                 $public = $key;
                   7365:                 last;
                   7366:             } elsif ($scope eq 'guest') {
                   7367:                 $guest = $key;
                   7368:             } elsif ($scope eq 'domains') {
                   7369:                 push(@domains,$key);
                   7370:             } elsif ($scope eq 'users') {
                   7371:                 push(@users,$key);
                   7372:             } elsif ($scope eq 'course') {
                   7373:                 push(@courses,$key);
                   7374:             } elsif ($scope eq 'group') {
                   7375:                 push(@groups,$key);
1.1172.2.77  raeburn  7376:             } elsif ($scope eq 'ip') {
                   7377:                 push(@ips,$key);
1.765     albertel 7378:             }
                   7379:         }
                   7380:         if ($public) {
                   7381:             return 'ok';
1.1172.2.77  raeburn  7382:         } elsif (@ips > 0) {
                   7383:             my $allowed;
                   7384:             foreach my $ipkey (@ips) {
                   7385:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7386:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7387:                         $allowed = 1;
                   7388:                         last;
                   7389:                     }
                   7390:                 }
                   7391:             }
                   7392:             if ($allowed) {
                   7393:                 return 'ok';
                   7394:             }
1.765     albertel 7395:         }
                   7396:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7397:             if ($guest) {
                   7398:                 return $guest;
                   7399:             }
                   7400:         } else {
                   7401:             if (@domains > 0) {
                   7402:                 foreach my $domkey (@domains) {
                   7403:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7404:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7405:                             return 'ok';
                   7406:                         }
                   7407:                     }
                   7408:                 }
                   7409:             }
                   7410:             if (@users > 0) {
                   7411:                 foreach my $userkey (@users) {
1.865     raeburn  7412:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7413:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7414:                             if (ref($item) eq 'HASH') {
                   7415:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7416:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7417:                                     return 'ok';
                   7418:                                 }
                   7419:                             }
                   7420:                         }
                   7421:                     } 
1.765     albertel 7422:                 }
                   7423:             }
                   7424:             my %roleshash;
                   7425:             my @courses_and_groups = @courses;
                   7426:             push(@courses_and_groups,@groups); 
                   7427:             if (@courses_and_groups > 0) {
                   7428:                 my (%allgroups,%allroles); 
                   7429:                 my ($start,$end,$role,$sec,$group);
                   7430:                 foreach my $envkey (%env) {
1.1060    raeburn  7431:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7432:                         my $cid = $2.'_'.$3; 
                   7433:                         if ($1 eq 'gr') {
                   7434:                             $group = $4;
                   7435:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7436:                         } else {
                   7437:                             if ($4 eq '') {
                   7438:                                 $sec = 'none';
                   7439:                             } else {
                   7440:                                 $sec = $4;
                   7441:                             }
                   7442:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7443:                         }
1.811     albertel 7444:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7445:                         my $cid = $2.'_'.$3;
                   7446:                         if ($4 eq '') {
                   7447:                             $sec = 'none';
                   7448:                         } else {
                   7449:                             $sec = $4;
                   7450:                         }
                   7451:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7452:                     }
                   7453:                 }
                   7454:                 if (keys(%allroles) == 0) {
                   7455:                     return;
                   7456:                 }
                   7457:                 foreach my $key (@courses_and_groups) {
                   7458:                     my %content = %{$$access_hash{$key}};
                   7459:                     my $cnum = $content{'number'};
                   7460:                     my $cdom = $content{'domain'};
                   7461:                     my $cid = $cdom.'_'.$cnum;
                   7462:                     if (!exists($allroles{$cid})) {
                   7463:                         next;
                   7464:                     }    
                   7465:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7466:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7467:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7468:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7469:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7470:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7471:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7472:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7473:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7474:                                         if (grep/^all$/,@sections) {
                   7475:                                             return 'ok';
                   7476:                                         } else {
                   7477:                                             if (grep/^$sec$/,@sections) {
                   7478:                                                 return 'ok';
                   7479:                                             }
                   7480:                                         }
                   7481:                                     }
                   7482:                                 }
                   7483:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7484:                                     if (grep/^none$/,@groups) {
                   7485:                                         return 'ok';
                   7486:                                     }
                   7487:                                 } else {
                   7488:                                     if (grep/^all$/,@groups) {
                   7489:                                         return 'ok';
                   7490:                                     } 
                   7491:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7492:                                         if (grep/^$group$/,@groups) {
                   7493:                                             return 'ok';
                   7494:                                         }
                   7495:                                     }
                   7496:                                 } 
                   7497:                             }
                   7498:                         }
                   7499:                     }
                   7500:                 }
                   7501:             }
                   7502:             if ($guest) {
                   7503:                 return $guest;
                   7504:             }
                   7505:         }
                   7506:     }
                   7507:     return;
                   7508: }
                   7509: 
                   7510: sub course_group_datechecker {
                   7511:     my ($dates,$now,$status) = @_;
                   7512:     my ($start,$end) = split(/\./,$dates);
                   7513:     if (!$start && !$end) {
                   7514:         return 'ok';
                   7515:     }
                   7516:     if (grep/^active$/,@{$status}) {
                   7517:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7518:             return 'ok';
                   7519:         }
                   7520:     }
                   7521:     if (grep/^previous$/,@{$status}) {
                   7522:         if ($end > $now ) {
                   7523:             return 'ok';
                   7524:         }
                   7525:     }
                   7526:     if (grep/^future$/,@{$status}) {
                   7527:         if ($start > $now) {
                   7528:             return 'ok';
                   7529:         }
                   7530:     }
                   7531:     return; 
                   7532: }
                   7533: 
                   7534: sub parse_portfolio_url {
                   7535:     my ($url) = @_;
                   7536: 
                   7537:     my ($type,$udom,$unum,$group,$file_name);
                   7538:     
1.823     albertel 7539:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7540: 	$type = 1;
                   7541:         $udom = $1;
                   7542:         $unum = $2;
                   7543:         $file_name = $3;
1.823     albertel 7544:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7545: 	$type = 2;
                   7546:         $udom = $1;
                   7547:         $unum = $2;
                   7548:         $group = $3;
                   7549:         $file_name = $3.'/'.$4;
                   7550:     }
                   7551:     if (wantarray) {
                   7552: 	return ($type,$udom,$unum,$file_name,$group);
                   7553:     }
                   7554:     return $type;
                   7555: }
                   7556: 
                   7557: sub is_portfolio_url {
                   7558:     my ($url) = @_;
                   7559:     return scalar(&parse_portfolio_url($url));
                   7560: }
                   7561: 
1.798     raeburn  7562: sub is_portfolio_file {
                   7563:     my ($file) = @_;
1.820     raeburn  7564:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7565:         return 1;
                   7566:     }
                   7567:     return;
                   7568: }
                   7569: 
1.976     raeburn  7570: sub usertools_access {
1.1084    raeburn  7571:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7572:     my ($access,%tools);
                   7573:     if ($context eq '') {
                   7574:         $context = 'tools';
                   7575:     }
                   7576:     if ($context eq 'requestcourses') {
                   7577:         %tools = (
                   7578:                       official   => 1,
                   7579:                       unofficial => 1,
1.1006    raeburn  7580:                       community  => 1,
1.1172.2.37  raeburn  7581:                       textbook   => 1,
1.985     raeburn  7582:                  );
1.1172.2.9  raeburn  7583:     } elsif ($context eq 'requestauthor') {
                   7584:         %tools = (
                   7585:                       requestauthor => 1,
                   7586:                  );
1.985     raeburn  7587:     } else {
                   7588:         %tools = (
                   7589:                       aboutme   => 1,
                   7590:                       blog      => 1,
1.1172.2.6  raeburn  7591:                       webdav    => 1,
1.985     raeburn  7592:                       portfolio => 1,
                   7593:                  );
                   7594:     }
1.976     raeburn  7595:     return if (!defined($tools{$tool}));
                   7596: 
1.1172.2.35  raeburn  7597:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7598:         $udom = $env{'user.domain'};
                   7599:         $uname = $env{'user.name'};
                   7600:     }
                   7601: 
1.978     raeburn  7602:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7603:         if ($action ne 'reload') {
1.985     raeburn  7604:             if ($context eq 'requestcourses') {
                   7605:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7606:             } elsif ($context eq 'requestauthor') {
                   7607:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7608:             } else {
                   7609:                 return $env{'environment.availabletools.'.$tool};
                   7610:             }
                   7611:         }
1.976     raeburn  7612:     }
                   7613: 
1.1172.2.9  raeburn  7614:     my ($toolstatus,$inststatus,$envkey);
                   7615:     if ($context eq 'requestauthor') {
                   7616:         $envkey = $context;
                   7617:     } else {
                   7618:         $envkey = $context.'.'.$tool;
                   7619:     }
1.976     raeburn  7620: 
1.985     raeburn  7621:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7622:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7623:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7624:         $inststatus = $env{'environment.inststatus'};
                   7625:     } else {
1.1084    raeburn  7626:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7627:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7628:             $inststatus = $userenvref->{'inststatus'};
                   7629:         } else {
1.1172.2.9  raeburn  7630:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7631:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7632:             $inststatus = $userenv{'inststatus'};
                   7633:         }
1.976     raeburn  7634:     }
                   7635: 
                   7636:     if ($toolstatus ne '') {
                   7637:         if ($toolstatus) {
                   7638:             $access = 1;
                   7639:         } else {
                   7640:             $access = 0;
                   7641:         }
                   7642:         return $access;
                   7643:     }
                   7644: 
1.1084    raeburn  7645:     my ($is_adv,%domdef);
                   7646:     if (ref($is_advref) eq 'HASH') {
                   7647:         $is_adv = $is_advref->{'is_adv'};
                   7648:     } else {
                   7649:         $is_adv = &is_advanced_user($udom,$uname);
                   7650:     }
                   7651:     if (ref($domdefref) eq 'HASH') {
                   7652:         %domdef = %{$domdefref};
                   7653:     } else {
                   7654:         %domdef = &get_domain_defaults($udom);
                   7655:     }
1.976     raeburn  7656:     if (ref($domdef{$tool}) eq 'HASH') {
                   7657:         if ($is_adv) {
                   7658:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7659:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7660:                     $access = 1;
                   7661:                 } else {
                   7662:                     $access = 0;
                   7663:                 }
                   7664:                 return $access;
                   7665:             }
                   7666:         }
                   7667:         if ($inststatus ne '') {
                   7668:             my ($hasaccess,$hasnoaccess);
                   7669:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7670:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7671:                     if ($domdef{$tool}{$affiliation}) {
                   7672:                         $hasaccess = 1;
                   7673:                     } else {
                   7674:                         $hasnoaccess = 1;
                   7675:                     }
                   7676:                 }
                   7677:             }
                   7678:             if ($hasaccess || $hasnoaccess) {
                   7679:                 if ($hasaccess) {
                   7680:                     $access = 1;
                   7681:                 } elsif ($hasnoaccess) {
                   7682:                     $access = 0; 
                   7683:                 }
                   7684:                 return $access;
                   7685:             }
                   7686:         } else {
                   7687:             if ($domdef{$tool}{'default'} ne '') {
                   7688:                 if ($domdef{$tool}{'default'}) {
                   7689:                     $access = 1;
                   7690:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7691:                     $access = 0;
                   7692:                 }
                   7693:                 return $access;
                   7694:             }
                   7695:         }
                   7696:     } else {
1.1172.2.6  raeburn  7697:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7698:             $access = 1;
                   7699:         } else {
                   7700:             $access = 0;
                   7701:         }
1.976     raeburn  7702:         return $access;
                   7703:     }
                   7704: }
                   7705: 
1.1050    raeburn  7706: sub is_course_owner {
                   7707:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7708:     if (($udom eq '') || ($uname eq '')) {
                   7709:         $udom = $env{'user.domain'};
                   7710:         $uname = $env{'user.name'};
                   7711:     }
                   7712:     unless (($udom eq '') || ($uname eq '')) {
                   7713:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7714:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7715:                 return 1;
                   7716:             } else {
                   7717:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7718:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7719:                     return 1;
                   7720:                 }
                   7721:             }
                   7722:         }
                   7723:     }
                   7724:     return;
                   7725: }
                   7726: 
1.976     raeburn  7727: sub is_advanced_user {
                   7728:     my ($udom,$uname) = @_;
1.1085    raeburn  7729:     if ($udom ne '' && $uname ne '') {
                   7730:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7731:             if (wantarray) {
                   7732:                 return ($env{'user.adv'},$env{'user.author'});
                   7733:             } else {
                   7734:                 return $env{'user.adv'};
                   7735:             }
1.1085    raeburn  7736:         }
                   7737:     }
1.976     raeburn  7738:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7739:     my %allroles;
1.1128    raeburn  7740:     my ($is_adv,$is_author);
1.976     raeburn  7741:     foreach my $role (keys(%roleshash)) {
                   7742:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7743:         my $area = '/'.$tdomain.'/'.$trest;
                   7744:         if ($sec ne '') {
                   7745:             $area .= '/'.$sec;
                   7746:         }
                   7747:         if (($area ne '') && ($trole ne '')) {
                   7748:             my $spec=$trole.'.'.$area;
                   7749:             if ($trole =~ /^cr\//) {
                   7750:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7751:             } elsif ($trole ne 'gr') {
                   7752:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7753:             }
1.1128    raeburn  7754:             if ($trole eq 'au') {
                   7755:                 $is_author = 1;
                   7756:             }
1.976     raeburn  7757:         }
                   7758:     }
                   7759:     foreach my $role (keys(%allroles)) {
                   7760:         last if ($is_adv);
                   7761:         foreach my $item (split(/:/,$allroles{$role})) {
                   7762:             if ($item ne '') {
                   7763:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7764:                 if ($privilege eq 'adv') {
                   7765:                     $is_adv = 1;
                   7766:                     last;
                   7767:                 }
                   7768:             }
                   7769:         }
                   7770:     }
1.1128    raeburn  7771:     if (wantarray) {
                   7772:         return ($is_adv,$is_author);
                   7773:     }
1.976     raeburn  7774:     return $is_adv;
                   7775: }
1.798     raeburn  7776: 
1.1035    raeburn  7777: sub check_can_request {
1.1036    raeburn  7778:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7779:     my $canreq = 0;
                   7780:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7781:     my @options = ('approval','validate','autolimit');
                   7782:     my $optregex = join('|',@options);
                   7783:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7784:         foreach my $type (@{$types}) {
                   7785:             if (&usertools_access($env{'user.name'},
                   7786:                                   $env{'user.domain'},
                   7787:                                   $type,undef,'requestcourses')) {
                   7788:                 $canreq ++;
1.1036    raeburn  7789:                 if (ref($request_domains) eq 'HASH') {
                   7790:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7791:                 }
1.1035    raeburn  7792:                 if ($dom eq $env{'user.domain'}) {
                   7793:                     $can_request->{$type} = 1;
                   7794:                 }
                   7795:             }
                   7796:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7797:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7798:                 if (@curr > 0) {
1.1036    raeburn  7799:                     foreach my $item (@curr) {
                   7800:                         if (ref($request_domains) eq 'HASH') {
                   7801:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7802:                             if ($otherdom ne '') {
                   7803:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7804:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7805:                                         push(@{$request_domains->{$type}},$otherdom);
                   7806:                                     }
                   7807:                                 } else {
                   7808:                                     push(@{$request_domains->{$type}},$otherdom);
                   7809:                                 }
                   7810:                             }
                   7811:                         }
                   7812:                     }
                   7813:                     unless($dom eq $env{'user.domain'}) {
                   7814:                         $canreq ++;
1.1035    raeburn  7815:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7816:                             $can_request->{$type} = 1;
                   7817:                         }
                   7818:                     }
                   7819:                 }
                   7820:             }
                   7821:         }
                   7822:     }
                   7823:     return $canreq;
                   7824: }
                   7825: 
1.341     www      7826: # ---------------------------------------------- Custom access rule evaluation
                   7827: 
                   7828: sub customaccess {
                   7829:     my ($priv,$uri)=@_;
1.807     albertel 7830:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7831:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7832:     $udom = &LONCAPA::clean_domain($udom);
                   7833:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7834:     my $access=0;
1.800     albertel 7835:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7836: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7837: 	if ($type eq 'user') {
                   7838: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7839: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7840: 		if ($tdom) {
                   7841: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7842: 		}
1.896     albertel 7843: 		if ($tuname) {
                   7844: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7845: 		}
                   7846: 		$access=($effect eq 'allow');
                   7847: 		last;
                   7848: 	    }
                   7849: 	} else {
                   7850: 	    if ($role) {
                   7851: 		if ($role ne $urole) { next; }
                   7852: 	    }
                   7853: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7854: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7855: 		if ($tdom) {
                   7856: 		    if ($tdom ne $udom) { next; }
                   7857: 		}
                   7858: 		if ($tcrs) {
                   7859: 		    if ($tcrs ne $ucrs) { next; }
                   7860: 		}
                   7861: 		if ($tsec) {
                   7862: 		    if ($tsec ne $usec) { next; }
                   7863: 		}
                   7864: 		$access=($effect eq 'allow');
                   7865: 		last;
                   7866: 	    }
                   7867: 	    if ($realm eq '' && $role eq '') {
                   7868: 		$access=($effect eq 'allow');
                   7869: 	    }
1.402     bowersj2 7870: 	}
1.341     www      7871:     }
                   7872:     return $access;
                   7873: }
                   7874: 
1.103     harris41 7875: # ------------------------------------------------- Check for a user privilege
1.12      www      7876: 
                   7877: sub allowed {
1.1172.2.118.  .8(raebu 7878:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7879:     my $ver_orguri=$uri;
1.439     www      7880:     $uri=&deversion($uri);
1.152     www      7881:     my $orguri=$uri;
1.52      www      7882:     $uri=&declutter($uri);
1.809     raeburn  7883: 
1.810     raeburn  7884:     if ($priv eq 'evb') {
                   7885: # Evade communication block restrictions for specified role in a course
                   7886:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7887:             return $1;
                   7888:         } else {
                   7889:             return;
                   7890:         }
                   7891:     }
                   7892: 
1.620     albertel 7893:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7894: # Free bre access to adm and meta resources
1.1172.2.118.  .13(raeb 7895:-21):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 7896: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7897: 	&& ($priv eq 'bre')) {
1.14      www      7898: 	return 'F';
1.159     www      7899:     }
                   7900: 
1.545     banghart 7901: # Free bre access to user's own portfolio contents
1.714     raeburn  7902:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7903:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7904: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7905:         my %setters;
                   7906:         my ($startblock,$endblock) = 
                   7907:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7908:         if ($startblock && $endblock) {
                   7909:             return 'B';
                   7910:         } else {
                   7911:             return 'F';
                   7912:         }
1.545     banghart 7913:     }
                   7914: 
1.762     raeburn  7915: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7916:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7917:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7918:         if (exists($env{'request.course.id'})) {
                   7919:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7920:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7921:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7922:                 my $courseprivid=$env{'request.course.id'};
                   7923:                 $courseprivid=~s/\_/\//;
                   7924:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7925:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7926:                     return $1; 
1.762     raeburn  7927:                 } else {
                   7928:                     if ($env{'request.course.sec'}) {
                   7929:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7930:                     }
                   7931:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7932:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7933:                         return $2;
                   7934:                     }
1.714     raeburn  7935:                 }
                   7936:             }
                   7937:         }
                   7938:     }
                   7939: 
1.159     www      7940: # Free bre to public access
                   7941: 
                   7942:     if ($priv eq 'bre') {
1.238     www      7943:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7944: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7945:            return 'F'; 
                   7946:         }
1.238     www      7947:         if ($copyright eq 'priv') {
                   7948:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7949: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7950: 		return '';
                   7951:             }
                   7952:         }
                   7953:         if ($copyright eq 'domain') {
                   7954:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7955: 	    unless (($env{'user.domain'} eq $1) ||
                   7956:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7957: 		return '';
                   7958:             }
1.262     matthew  7959:         }
1.620     albertel 7960:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7961:             # Library role, so allow browsing of resources in this domain.
                   7962:             return 'F';
1.238     www      7963:         }
1.341     www      7964:         if ($copyright eq 'custom') {
                   7965: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7966:         }
1.14      www      7967:     }
1.264     matthew  7968:     # Domain coordinator is trying to create a course
1.620     albertel 7969:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7970:         # uri is the requested domain in this case.
                   7971:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7972:         # a role of dc for the domain in question.
1.620     albertel 7973:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7974:     }
1.29      www      7975: 
1.52      www      7976:     my $thisallowed='';
                   7977:     my $statecond=0;
                   7978:     my $courseprivid='';
                   7979: 
1.1039    raeburn  7980:     my $ownaccess;
1.1043    raeburn  7981:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7982:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7983:         if ($uri eq '') {
                   7984:             $ownaccess = 1;
                   7985:         } else {
                   7986:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7987:                 my $udom = $env{'user.domain'};
                   7988:                 my $uname = $env{'user.name'};
                   7989:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7990:                     $ownaccess = 1;
1.1040    raeburn  7991:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7992:                     unless ($uri =~ m{\.\./}) {
                   7993:                         $ownaccess = 1;
                   7994:                     }
                   7995:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7996:                     my $now = time;
                   7997:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7998:                         my $adom = $1;
                   7999:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8000:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8001:                                 my ($start,$end) = split('.',$env{$key});
                   8002:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8003:                                     $ownaccess = 1;
                   8004:                                     last;
                   8005:                                 }
                   8006:                             }
                   8007:                         }
                   8008:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8009:                         my $adom = $1;
                   8010:                         my $aname = $2;
1.1042    raeburn  8011:                         foreach my $role ('ca','aa') { 
                   8012:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8013:                                 my ($start,$end) =
                   8014:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8015:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8016:                                     $ownaccess = 1;
                   8017:                                     last;
                   8018:                                 }
1.1039    raeburn  8019:                             }
                   8020:                         }
                   8021:                     }
                   8022:                 }
                   8023:             }
                   8024:         }
                   8025:     }
                   8026: 
1.52      www      8027: # Course
                   8028: 
1.620     albertel 8029:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8030:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8031:             $thisallowed.=$1;
                   8032:         }
1.52      www      8033:     }
1.29      www      8034: 
1.52      www      8035: # Domain
                   8036: 
1.620     albertel 8037:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8038:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8039:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8040:             $thisallowed.=$1;
                   8041:         }
1.12      www      8042:     }
1.52      www      8043: 
1.1141    raeburn  8044: # User who is not author or co-author might still be able to edit
                   8045: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8046:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8047:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8048:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8049:             $thisallowed.=$1;
                   8050:         }
                   8051:     }
                   8052: 
1.52      www      8053: # Course: uri itself is a course
1.66      www      8054:     my $courseuri=$uri;
                   8055:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8056:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8057: 
1.620     albertel 8058:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8059:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8060:         if ($priv eq 'mip') {
                   8061:             my $rem = $1;
                   8062:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8063:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8064:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8065:                 if ($cdom ne '') {
                   8066:                     my %passwdconf = &get_passwdconf($cdom);
                   8067:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8068:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8069:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8070:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8071:                                 unless (@inststatuses) {
                   8072:                                     @inststatuses = ('default');
                   8073:                                 }
                   8074:                                 foreach my $status (@inststatuses) {
                   8075:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8076:                                         $thisallowed.=$rem;
                   8077:                                     }
                   8078:                                 }
                   8079:                             }
                   8080:                         }
                   8081:                     }
                   8082:                 }
                   8083:             }
                   8084:         } else {
                   8085:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8086:                 $thisallowed.=$1;
                   8087:             }
1.1039    raeburn  8088:         }
1.12      www      8089:     }
1.29      www      8090: 
1.665     albertel 8091: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8092: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8093:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8094: 	$thisallowed='';
1.671     raeburn  8095:         my ($match)=&is_on_map($uri);
                   8096:         if ($match) {
                   8097:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8098:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8099:                 my $value = $1;
                   8100:                 if ($noblockcheck) {
                   8101:                     $thisallowed.=$value;
1.1162    raeburn  8102:                 } else {
1.1172.2.118.  .8(raebu 8103:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8104:                     if (@blockers > 0) {
                   8105:                         $thisallowed = 'B';
                   8106:                     } else {
                   8107:                         $thisallowed.=$value;
                   8108:                     }
1.1162    raeburn  8109:                 }
1.671     raeburn  8110:             }
                   8111:         } else {
1.705     albertel 8112:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8113:             if ($refuri) {
                   8114:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8115:                     $thisallowed='F';
1.671     raeburn  8116:                 } else {
                   8117:                     $refuri=&declutter($refuri);
                   8118:                     my ($match) = &is_on_map($refuri);
                   8119:                     if ($match) {
1.1172.2.65  raeburn  8120:                         if ($noblockcheck) {
1.1162    raeburn  8121:                             $thisallowed='F';
1.1172.2.65  raeburn  8122:                         } else {
1.1172.2.118.  .8(raebu 8123:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8124:                             if (@blockers > 0) {
                   8125:                                 $thisallowed = 'B';
                   8126:                             } else {
                   8127:                                 $thisallowed='F';
                   8128:                             }
1.1162    raeburn  8129:                         }
1.671     raeburn  8130:                     }
1.669     raeburn  8131:                 }
1.671     raeburn  8132:             }
                   8133:         }
1.314     www      8134:     }
1.492     albertel 8135: 
1.766     albertel 8136:     if ($priv eq 'bre'
                   8137: 	&& $thisallowed ne 'F' 
                   8138: 	&& $thisallowed ne '2'
                   8139: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8140: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8141:     }
1.1172.2.118.  .8(raebu 8142:20): 
1.52      www      8143: # Full access at system, domain or course-wide level? Exit.
1.29      www      8144:     if ($thisallowed=~/F/) {
                   8145: 	return 'F';
                   8146:     }
                   8147: 
1.52      www      8148: # If this is generating or modifying users, exit with special codes
1.29      www      8149: 
1.643     www      8150:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8151: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8152: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8153: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8154: 	    unless ($auname) { return $thisallowed; }
                   8155: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8156: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8157: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8158: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8159: 	}
1.52      www      8160: 	return $thisallowed;
                   8161:     }
                   8162: #
1.103     harris41 8163: # Gathered so far: system, domain and course wide privileges
1.52      www      8164: #
                   8165: # Course: See if uri or referer is an individual resource that is part of 
                   8166: # the course
                   8167: 
1.620     albertel 8168:     if ($env{'request.course.id'}) {
1.232     www      8169: 
1.1172.2.115  raeburn  8170: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8171: 
                   8172:         if ($priv eq 'mip') {
                   8173:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8174:                 return $thisallowed;
                   8175:             } else {
                   8176:                 return '';
                   8177:             }
                   8178:         }
                   8179: 
1.620     albertel 8180:        $courseprivid=$env{'request.course.id'};
                   8181:        if ($env{'request.course.sec'}) {
                   8182:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8183:        }
                   8184:        $courseprivid=~s/\_/\//;
                   8185:        my $checkreferer=1;
1.232     www      8186:        my ($match,$cond)=&is_on_map($uri);
                   8187:        if ($match) {
                   8188:            $statecond=$cond;
1.620     albertel 8189:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8190:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8191:                my $value = $1;
                   8192:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8193:                    if ($noblockcheck) {
1.1162    raeburn  8194:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8195:                    } else {
1.1172.2.118.  .8(raebu 8196:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8197:                        if (@blockers > 0) {
                   8198:                            $thisallowed = 'B';
                   8199:                        } else {
                   8200:                            $thisallowed.=$value;
                   8201:                        }
1.1162    raeburn  8202:                    }
                   8203:                } else {
                   8204:                    $thisallowed.=$value;
                   8205:                }
1.52      www      8206:                $checkreferer=0;
                   8207:            }
1.29      www      8208:        }
1.1172.2.118.  .8(raebu 8209:20): 
1.148     www      8210:        if ($checkreferer) {
1.620     albertel 8211: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8212:             unless ($refuri) {
1.800     albertel 8213:                 foreach my $key (keys(%env)) {
                   8214: 		    if ($key=~/^httpref\..*\*/) {
                   8215: 			my $pattern=$key;
1.156     www      8216:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8217:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8218:                         $pattern=~s/\//\\\//g;
1.152     www      8219:                         if ($orguri=~/$pattern/) {
1.800     albertel 8220: 			    $refuri=$env{$key};
1.148     www      8221:                         }
                   8222:                     }
1.191     harris41 8223:                 }
1.148     www      8224:             }
1.232     www      8225: 
1.148     www      8226:          if ($refuri) { 
1.152     www      8227: 	  $refuri=&declutter($refuri);
1.232     www      8228:           my ($match,$cond)=&is_on_map($refuri);
                   8229:             if ($match) {
                   8230:               my $refstatecond=$cond;
1.620     albertel 8231:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8232:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8233:                   my $value = $1;
                   8234:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8235:                       if ($noblockcheck) {
1.1162    raeburn  8236:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8237:                       } else {
1.1172.2.118.  .8(raebu 8238:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8239:                           if (@blockers > 0) {
                   8240:                               $thisallowed = 'B';
                   8241:                           } else {
                   8242:                               $thisallowed.=$value;
                   8243:                           }
1.1162    raeburn  8244:                       }
                   8245:                   } else {
                   8246:                       $thisallowed.=$value;
                   8247:                   }
1.53      www      8248:                   $uri=$refuri;
                   8249:                   $statecond=$refstatecond;
1.52      www      8250:               }
                   8251:           }
1.148     www      8252:         }
1.29      www      8253:        }
1.52      www      8254:    }
1.29      www      8255: 
1.52      www      8256: #
1.103     harris41 8257: # Gathered now: all privileges that could apply, and condition number
1.52      www      8258: # 
                   8259: #
                   8260: # Full or no access?
                   8261: #
1.29      www      8262: 
1.52      www      8263:     if ($thisallowed=~/F/) {
                   8264: 	return 'F';
                   8265:     }
1.29      www      8266: 
1.52      www      8267:     unless ($thisallowed) {
                   8268:         return '';
                   8269:     }
1.29      www      8270: 
1.52      www      8271: # Restrictions exist, deal with them
                   8272: #
                   8273: #   C:according to course preferences
                   8274: #   R:according to resource settings
                   8275: #   L:unless locked
                   8276: #   X:according to user session state
                   8277: #
                   8278: 
                   8279: # Possibly locked functionality, check all courses
1.54      www      8280: # Locks might take effect only after 10 minutes cache expiration for other
                   8281: # courses, and 2 minutes for current course
1.52      www      8282: 
                   8283:     my $envkey;
                   8284:     if ($thisallowed=~/L/) {
1.1000    raeburn  8285:         foreach $envkey (keys(%env)) {
1.54      www      8286:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8287:                my $courseid=$2;
                   8288:                my $roleid=$1.'.'.$2;
1.92      www      8289:                $courseid=~s/^\///;
1.54      www      8290:                my $expiretime=600;
1.620     albertel 8291:                if ($env{'request.role'} eq $roleid) {
1.54      www      8292: 		  $expiretime=120;
                   8293:                }
                   8294: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8295:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8296:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8297: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8298:                }
1.620     albertel 8299:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8300:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8301: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8302:                        &log($env{'user.domain'},$env{'user.name'},
                   8303:                             $env{'user.home'},
1.57      www      8304:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8305:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8306:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8307: 		       return '';
                   8308:                    }
                   8309:                }
1.620     albertel 8310:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8311:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8312: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8313:                        &log($env{'user.domain'},$env{'user.name'},
                   8314:                             $env{'user.home'},
1.57      www      8315:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8316:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8317:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8318: 		       return '';
                   8319:                    }
                   8320:                }
                   8321: 	   }
1.29      www      8322:        }
1.52      www      8323:     }
1.1172.2.118.  .8(raebu 8324:20): 
1.52      www      8325: #
                   8326: # Rest of the restrictions depend on selected course
                   8327: #
                   8328: 
1.620     albertel 8329:     unless ($env{'request.course.id'}) {
1.766     albertel 8330: 	if ($thisallowed eq 'A') {
                   8331: 	    return 'A';
1.814     raeburn  8332:         } elsif ($thisallowed eq 'B') {
                   8333:             return 'B';
1.766     albertel 8334: 	} else {
                   8335: 	    return '1';
                   8336: 	}
1.52      www      8337:     }
1.29      www      8338: 
1.52      www      8339: #
                   8340: # Now user is definitely in a course
                   8341: #
1.53      www      8342: 
                   8343: 
                   8344: # Course preferences
                   8345: 
                   8346:    if ($thisallowed=~/C/) {
1.620     albertel 8347:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8348:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8349:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8350: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8351: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8352: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8353: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8354: 			$env{'request.course.id'});
                   8355: 	   }
1.237     www      8356:            return '';
                   8357:        }
                   8358: 
1.620     albertel 8359:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8360: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8361: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8362: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8363: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8364: 			$env{'request.course.id'});
                   8365: 	   }
1.54      www      8366:            return '';
                   8367:        }
1.53      www      8368:    }
                   8369: 
                   8370: # Resource preferences
                   8371: 
                   8372:    if ($thisallowed=~/R/) {
1.620     albertel 8373:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8374:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8375: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8376: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8377: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8378: 	   }
                   8379: 	   return '';
1.54      www      8380:        }
1.53      www      8381:    }
1.30      www      8382: 
1.246     www      8383: # Restricted by state or randomout?
1.30      www      8384: 
1.52      www      8385:    if ($thisallowed=~/X/) {
1.620     albertel 8386:       if ($env{'acc.randomout'}) {
1.579     albertel 8387: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8388:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8389:             return ''; 
                   8390:          }
1.247     www      8391:       }
                   8392:       if (&condval($statecond)) {
1.52      www      8393: 	 return '2';
                   8394:       } else {
                   8395:          return '';
                   8396:       }
                   8397:    }
1.30      www      8398: 
1.766     albertel 8399:     if ($thisallowed eq 'A') {
                   8400: 	return 'A';
1.814     raeburn  8401:     } elsif ($thisallowed eq 'B') {
                   8402:         return 'B';
1.766     albertel 8403:     }
1.52      www      8404:    return 'F';
1.232     www      8405: }
1.1162    raeburn  8406: 
1.1172.2.13  raeburn  8407: # ------------------------------------------- Check construction space access
                   8408: 
                   8409: sub constructaccess {
                   8410:     my ($url,$setpriv)=@_;
                   8411: 
                   8412: # We do not allow editing of previous versions of files
                   8413:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8414: 
                   8415: # Get username and domain from URL
                   8416:     my ($ownername,$ownerdomain,$ownerhome);
                   8417: 
                   8418:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8419:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8420: 
                   8421: # The URL does not really point to any authorspace, forget it
                   8422:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8423: 
                   8424: # Now we need to see if the user has access to the authorspace of
                   8425: # $ownername at $ownerdomain
                   8426: 
                   8427:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8428: # Real author for this?
                   8429:        $ownerhome = $env{'user.home'};
                   8430:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8431:           return ($ownername,$ownerdomain,$ownerhome);
                   8432:        }
                   8433:     } else {
                   8434: # Co-author for this?
                   8435:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8436:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8437:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8438:             return ($ownername,$ownerdomain,$ownerhome);
                   8439:         }
                   8440:     }
                   8441: 
                   8442: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8443: # we might as well leave
                   8444:    unless ($setpriv) { return ''; }
                   8445: 
                   8446: # Backdoor access?
                   8447:     my $allowed=&allowed('eco',$ownerdomain);
                   8448: # Nope
                   8449:     unless ($allowed) { return ''; }
                   8450: # Looks like we may have access, but could be locked by the owner of the construction space
                   8451:     if ($allowed eq 'U') {
                   8452:         my %blocked=&get('environment',['domcoord.author'],
                   8453:                          $ownerdomain,$ownername);
                   8454: # Is blocked by owner
                   8455:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8456:     }
                   8457:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8458: # Grant temporary access
                   8459:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8460:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8461:         if (!$update) { $update = $then; }
                   8462:         my $refresh=$env{'user.refresh.time'};
                   8463:         if (!$refresh) { $refresh = $update; }
                   8464:         my $now = time;
                   8465:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8466:                            $now,'ca','constructaccess');
                   8467:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8468:         return($ownername,$ownerdomain,$ownerhome);
                   8469:     }
                   8470: # No business here
                   8471:     return '';
                   8472: }
                   8473: 
1.1172.2.66  raeburn  8474: # ----------------------------------------------------------- Content Blocking
                   8475: 
                   8476: {
                   8477: # Caches for faster Course Contents display where content blocking
                   8478: # is in operation (i.e., interval param set) for timed quiz.
                   8479: #
                   8480: # User for whom data are being temporarily cached.
                   8481: my $cacheduser='';
1.1172.2.118.  .8(raebu 8482:20): # Course for which data are being temporarily cached.
                   8483:20): my $cachedcid='';
1.1172.2.66  raeburn  8484: # Cached blockers for this user (a hash of blocking items).
                   8485: my %cachedblockers=();
                   8486: # When the data were last cached.
                   8487: my $cachedlast='';
                   8488: 
                   8489: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8490:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8491:     if (($uname ne '') && ($udom ne '')) {
                   8492:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8493:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8494:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8495:             return;
                   8496:         }
                   8497:     }
                   8498:     $cachedlast=time;
                   8499:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8500:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8501:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8502:20):     return;
1.1172.2.66  raeburn  8503: }
                   8504: 
1.1162    raeburn  8505: sub get_comm_blocks {
                   8506:     my ($cdom,$cnum) = @_;
                   8507:     if ($cdom eq '' || $cnum eq '') {
                   8508:         return unless ($env{'request.course.id'});
                   8509:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8510:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8511:     }
                   8512:     my %commblocks;
                   8513:     my $hashid=$cdom.'_'.$cnum;
                   8514:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8515:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8516:         %commblocks = %{$blocksref};
                   8517:     } else {
                   8518:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8519:         my $cachetime = 600;
                   8520:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8521:     }
                   8522:     return %commblocks;
                   8523: }
                   8524: 
1.1172.2.66  raeburn  8525: sub get_commblock_resources {
                   8526:     my ($blocks) = @_;
                   8527:     my %blockers = ();
                   8528:     return %blockers unless ($env{'request.course.id'});
                   8529:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8530:     my %commblocks;
                   8531:     if (ref($blocks) eq 'HASH') {
                   8532:         %commblocks = %{$blocks};
                   8533:     } else {
                   8534:         %commblocks = &get_comm_blocks();
                   8535:     }
1.1172.2.66  raeburn  8536:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8537:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8538:     return %blockers unless (ref($navmap));
                   8539:     my $now = time;
1.1162    raeburn  8540:     foreach my $block (keys(%commblocks)) {
                   8541:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8542:             my ($start,$end) = ($1,$2);
                   8543:             if ($start <= $now && $end >= $now) {
                   8544:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8545:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8546:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8547:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8548:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8549:                             }
                   8550:                         }
                   8551:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8552:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8553:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8554:                             }
                   8555:                         }
                   8556:                     }
                   8557:                 }
                   8558:             }
                   8559:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8560:             my $item = $1;
1.1163    raeburn  8561:             my @to_test;
1.1162    raeburn  8562:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8563:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8564:                     my @interval;
                   8565:                     my $type = 'map';
                   8566:                     if ($item eq 'course') {
                   8567:                         $type = 'course';
                   8568:                         @interval=&EXT("resource.0.interval");
                   8569:                     } else {
                   8570:                         if ($item =~ /___\d+___/) {
                   8571:                             $type = 'resource';
                   8572:                             @interval=&EXT("resource.0.interval",$item);
                   8573:                             if (ref($navmap)) {
                   8574:                                 my $res = $navmap->getBySymb($item);
                   8575:                                 push(@to_test,$res);
                   8576:                             }
1.1162    raeburn  8577:                         } else {
1.1172.2.66  raeburn  8578:                             my $mapsymb = &symbread($item,1);
                   8579:                             if ($mapsymb) {
                   8580:                                 if (ref($navmap)) {
                   8581:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118.  .11(raeb 8582:-20):                                     if (ref($mapres)) {
                   8583:-20):                                         my $first = $mapres->map_start();
                   8584:-20):                                         my $finish = $mapres->map_finish();
                   8585:-20):                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8586:-20):                                         if (ref($it)) {
                   8587:-20):                                             my $res;
                   8588:-20):                                             while ($res = $it->next(undef,1)) {
                   8589:-20):                                                 next unless (ref($res));
                   8590:-20):                                                 my $symb = $res->symb();
                   8591:-20):                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8592:-20):                                                 @interval=&EXT("resource.0.interval",$symb);
                   8593:-20):                                                 if ($interval[1] eq 'map') {
                   8594:-20):                                                     if ($res->answerable()) {
                   8595:-20):                                                         push(@to_test,$res);
                   8596:-20):                                                         last;
                   8597:-20):                                                     }
                   8598:-20):                                                 }
1.1162    raeburn  8599:                                             }
                   8600:                                         }
                   8601:                                     }
                   8602:                                 }
                   8603:                             }
                   8604:                         }
1.1172.2.66  raeburn  8605:                     }
1.1172.2.118.  .1(raebu 8606:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8607:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8608:                         my $first_access;
                   8609:                         if ($type eq 'resource') {
                   8610:                             $first_access=&get_first_access($interval[1],$item);
                   8611:                         } elsif ($type eq 'map') {
                   8612:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8613:                         } else {
                   8614:                             $first_access=&get_first_access($interval[1]);
                   8615:                         }
                   8616:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8617:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8618:                             if ($timesup > $now) {
                   8619:                                 my $activeblock;
                   8620:                                 foreach my $res (@to_test) {
                   8621:                                     if ($res->answerable()) {
                   8622:                                         $activeblock = 1;
                   8623:                                         last;
                   8624:                                     }
                   8625:                                 }
                   8626:                                 if ($activeblock) {
                   8627:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8628:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8629:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8630:                                          }
                   8631:                                     }
                   8632:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8633:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8634:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8635:                                         }
1.1162    raeburn  8636:                                     }
                   8637:                                 }
                   8638:                             }
                   8639:                         }
                   8640:                     }
                   8641:                 }
                   8642:             }
                   8643:         }
                   8644:     }
1.1172.2.66  raeburn  8645:     return %blockers;
1.1162    raeburn  8646: }
                   8647: 
1.1172.2.66  raeburn  8648: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8649:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8650:     my @blockers;
                   8651:     return unless ($env{'request.course.id'});
                   8652:     return unless ($priv eq 'bre');
                   8653:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8654:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8655:20):     my %blockinfo;
                   8656:20):     if (ref($blocks) eq 'HASH') {
                   8657:20):         %blockinfo = &get_commblock_resources($blocks);
                   8658:20):     } else {
                   8659:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8660:20):         %blockinfo = %cachedblockers;
                   8661:20):     }
                   8662:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8663:     my (%possibles,@symbs);
                   8664:     if (!$symb) {
1.1172.2.118.  .9(raebu 8665:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8666:     }
1.1172.2.66  raeburn  8667:     if ($symb) {
                   8668:         @symbs = ($symb);
                   8669:     } elsif (keys(%possibles)) {
                   8670:         @symbs = keys(%possibles);
                   8671:     }
                   8672:     my $noblock;
                   8673:     foreach my $symb (@symbs) {
                   8674:         last if ($noblock);
                   8675:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8676:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8677:             if ($block =~ /^firstaccess____(.+)$/) {
                   8678:                 my $item = $1;
1.1172.2.118.  .8(raebu 8679:20):                 unless ($blocked) {
                   8680:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8681:20):                         $noblock = 1;
                   8682:20):                         last;
                   8683:20):                     }
1.1172.2.66  raeburn  8684:                 }
1.1162    raeburn  8685:             }
1.1172.2.118.  .9(raebu 8686:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8687:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8688:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8689:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8690:                             push(@blockers,$block);
                   8691:                         }
                   8692:                     }
                   8693:                 }
1.1172.2.118.  .9(raebu 8694:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8695:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8696:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8697:20):                             push(@blockers,$block);
                   8698:20):                         }
1.1172.2.66  raeburn  8699:                     }
                   8700:                 }
1.1162    raeburn  8701:             }
                   8702:         }
                   8703:     }
1.1172.2.118.  .8(raebu 8704:20):     unless ($noblock) {
                   8705:20):         return @blockers;
                   8706:20):     }
                   8707:20):     return;
1.1172.2.66  raeburn  8708: }
1.1162    raeburn  8709: }
                   8710: 
1.1172.2.66  raeburn  8711: # -------------------------------- Deversion and split uri into path an filename
                   8712: 
1.1133    foxr     8713: #
1.1172.2.66  raeburn  8714: #   Removes the version from a URI and
1.1133    foxr     8715: #   splits it in to its filename and path to the filename.
                   8716: #   Seems like File::Basename could have done this more clearly.
                   8717: #   Parameters:
                   8718: #      $uri   - input URI
                   8719: #   Returns:
                   8720: #     Two element list consisting of 
                   8721: #     $pathname  - the URI up to and excluding the trailing /
                   8722: #     $filename  - The part of the URI following the last /
                   8723: #  NOTE:
                   8724: #    Another realization of this is simply:
                   8725: #    use File::Basename;
                   8726: #    ...
                   8727: #    $uri = shift;
                   8728: #    $filename = basename($uri);
                   8729: #    $path     = dirname($uri);
                   8730: #    return ($filename, $path);
                   8731: #
                   8732: #     The implementation below is probably faster however.
                   8733: #
1.710     albertel 8734: sub split_uri_for_cond {
                   8735:     my $uri=&deversion(&declutter(shift));
                   8736:     my @uriparts=split(/\//,$uri);
                   8737:     my $filename=pop(@uriparts);
                   8738:     my $pathname=join('/',@uriparts);
                   8739:     return ($pathname,$filename);
                   8740: }
1.232     www      8741: # --------------------------------------------------- Is a resource on the map?
                   8742: 
                   8743: sub is_on_map {
1.710     albertel 8744:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8745:     #Trying to find the conditional for the file
1.620     albertel 8746:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8747: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8748:     if ($match) {
1.289     bowersj2 8749: 	return (1,$1);
                   8750:     } else {
1.434     www      8751: 	return (0,0);
1.289     bowersj2 8752:     }
1.12      www      8753: }
                   8754: 
1.427     www      8755: # --------------------------------------------------------- Get symb from alias
                   8756: 
                   8757: sub get_symb_from_alias {
                   8758:     my $symb=shift;
                   8759:     my ($map,$resid,$url)=&decode_symb($symb);
                   8760: # Already is a symb
                   8761:     if ($url) { return $symb; }
                   8762: # Must be an alias
                   8763:     my $aliassymb='';
                   8764:     my %bighash;
1.620     albertel 8765:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8766:                             &GDBM_READER(),0640)) {
                   8767:         my $rid=$bighash{'mapalias_'.$symb};
                   8768: 	if ($rid) {
                   8769: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8770: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8771: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8772: 	}
                   8773:         untie %bighash;
                   8774:     }
                   8775:     return $aliassymb;
                   8776: }
                   8777: 
1.12      www      8778: # ----------------------------------------------------------------- Define Role
                   8779: 
                   8780: sub definerole {
                   8781:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8782:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8783:     foreach my $role (split(':',$sysrole)) {
                   8784: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8785:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8786:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8787: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8788:                return "refused:s:$crole&$cqual"; 
                   8789:             }
                   8790:         }
1.191     harris41 8791:     }
1.800     albertel 8792:     foreach my $role (split(':',$domrole)) {
                   8793: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8794:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8795:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8796: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8797:                return "refused:d:$crole&$cqual"; 
                   8798:             }
                   8799:         }
1.191     harris41 8800:     }
1.800     albertel 8801:     foreach my $role (split(':',$courole)) {
                   8802: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8803:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8804:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8805: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8806:                return "refused:c:$crole&$cqual"; 
                   8807:             }
                   8808:         }
1.191     harris41 8809:     }
1.1172.2.84  raeburn  8810:     my $uhome;
                   8811:     if (($uname ne '') && ($udom ne '')) {
                   8812:         $uhome = &homeserver($uname,$udom);
                   8813:         return $uhome if ($uhome eq 'no_host');
                   8814:     } else {
                   8815:         $uname = $env{'user.name'};
                   8816:         $udom = $env{'user.domain'};
                   8817:         $uhome = $env{'user.home'};
                   8818:     }
1.620     albertel 8819:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8820:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8821:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8822:     return reply($command,$uhome);
1.12      www      8823:   } else {
                   8824:     return 'refused';
                   8825:   }
1.105     harris41 8826: }
                   8827: 
                   8828: # ---------------- Make a metadata query against the network of library servers
                   8829: 
                   8830: sub metadata_query {
1.1172.2.33  raeburn  8831:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8832:     my %rhash;
1.845     albertel 8833:     my %libserv = &all_library();
1.244     matthew  8834:     my @server_list = (defined($server_array) ? @$server_array
                   8835:                                               : keys(%libserv) );
                   8836:     for my $server (@server_list) {
1.1172.2.33  raeburn  8837:         my $domains = '';
                   8838:         if (ref($domains_hash) eq 'HASH') {
                   8839:             $domains = $domains_hash->{$server};    
                   8840:         }
1.118     harris41 8841: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8842: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8843: 	    $rhash{$server}=$reply;
                   8844: 	}
                   8845: 	else {
                   8846: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8847: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8848: 			     $server);
                   8849: 	    $rhash{$server}=$reply;
                   8850: 	}
1.112     harris41 8851:     }
1.118     harris41 8852:     return \%rhash;
1.240     www      8853: }
                   8854: 
                   8855: # ----------------------------------------- Send log queries and wait for reply
                   8856: 
                   8857: sub log_query {
                   8858:     my ($uname,$udom,$query,%filters)=@_;
                   8859:     my $uhome=&homeserver($uname,$udom);
                   8860:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8861:     my $uhost=&hostname($uhome);
1.800     albertel 8862:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8863:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8864:                        $uhome);
1.479     albertel 8865:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8866:     return get_query_reply($queryid);
                   8867: }
                   8868: 
1.818     raeburn  8869: # -------------------------- Update MySQL table for portfolio file
                   8870: 
                   8871: sub update_portfolio_table {
1.821     raeburn  8872:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8873:     if ($group ne '') {
                   8874:         $file_name =~s /^\Q$group\E//;
                   8875:     }
1.818     raeburn  8876:     my $homeserver = &homeserver($uname,$udom);
                   8877:     my $queryid=
1.821     raeburn  8878:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8879:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8880:     my $reply = &get_query_reply($queryid);
                   8881:     return $reply;
                   8882: }
                   8883: 
1.899     raeburn  8884: # -------------------------- Update MySQL allusers table
                   8885: 
                   8886: sub update_allusers_table {
                   8887:     my ($uname,$udom,$names) = @_;
                   8888:     my $homeserver = &homeserver($uname,$udom);
                   8889:     my $queryid=
                   8890:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8891:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8892:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8893:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8894:                'generation='.&escape($names->{'generation'}).'%%'.
                   8895:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8896:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8897:     return;
1.899     raeburn  8898: }
                   8899: 
1.508     raeburn  8900: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8901: 
                   8902: sub fetch_enrollment_query {
1.511     raeburn  8903:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8904:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8905:     my $maxtries = 1;
1.508     raeburn  8906:     if ($context eq 'automated') {
                   8907:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8908:         $sleep = 2;
                   8909:         $loopmax = 100;
1.547     raeburn  8910:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8911:     } else {
                   8912:         $homeserver = &homeserver($cnum,$dom);
                   8913:     }
1.838     albertel 8914:     my $host=&hostname($homeserver);
1.506     raeburn  8915:     my $cmd = '';
1.1000    raeburn  8916:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8917:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8918:     }
                   8919:     $cmd =~ s/%%$//;
                   8920:     $cmd = &escape($cmd);
                   8921:     my $query = 'fetchenrollment';
1.620     albertel 8922:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8923:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8924:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8925:         return 'error: '.$queryid;
                   8926:     }
1.1172.2.93  raeburn  8927:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8928:     my $tries = 1;
                   8929:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8930:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8931:         $tries ++;
                   8932:     }
1.526     raeburn  8933:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8934:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8935:     } else {
1.901     albertel 8936:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8937:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8938:             foreach my $line (@responses) {
                   8939:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8940:                 $$replyref{$key} = $value;
                   8941:             }
                   8942:         } else {
1.1117    foxr     8943:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8944:             foreach my $line (@responses) {
                   8945:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8946:                 $$replyref{$key} = $value;
                   8947:                 if ($value > 0) {
1.800     albertel 8948:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8949:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8950:                         my $destname = $pathname.'/'.$filename;
                   8951:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8952:                         if ($xml_classlist =~ /^error/) {
                   8953:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8954:                         } else {
1.1172.2.96  raeburn  8955:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8956:                                 print FILE &unescape($xml_classlist);
                   8957:                                 close(FILE);
1.526     raeburn  8958:                             } else {
                   8959:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8960:                             }
                   8961:                         }
                   8962:                     }
                   8963:                 }
                   8964:             }
                   8965:         }
                   8966:         return 'ok';
                   8967:     }
                   8968:     return 'error';
                   8969: }
                   8970: 
1.242     www      8971: sub get_query_reply {
1.1172.2.79  raeburn  8972:     my ($queryid,$sleep,$loopmax) = @_;
                   8973:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8974:         $sleep = 0.2;
                   8975:     }
                   8976:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8977:         $loopmax = 100;
                   8978:     }
1.1117    foxr     8979:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8980:     my $reply='';
1.1172.2.79  raeburn  8981:     for (1..$loopmax) {
                   8982: 	sleep($sleep);
1.240     www      8983:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8984: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8985: 		$reply = join('',<$fh>);
                   8986: 		close($fh);
1.240     www      8987: 	   } else { return 'error: reply_file_error'; }
1.242     www      8988:            return &unescape($reply);
                   8989: 	}
1.240     www      8990:     }
1.242     www      8991:     return 'timeout:'.$queryid;
1.240     www      8992: }
                   8993: 
                   8994: sub courselog_query {
1.241     www      8995: #
                   8996: # possible filters:
                   8997: # url: url or symb
                   8998: # username
                   8999: # domain
                   9000: # action: view, submit, grade
                   9001: # start: timestamp
                   9002: # end: timestamp
                   9003: #
1.240     www      9004:     my (%filters)=@_;
1.620     albertel 9005:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9006:     if ($filters{'url'}) {
                   9007: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9008:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9009:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9010:     }
1.620     albertel 9011:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9012:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9013:     return &log_query($cname,$cdom,'courselog',%filters);
                   9014: }
                   9015: 
                   9016: sub userlog_query {
1.858     raeburn  9017: #
                   9018: # possible filters:
                   9019: # action: log check role
                   9020: # start: timestamp
                   9021: # end: timestamp
                   9022: #
1.240     www      9023:     my ($uname,$udom,%filters)=@_;
                   9024:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9025: }
                   9026: 
1.506     raeburn  9027: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9028: 
                   9029: sub auto_run {
1.508     raeburn  9030:     my ($cnum,$cdom) = @_;
1.876     raeburn  9031:     my $response = 0;
                   9032:     my $settings;
                   9033:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9034:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9035:         $settings = $domconfig{'autoenroll'};
                   9036:         if ($settings->{'run'} eq '1') {
                   9037:             $response = 1;
                   9038:         }
                   9039:     } else {
1.934     raeburn  9040:         my $homeserver;
                   9041:         if (&is_course($cdom,$cnum)) {
                   9042:             $homeserver = &homeserver($cnum,$cdom);
                   9043:         } else {
                   9044:             $homeserver = &domain($cdom,'primary');
                   9045:         }
                   9046:         if ($homeserver ne 'no_host') {
                   9047:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9048:         }
1.876     raeburn  9049:     }
1.506     raeburn  9050:     return $response;
                   9051: }
1.776     albertel 9052: 
1.506     raeburn  9053: sub auto_get_sections {
1.508     raeburn  9054:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9055:     my $homeserver;
                   9056:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9057:         $homeserver = &homeserver($cnum,$cdom);
                   9058:     }
                   9059:     if (!defined($homeserver)) { 
                   9060:         if ($cdom =~ /^$match_domain$/) {
                   9061:             $homeserver = &domain($cdom,'primary');
                   9062:         }
                   9063:     }
                   9064:     my @secs;
                   9065:     if (defined($homeserver)) {
                   9066:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9067:         unless ($response eq 'refused') {
                   9068:             @secs = split(/:/,$response);
                   9069:         }
1.506     raeburn  9070:     }
                   9071:     return @secs;
                   9072: }
1.776     albertel 9073: 
1.506     raeburn  9074: sub auto_new_course {
1.1099    raeburn  9075:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9076:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9077:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9078:     return $response;
                   9079: }
1.776     albertel 9080: 
1.506     raeburn  9081: sub auto_validate_courseID {
1.508     raeburn  9082:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9083:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9084:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9085:     return $response;
                   9086: }
1.776     albertel 9087: 
1.1007    raeburn  9088: sub auto_validate_instcode {
1.1020    raeburn  9089:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9090:     my ($homeserver,$response);
                   9091:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9092:         $homeserver = &homeserver($cnum,$cdom);
                   9093:     }
                   9094:     if (!defined($homeserver)) {
                   9095:         if ($cdom =~ /^$match_domain$/) {
                   9096:             $homeserver = &domain($cdom,'primary');
                   9097:         }
                   9098:     }
1.1065    raeburn  9099:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9100:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9101:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9102:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9103: }
                   9104: 
1.506     raeburn  9105: sub auto_create_password {
1.873     raeburn  9106:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9107:     my ($homeserver,$response);
1.506     raeburn  9108:     my $create_passwd = 0;
                   9109:     my $authchk = '';
1.873     raeburn  9110:     if ($udom =~ /^$match_domain$/) {
                   9111:         $homeserver = &domain($udom,'primary');
                   9112:     }
                   9113:     if ($homeserver eq '') {
                   9114:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9115:             $homeserver = &homeserver($cnum,$cdom);
                   9116:         }
                   9117:     }
                   9118:     if ($homeserver eq '') {
                   9119:         $authchk = 'nodomain';
1.506     raeburn  9120:     } else {
1.873     raeburn  9121:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9122:         if ($response eq 'refused') {
                   9123:             $authchk = 'refused';
                   9124:         } else {
1.901     albertel 9125:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9126:         }
1.506     raeburn  9127:     }
                   9128:     return ($authparam,$create_passwd,$authchk);
                   9129: }
                   9130: 
1.706     raeburn  9131: sub auto_photo_permission {
                   9132:     my ($cnum,$cdom,$students) = @_;
                   9133:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9134:     my ($outcome,$perm_reqd,$conditions) = 
                   9135: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9136:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9137: 	return (undef,undef);
                   9138:     }
1.706     raeburn  9139:     return ($outcome,$perm_reqd,$conditions);
                   9140: }
                   9141: 
                   9142: sub auto_checkphotos {
                   9143:     my ($uname,$udom,$pid) = @_;
                   9144:     my $homeserver = &homeserver($uname,$udom);
                   9145:     my ($result,$resulttype);
                   9146:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9147: 				   &escape($uname).':'.&escape($pid),
                   9148: 				   $homeserver));
1.709     albertel 9149:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9150: 	return (undef,undef);
                   9151:     }
1.706     raeburn  9152:     if ($outcome) {
                   9153:         ($result,$resulttype) = split(/:/,$outcome);
                   9154:     } 
                   9155:     return ($result,$resulttype);
                   9156: }
                   9157: 
                   9158: sub auto_photochoice {
                   9159:     my ($cnum,$cdom) = @_;
                   9160:     my $homeserver = &homeserver($cnum,$cdom);
                   9161:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9162: 						       &escape($cdom),
                   9163: 						       $homeserver)));
1.709     albertel 9164:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9165: 	return (undef,undef);
                   9166:     }
1.706     raeburn  9167:     return ($update,$comment);
                   9168: }
                   9169: 
                   9170: sub auto_photoupdate {
                   9171:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9172:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9173:     my $host=&hostname($homeserver);
1.706     raeburn  9174:     my $cmd = '';
                   9175:     my $maxtries = 1;
1.800     albertel 9176:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9177:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9178:     }
                   9179:     $cmd =~ s/%%$//;
                   9180:     $cmd = &escape($cmd);
                   9181:     my $query = 'institutionalphotos';
                   9182:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9183:     unless ($queryid=~/^\Q$host\E\_/) {
                   9184:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9185:         return 'error: '.$queryid;
                   9186:     }
                   9187:     my $reply = &get_query_reply($queryid);
                   9188:     my $tries = 1;
                   9189:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9190:         $reply = &get_query_reply($queryid);
                   9191:         $tries ++;
                   9192:     }
                   9193:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9194:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9195:     } else {
                   9196:         my @responses = split(/:/,$reply);
                   9197:         my $outcome = shift(@responses); 
                   9198:         foreach my $item (@responses) {
                   9199:             my ($key,$value) = split(/=/,$item);
                   9200:             $$photo{$key} = $value;
                   9201:         }
                   9202:         return $outcome;
                   9203:     }
                   9204:     return 'error';
                   9205: }
                   9206: 
1.521     raeburn  9207: sub auto_instcode_format {
1.793     albertel 9208:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9209: 	$cat_order) = @_;
1.521     raeburn  9210:     my $courses = '';
1.772     raeburn  9211:     my @homeservers;
1.521     raeburn  9212:     if ($caller eq 'global') {
1.841     albertel 9213: 	my %servers = &get_servers($codedom,'library');
                   9214: 	foreach my $tryserver (keys(%servers)) {
                   9215: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9216: 		push(@homeservers,$tryserver);
                   9217: 	    }
1.584     raeburn  9218:         }
1.1022    raeburn  9219:     } elsif ($caller eq 'requests') {
                   9220:         if ($codedom =~ /^$match_domain$/) {
                   9221:             my $chome = &domain($codedom,'primary');
                   9222:             unless ($chome eq 'no_host') {
                   9223:                 push(@homeservers,$chome);
                   9224:             }
                   9225:         }
1.521     raeburn  9226:     } else {
1.772     raeburn  9227:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9228:     }
1.793     albertel 9229:     foreach my $code (keys(%{$instcodes})) {
                   9230:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9231:     }
                   9232:     chop($courses);
1.772     raeburn  9233:     my $ok_response = 0;
                   9234:     my $response;
                   9235:     while (@homeservers > 0 && $ok_response == 0) {
                   9236:         my $server = shift(@homeservers); 
                   9237:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9238:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9239:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9240: 		split(/:/,$response);
1.772     raeburn  9241:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9242:             push(@{$codetitles},&str2array($codetitles_str));
                   9243:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9244:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9245:             $ok_response = 1;
                   9246:         }
                   9247:     }
                   9248:     if ($ok_response) {
1.521     raeburn  9249:         return 'ok';
1.772     raeburn  9250:     } else {
                   9251:         return $response;
1.521     raeburn  9252:     }
                   9253: }
                   9254: 
1.792     raeburn  9255: sub auto_instcode_defaults {
                   9256:     my ($domain,$returnhash,$code_order) = @_;
                   9257:     my @homeservers;
1.841     albertel 9258: 
                   9259:     my %servers = &get_servers($domain,'library');
                   9260:     foreach my $tryserver (keys(%servers)) {
                   9261: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9262: 	    push(@homeservers,$tryserver);
                   9263: 	}
1.792     raeburn  9264:     }
1.841     albertel 9265: 
1.792     raeburn  9266:     my $response;
1.841     albertel 9267:     foreach my $server (@homeservers) {
1.792     raeburn  9268:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9269:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9270: 	
                   9271: 	foreach my $pair (split(/\&/,$response)) {
                   9272: 	    my ($name,$value)=split(/\=/,$pair);
                   9273: 	    if ($name eq 'code_order') {
                   9274: 		@{$code_order} = split(/\&/,&unescape($value));
                   9275: 	    } else {
                   9276: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9277: 	    }
                   9278: 	}
                   9279: 	return 'ok';
1.792     raeburn  9280:     }
1.841     albertel 9281: 
                   9282:     return $response;
1.1003    raeburn  9283: }
                   9284: 
                   9285: sub auto_possible_instcodes {
1.1007    raeburn  9286:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9287:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9288:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9289:         return;
                   9290:     }
1.1003    raeburn  9291:     my (@homeservers,$uhome);
                   9292:     if (defined(&domain($domain,'primary'))) {
                   9293:         $uhome=&domain($domain,'primary');
                   9294:         push(@homeservers,&domain($domain,'primary'));
                   9295:     } else {
                   9296:         my %servers = &get_servers($domain,'library');
                   9297:         foreach my $tryserver (keys(%servers)) {
                   9298:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9299:                 push(@homeservers,$tryserver);
                   9300:             }
                   9301:         }
                   9302:     }
                   9303:     my $response;
                   9304:     foreach my $server (@homeservers) {
                   9305:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9306:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9307:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9308:             split(':',$response);
                   9309:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9310:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9311:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9312:             my ($name,$value)=split('=',$item);
                   9313:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9314:         }
                   9315:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9316:             my ($name,$value)=split('=',$item);
                   9317:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9318:         }
                   9319:         return 'ok';
                   9320:     }
                   9321:     return $response;
                   9322: }
1.792     raeburn  9323: 
1.1010    raeburn  9324: sub auto_courserequest_checks {
                   9325:     my ($dom) = @_;
1.1020    raeburn  9326:     my ($homeserver,%validations);
                   9327:     if ($dom =~ /^$match_domain$/) {
                   9328:         $homeserver = &domain($dom,'primary');
                   9329:     }
                   9330:     unless ($homeserver eq 'no_host') {
                   9331:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9332:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9333:             my @items = split(/&/,$response);
                   9334:             foreach my $item (@items) {
                   9335:                 my ($key,$value) = split('=',$item);
                   9336:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9337:             }
                   9338:         }
                   9339:     }
1.1010    raeburn  9340:     return %validations; 
                   9341: }
                   9342: 
1.1020    raeburn  9343: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9344:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9345:     my ($homeserver,$response);
                   9346:     if ($dom =~ /^$match_domain$/) {
                   9347:         $homeserver = &domain($dom,'primary');
                   9348:     }
1.1172.2.43  raeburn  9349:     unless ($homeserver eq 'no_host') {
                   9350:         my $customdata;
                   9351:         if (ref($custominfo) eq 'HASH') {
                   9352:             $customdata = &freeze_escape($custominfo);
                   9353:         }
1.1020    raeburn  9354:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9355:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9356:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9357:                                     $customdata,$homeserver));
1.1020    raeburn  9358:     }
                   9359:     return $response;
                   9360: }
                   9361: 
1.777     albertel 9362: sub auto_validate_class_sec {
1.918     raeburn  9363:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9364:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9365:     my $ownerlist;
                   9366:     if (ref($owners) eq 'ARRAY') {
                   9367:         $ownerlist = join(',',@{$owners});
                   9368:     } else {
                   9369:         $ownerlist = $owners;
                   9370:     }
1.773     raeburn  9371:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9372:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9373:     return $response;
                   9374: }
                   9375: 
1.1172.2.94  raeburn  9376: sub auto_validate_instclasses {
                   9377:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9378:     my ($homeserver,%validations);
                   9379:     $homeserver = &homeserver($cnum,$cdom);
                   9380:     unless ($homeserver eq 'no_host') {
                   9381:         my $ownerlist;
                   9382:         if (ref($owners) eq 'ARRAY') {
                   9383:             $ownerlist = join(',',@{$owners});
                   9384:         } else {
                   9385:             $ownerlist = $owners;
                   9386:         }
                   9387:         if (ref($classesref) eq 'HASH') {
                   9388:             my $classes = &freeze_escape($classesref);
                   9389:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9390:                                 ':'.$cdom.':'.$classes,$homeserver);
                   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:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9396:                 }
                   9397:             }
                   9398:         }
                   9399:     }
                   9400:     return %validations;
                   9401: }
                   9402: 
1.1172.2.38  raeburn  9403: sub auto_crsreq_update {
                   9404:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9405:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9406:     my ($homeserver,%crsreqresponse);
                   9407:     if ($cdom =~ /^$match_domain$/) {
                   9408:         $homeserver = &domain($cdom,'primary');
                   9409:     }
                   9410:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9411:         my $info;
                   9412:         if (ref($inbound) eq 'HASH') {
                   9413:             $info = &freeze_escape($inbound);
                   9414:         }
                   9415:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9416:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9417:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9418:                             &escape($title).':'.&escape($code).':'.
                   9419:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9420:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9421:             my @items = split(/&/,$response);
                   9422:             foreach my $item (@items) {
                   9423:                 my ($key,$value) = split('=',$item);
                   9424:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9425:             }
                   9426:         }
                   9427:     }
                   9428:     return \%crsreqresponse;
                   9429: }
                   9430: 
1.1172.2.78  raeburn  9431: sub auto_export_grades {
                   9432:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9433:     my ($homeserver,%exportresponse);
                   9434:     if ($cdom =~ /^$match_domain$/) {
                   9435:         $homeserver = &domain($cdom,'primary');
                   9436:     }
                   9437:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9438:         my $info;
                   9439:         if (ref($inforef) eq 'HASH') {
                   9440:             $info = &freeze_escape($inforef);
                   9441:         }
                   9442:         if (ref($gradesref) eq 'HASH') {
                   9443:             my $grades = &freeze_escape($gradesref);
                   9444:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9445:                                 $info.':'.$grades,$homeserver);
                   9446:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9447:                 my @items = split(/&/,$response);
                   9448:                 foreach my $item (@items) {
                   9449:                     my ($key,$value) = split('=',$item);
                   9450:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9451:                 }
                   9452:             }
                   9453:         }
                   9454:     }
                   9455:     return \%exportresponse;
                   9456: }
                   9457: 
1.1172.2.68  raeburn  9458: sub check_instcode_cloning {
                   9459:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9460:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9461:         return;
                   9462:     }
                   9463:     my $canclone;
                   9464:     if (@{$code_order} > 0) {
                   9465:         my $instcoderegexp ='^';
                   9466:         my @clonecodes = split(/\&/,$cloner);
                   9467:         foreach my $item (@{$code_order}) {
                   9468:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9469:                 foreach my $pair (@clonecodes) {
                   9470:                     my ($key,$val) = split(/\=/,$pair,2);
                   9471:                     $val = &unescape($val);
                   9472:                     if ($key eq $item) {
                   9473:                         $instcoderegexp .= '('.$val.')';
                   9474:                         last;
                   9475:                     }
                   9476:                 }
                   9477:             } else {
                   9478:                 $instcoderegexp .= $codedefaults->{$item};
                   9479:             }
                   9480:         }
                   9481:         $instcoderegexp .= '$';
                   9482:         my (@from,@to);
                   9483:         eval {
                   9484:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9485:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9486:         };
                   9487:         if ((@from > 0) && (@to > 0)) {
                   9488:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9489:             if (!@diffs) {
                   9490:                 $canclone = 1;
                   9491:             }
                   9492:         }
                   9493:     }
                   9494:     return $canclone;
                   9495: }
                   9496: 
                   9497: sub default_instcode_cloning {
                   9498:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9499:     my (%codedefaults,@code_order,$canclone);
                   9500:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9501:         %codedefaults = %{$codedefaultsref};
                   9502:         @code_order = @{$codeorderref};
                   9503:     } elsif ($clonedom) {
                   9504:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9505:     }
                   9506:     if (($domdefclone) && (@code_order)) {
                   9507:         my @clonecodes = split(/\+/,$domdefclone);
                   9508:         my $instcoderegexp ='^';
                   9509:         foreach my $item (@code_order) {
                   9510:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9511:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9512:             } else {
                   9513:                 $instcoderegexp .= $codedefaults{$item};
                   9514:             }
                   9515:         }
                   9516:         $instcoderegexp .= '$';
                   9517:         my (@from,@to);
                   9518:         eval {
                   9519:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9520:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9521:         };
                   9522:         if ((@from > 0) && (@to > 0)) {
                   9523:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9524:             if (!@diffs) {
                   9525:                 $canclone = 1;
                   9526:             }
                   9527:         }
                   9528:     }
                   9529:     return $canclone;
                   9530: }
                   9531: 
1.679     raeburn  9532: # ------------------------------------------------------- Course Group routines
                   9533: 
                   9534: sub get_coursegroups {
1.809     raeburn  9535:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9536:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9537: }
                   9538: 
1.679     raeburn  9539: sub modify_coursegroup {
                   9540:     my ($cdom,$cnum,$groupsettings) = @_;
                   9541:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9542: }
                   9543: 
1.809     raeburn  9544: sub toggle_coursegroup_status {
                   9545:     my ($cdom,$cnum,$group,$action) = @_;
                   9546:     my ($from_namespace,$to_namespace);
                   9547:     if ($action eq 'delete') {
                   9548:         $from_namespace = 'coursegroups';
                   9549:         $to_namespace = 'deleted_groups';
                   9550:     } else {
                   9551:         $from_namespace = 'deleted_groups';
                   9552:         $to_namespace = 'coursegroups';
                   9553:     }
                   9554:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9555:     if (my $tmp = &error(%curr_group)) {
                   9556:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9557:         return ('read error',$tmp);
                   9558:     } else {
                   9559:         my %savedsettings = %curr_group; 
1.809     raeburn  9560:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9561:         my $deloutcome;
                   9562:         if ($result eq 'ok') {
1.809     raeburn  9563:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9564:         } else {
                   9565:             return ('write error',$result);
                   9566:         }
                   9567:         if ($deloutcome eq 'ok') {
                   9568:             return 'ok';
                   9569:         } else {
                   9570:             return ('delete error',$deloutcome);
                   9571:         }
                   9572:     }
                   9573: }
                   9574: 
1.679     raeburn  9575: sub modify_group_roles {
1.957     raeburn  9576:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9577:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9578:     my $role = 'gr/'.&escape($userprivs);
                   9579:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9580:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9581:     if ($result eq 'ok') {
                   9582:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9583:     }
1.679     raeburn  9584:     return $result;
                   9585: }
                   9586: 
                   9587: sub modify_coursegroup_membership {
                   9588:     my ($cdom,$cnum,$membership) = @_;
                   9589:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9590:     return $result;
                   9591: }
                   9592: 
1.682     raeburn  9593: sub get_active_groups {
                   9594:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9595:     my $now = time;
                   9596:     my %groups = ();
                   9597:     foreach my $key (keys(%env)) {
1.811     albertel 9598:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9599:             my ($start,$end) = split(/\./,$env{$key});
                   9600:             if (($end!=0) && ($end<$now)) { next; }
                   9601:             if (($start!=0) && ($start>$now)) { next; }
                   9602:             if ($1 eq $cdom && $2 eq $cnum) {
                   9603:                 $groups{$3} = $env{$key} ;
                   9604:             }
                   9605:         }
                   9606:     }
                   9607:     return %groups;
                   9608: }
                   9609: 
1.683     raeburn  9610: sub get_group_membership {
                   9611:     my ($cdom,$cnum,$group) = @_;
                   9612:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9613: }
                   9614: 
                   9615: sub get_users_groups {
                   9616:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9617:     my @usersgroups;
1.683     raeburn  9618:     my $cachetime=1800;
                   9619: 
                   9620:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9621:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9622:     if (defined($cached)) {
1.734     albertel 9623:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9624:     } else {  
                   9625:         $grouplist = '';
1.816     raeburn  9626:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9627:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9628:         my $access_end = $env{'course.'.$courseid.
                   9629:                               '.default_enrollment_end_date'};
                   9630:         my $now = time;
                   9631:         foreach my $key (keys(%roleshash)) {
                   9632:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9633:                 my $group = $1;
                   9634:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9635:                     my $start = $2;
                   9636:                     my $end = $1;
                   9637:                     if ($start == -1) { next; } # deleted from group
                   9638:                     if (($start!=0) && ($start>$now)) { next; }
                   9639:                     if (($end!=0) && ($end<$now)) {
                   9640:                         if ($access_end && $access_end < $now) {
                   9641:                             if ($access_end - $end < 86400) {
                   9642:                                 push(@usersgroups,$group);
1.733     raeburn  9643:                             }
                   9644:                         }
1.817     raeburn  9645:                         next;
1.733     raeburn  9646:                     }
1.817     raeburn  9647:                     push(@usersgroups,$group);
1.683     raeburn  9648:                 }
                   9649:             }
                   9650:         }
1.817     raeburn  9651:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9652:         $grouplist = join(':',@usersgroups);
                   9653:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9654:     }
1.733     raeburn  9655:     return @usersgroups;
1.683     raeburn  9656: }
                   9657: 
                   9658: sub devalidate_getgroups_cache {
                   9659:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9660:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9661: 
1.683     raeburn  9662:     my $hashid="$udom:$uname:$courseid";
                   9663:     &devalidate_cache_new('getgroups',$hashid);
                   9664: }
                   9665: 
1.12      www      9666: # ------------------------------------------------------------------ Plain Text
                   9667: 
                   9668: sub plaintext {
1.988     raeburn  9669:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9670:     if ($short =~ m{^cr/}) {
1.758     albertel 9671: 	return (split('/',$short))[-1];
                   9672:     }
1.742     raeburn  9673:     if (!defined($cid)) {
                   9674:         $cid = $env{'request.course.id'};
                   9675:     }
                   9676:     my %rolenames = (
1.1008    raeburn  9677:                       Course    => 'std',
                   9678:                       Community => 'alt1',
1.742     raeburn  9679:                     );
1.1037    raeburn  9680:     if ($cid ne '') {
                   9681:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9682:             unless ($forcedefault) {
                   9683:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9684:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9685:                 return &Apache::lonlocal::mt($roletext);
                   9686:             }
                   9687:         }
                   9688:     }
                   9689:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9690:         (defined($rolenames{$type})) && 
                   9691:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9692:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9693:     } elsif ($cid ne '') {
                   9694:         my $crstype = $env{'course.'.$cid.'.type'};
                   9695:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9696:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9697:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9698:         }
1.742     raeburn  9699:     }
1.1037    raeburn  9700:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9701: }
                   9702: 
                   9703: # ----------------------------------------------------------------- Assign Role
                   9704: 
                   9705: sub assignrole {
1.957     raeburn  9706:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9707:         $context)=@_;
1.21      www      9708:     my $mrole;
                   9709:     if ($role =~ /^cr\//) {
1.393     www      9710:         my $cwosec=$url;
1.811     albertel 9711:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9712: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9713:            my $refused = 1;
                   9714:            if ($context eq 'requestcourses') {
                   9715:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9716:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9717:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9718:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9719:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9720:                            if ($crsenv{'internal.courseowner'} eq
                   9721:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9722:                                $refused = '';
                   9723:                            }
                   9724:                        }
                   9725:                    }
                   9726:                }
                   9727:            }
                   9728:            if ($refused) {
                   9729:                &logthis('Refused custom assignrole: '.
                   9730:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9731:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9732:                return 'refused';
                   9733:            }
1.104     www      9734:         }
1.21      www      9735:         $mrole='cr';
1.678     raeburn  9736:     } elsif ($role =~ /^gr\//) {
                   9737:         my $cwogrp=$url;
1.811     albertel 9738:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9739:         unless (&allowed('mdg',$cwogrp)) {
                   9740:             &logthis('Refused group assignrole: '.
                   9741:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9742:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9743:             return 'refused';
                   9744:         }
                   9745:         $mrole='gr';
1.21      www      9746:     } else {
1.82      www      9747:         my $cwosec=$url;
1.811     albertel 9748:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9749:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9750:             my $refused;
                   9751:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9752:                 if (!(&allowed('c'.$role,$url))) {
                   9753:                     $refused = 1;
                   9754:                 }
                   9755:             } else {
                   9756:                 $refused = 1;
                   9757:             }
1.947     raeburn  9758:             if ($refused) {
1.1045    raeburn  9759:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9760:                 if (!$selfenroll && $context eq 'course') {
                   9761:                     my %crsenv;
                   9762:                     if ($role eq 'cc' || $role eq 'co') {
                   9763:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9764:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9765:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9766:                                 if ($crsenv{'internal.courseowner'} eq 
                   9767:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9768:                                     $refused = '';
                   9769:                                 }
                   9770:                             }
                   9771:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9772:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9773:                                 if ($crsenv{'internal.courseowner'} eq 
                   9774:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9775:                                     $refused = '';
                   9776:                                 }
                   9777:                             }
                   9778:                         }
                   9779:                     }
                   9780:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9781:                     $refused = '';
1.1017    raeburn  9782:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9783:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9784:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9785:                         my $wrongcc;
                   9786:                         if ($cnum =~ /^$match_community$/) {
                   9787:                             $wrongcc = 1 if ($role eq 'cc');
                   9788:                         } else {
                   9789:                             $wrongcc = 1 if ($role eq 'co');
                   9790:                         }
                   9791:                         unless ($wrongcc) {
                   9792:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9793:                             if ($crsenv{'internal.courseowner'} eq 
                   9794:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9795:                                 $refused = '';
                   9796:                             }
1.1017    raeburn  9797:                         }
                   9798:                     }
1.1172.2.9  raeburn  9799:                 } elsif ($context eq 'requestauthor') {
                   9800:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9801:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9802:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9803:                             $refused = '';
                   9804:                         } else {
                   9805:                             my %domdefaults = &get_domain_defaults($udom);
                   9806:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9807:                                 my $checkbystatus;
                   9808:                                 if ($env{'user.adv'}) {
                   9809:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9810:                                     if ($disposition eq 'automatic') {
                   9811:                                         $refused = '';
                   9812:                                     } elsif ($disposition eq '') {
                   9813:                                         $checkbystatus = 1;
                   9814:                                     }
                   9815:                                 } else {
                   9816:                                     $checkbystatus = 1;
                   9817:                                 }
                   9818:                                 if ($checkbystatus) {
                   9819:                                     if ($env{'environment.inststatus'}) {
                   9820:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9821:                                         foreach my $type (@inststatuses) {
                   9822:                                             if (($type ne '') &&
                   9823:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9824:                                                 $refused = '';
                   9825:                                             }
                   9826:                                         }
                   9827:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9828:                                         $refused = '';
                   9829:                                     }
                   9830:                                 }
                   9831:                             }
                   9832:                         }
                   9833:                     }
1.1017    raeburn  9834:                 }
                   9835:                 if ($refused) {
1.947     raeburn  9836:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9837:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9838: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9839:                     return 'refused';
                   9840:                 }
1.932     raeburn  9841:             }
1.1131    raeburn  9842:         } elsif ($role eq 'au') {
                   9843:             if ($url ne '/'.$udom.'/') {
                   9844:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9845:                          ' to assign author role for '.$uname.':'.$udom.
                   9846:                          ' in domain: '.$url.' refused (wrong domain).');
                   9847:                 return 'refused';
                   9848:             }
1.104     www      9849:         }
1.21      www      9850:         $mrole=$role;
                   9851:     }
1.620     albertel 9852:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9853:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9854:     if ($end) { $command.='_'.$end; }
1.21      www      9855:     if ($start) {
                   9856: 	if ($end) { 
1.81      www      9857:            $command.='_'.$start; 
1.21      www      9858:         } else {
1.81      www      9859:            $command.='_0_'.$start;
1.21      www      9860:         }
                   9861:     }
1.739     raeburn  9862:     my $origstart = $start;
                   9863:     my $origend = $end;
1.957     raeburn  9864:     my $delflag;
1.357     www      9865: # actually delete
                   9866:     if ($deleteflag) {
1.373     www      9867: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9868: # modify command to delete the role
1.620     albertel 9869:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9870:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9871: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9872: # set start and finish to negative values for userrolelog
                   9873:            $start=-1;
                   9874:            $end=-1;
1.957     raeburn  9875:            $delflag = 1;
1.357     www      9876:         }
                   9877:     }
                   9878: # send command
1.349     www      9879:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9880: # log new user role if status is ok
1.349     www      9881:     if ($answer eq 'ok') {
1.663     raeburn  9882: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9883:         if (($role eq 'cc') || ($role eq 'in') ||
                   9884:             ($role eq 'ep') || ($role eq 'ad') ||
                   9885:             ($role eq 'ta') || ($role eq 'st') ||
                   9886:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9887:             ($role eq 'co')) {
1.1172.2.13  raeburn  9888: # for course roles, perform group memberships changes triggered by role change.
                   9889:             unless ($role =~ /^gr/) {
                   9890:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9891:                                                  $origstart,$selfenroll,$context);
                   9892:             }
1.1172.2.9  raeburn  9893:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9894:                            $selfenroll,$context);
                   9895:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9896:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9897:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9898:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9899:                            $context);
                   9900:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9901:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9902:                              $context);
                   9903:         }
1.1053    raeburn  9904:         if ($role eq 'cc') {
                   9905:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9906:         }
1.349     www      9907:     }
                   9908:     return $answer;
1.169     harris41 9909: }
                   9910: 
1.1053    raeburn  9911: sub autoupdate_coowners {
                   9912:     my ($url,$end,$start,$uname,$udom) = @_;
                   9913:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9914:     if (($cdom ne '') && ($cnum ne '')) {
                   9915:         my $now = time;
                   9916:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9917:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9918:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9919:             my $instcode = $coursehash{'internal.coursecode'};
                   9920:             if ($instcode ne '') {
1.1056    raeburn  9921:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9922:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9923:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9924:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9925:                         if ($result eq 'valid') {
                   9926:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9927:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9928:                                     push(@newcoowners,$coowner);
                   9929:                                 }
                   9930:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9931:                                     push(@newcoowners,$uname.':'.$udom);
                   9932:                                 }
                   9933:                                 @newcoowners = sort(@newcoowners);
                   9934:                             } else {
                   9935:                                 push(@newcoowners,$uname.':'.$udom);
                   9936:                             }
                   9937:                         } else {
                   9938:                             if ($coursehash{'internal.co-owners'}) {
                   9939:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9940:                                     unless ($coowner eq $uname.':'.$udom) {
                   9941:                                         push(@newcoowners,$coowner);
                   9942:                                     }
                   9943:                                 }
                   9944:                                 unless (@newcoowners > 0) {
                   9945:                                     $delcoowners = 1;
                   9946:                                     $coowners = '';
                   9947:                                 }
                   9948:                             }
                   9949:                         }
                   9950:                         if (@newcoowners || $delcoowners) {
                   9951:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9952:                                             $delcoowners,@newcoowners);
                   9953:                         }
                   9954:                     }
                   9955:                 }
                   9956:             }
                   9957:         }
                   9958:     }
                   9959: }
                   9960: 
                   9961: sub store_coowners {
                   9962:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9963:     my $cid = $cdom.'_'.$cnum;
                   9964:     my ($coowners,$delresult,$putresult);
                   9965:     if (@newcoowners) {
                   9966:         $coowners = join(',',@newcoowners);
                   9967:         my %coownershash = (
                   9968:                             'internal.co-owners' => $coowners,
                   9969:                            );
                   9970:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9971:         if ($putresult eq 'ok') {
                   9972:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9973:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9974:             }
                   9975:         }
                   9976:     }
                   9977:     if ($delcoowners) {
                   9978:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9979:         if ($delresult eq 'ok') {
                   9980:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9981:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9982:             }
                   9983:         }
                   9984:     }
                   9985:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9986:         my %crsinfo =
                   9987:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9988:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9989:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9990:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9991:         }
                   9992:     }
                   9993: }
                   9994: 
1.169     harris41 9995: # -------------------------------------------------- Modify user authentication
1.197     www      9996: # Overrides without validation
                   9997: 
1.169     harris41 9998: sub modifyuserauth {
                   9999:     my ($udom,$uname,$umode,$upass)=@_;
                   10000:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10001:     my $allowed;
                   10002:     if (&allowed('mau',$udom)) {
                   10003:         $allowed = 1;
                   10004:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10005:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10006:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10007:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10008:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10009:         if (($cdom ne '') && ($cnum ne '')) {
                   10010:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10011:             if ($is_owner) {
                   10012:                 $allowed = 1;
                   10013:             }
                   10014:         }
                   10015:     }
                   10016:     unless ($allowed) { return 'refused'; }
1.197     www      10017:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10018:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10019:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10020:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10021: 		     &escape($upass),$uhome);
1.1172.2.118.  .14(raeb 10022:-21):     my $ip = &get_requestor_ip();
1.620     albertel 10023:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10024:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.118.  .14(raeb 10025:-21):          '(Remote '.$ip.'): '.$reply);
1.197     www      10026:     &log($udom,,$uname,$uhome,
1.620     albertel 10027:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10028:                                      $env{'user.name'}.', '.$umode.
1.1172.2.118.  .14(raeb 10029:-21):          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10030:     unless ($reply eq 'ok') {
1.197     www      10031:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10032: 	return 'error: '.$reply;
                   10033:     }   
1.170     harris41 10034:     return 'ok';
1.80      www      10035: }
                   10036: 
1.81      www      10037: # --------------------------------------------------------------- Modify a user
1.80      www      10038: 
1.81      www      10039: sub modifyuser {
1.206     matthew  10040:     my ($udom,    $uname, $uid,
                   10041:         $umode,   $upass, $first,
                   10042:         $middle,  $last,  $gene,
1.1058    raeburn  10043:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10044:     $udom= &LONCAPA::clean_domain($udom);
                   10045:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10046:     my $showcandelete = 'none';
                   10047:     if (ref($candelete) eq 'ARRAY') {
                   10048:         if (@{$candelete} > 0) {
                   10049:             $showcandelete = join(', ',@{$candelete});
                   10050:         }
                   10051:     }
1.81      www      10052:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10053:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10054: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10055:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10056:                                      ' desiredhome not specified'). 
1.620     albertel 10057:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10058:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10059:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10060:     my $newuser;
                   10061:     if ($uhome eq 'no_host') {
                   10062:         $newuser = 1;
                   10063:     }
1.80      www      10064: # ----------------------------------------------------------------- Create User
1.406     albertel 10065:     if (($uhome eq 'no_host') && 
                   10066: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10067:         my $unhome='';
1.844     albertel 10068:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10069:             $unhome = $desiredhome;
1.620     albertel 10070: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10071: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10072:         } else { # load balancing routine for determining $unhome
1.81      www      10073:             my $loadm=10000000;
1.841     albertel 10074: 	    my %servers = &get_servers($udom,'library');
                   10075: 	    foreach my $tryserver (keys(%servers)) {
                   10076: 		my $answer=reply('load',$tryserver);
                   10077: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10078: 		    $loadm=$answer;
                   10079: 		    $unhome=$tryserver;
                   10080: 		}
1.80      www      10081: 	    }
                   10082:         }
                   10083:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10084: 	    return 'error: unable to find a home server for '.$uname.
                   10085:                    ' in domain '.$udom;
1.80      www      10086:         }
                   10087:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10088:                          &escape($upass),$unhome);
                   10089: 	unless ($reply eq 'ok') {
                   10090:             return 'error: '.$reply;
                   10091:         }   
1.230     stredwic 10092:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10093:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10094: 	    return 'error: unable verify users home machine.';
1.80      www      10095:         }
1.209     matthew  10096:     }   # End of creation of new user
1.80      www      10097: # ---------------------------------------------------------------------- Add ID
                   10098:     if ($uid) {
                   10099:        $uid=~tr/A-Z/a-z/;
                   10100:        my %uidhash=&idrget($udom,$uname);
1.196     www      10101:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10102:          && (!$forceid)) {
1.80      www      10103: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10104: 	      return 'error: user id "'.$uid.'" does not match '.
                   10105:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10106:           }
                   10107:        } else {
                   10108: 	  &idput($udom,($uname => $uid));
                   10109:        }
                   10110:     }
                   10111: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10112:     my @tmp=&get('environment',
1.899     raeburn  10113: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10114:                     'permanentemail','inststatus'],
1.134     albertel 10115: 		   $udom,$uname);
1.1075    raeburn  10116:     my (%names,%oldnames);
1.313     matthew  10117:     if ($tmp[0] =~ m/^error:.*/) { 
                   10118:         %names=(); 
                   10119:     } else {
                   10120:         %names = @tmp;
1.1075    raeburn  10121:         %oldnames = %names;
1.313     matthew  10122:     }
1.388     www      10123: #
1.1058    raeburn  10124: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10125: # of users did not contain them), do not overwrite existing values
                   10126: # unless field is in $candelete array ref.  
                   10127: #
                   10128: 
                   10129:     my @fields = ('firstname','middlename','lastname','generation',
                   10130:                   'permanentemail','id');
                   10131:     my %newvalues;
                   10132:     if (ref($candelete) eq 'ARRAY') {
                   10133:         foreach my $field (@fields) {
                   10134:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10135:                 if ($field eq 'firstname') {
                   10136:                     $names{$field} = $first;
                   10137:                 } elsif ($field eq 'middlename') {
                   10138:                     $names{$field} = $middle;
                   10139:                 } elsif ($field eq 'lastname') {
                   10140:                     $names{$field} = $last;
                   10141:                 } elsif ($field eq 'generation') { 
                   10142:                     $names{$field} = $gene;
                   10143:                 } elsif ($field eq 'permanentemail') {
                   10144:                     $names{$field} = $email;
                   10145:                 } elsif ($field eq 'id') {
                   10146:                     $names{$field}  = $uid;
                   10147:                 }
                   10148:             }
                   10149:         }
                   10150:     }
1.388     www      10151:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10152:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10153:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10154:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10155:     if ($email) {
                   10156:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10157:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10158:     }
1.899     raeburn  10159:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10160:     if (defined($inststatus)) {
                   10161:         $names{'inststatus'} = '';
                   10162:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10163:         if (ref($usertypes) eq 'HASH') {
                   10164:             my @okstatuses; 
                   10165:             foreach my $item (split(/:/,$inststatus)) {
                   10166:                 if (defined($usertypes->{$item})) {
                   10167:                     push(@okstatuses,$item);  
                   10168:                 }
                   10169:             }
                   10170:             if (@okstatuses) {
                   10171:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10172:             }
                   10173:         }
                   10174:     }
1.1075    raeburn  10175:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10176:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10177:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10178:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10179:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10180:     } else {
                   10181:         $logmsg .= ' during self creation';
                   10182:     }
1.1075    raeburn  10183:     my $changed;
                   10184:     if ($newuser) {
                   10185:         $changed = 1;
                   10186:     } else {
                   10187:         foreach my $field (@fields) {
                   10188:             if ($names{$field} ne $oldnames{$field}) {
                   10189:                 $changed = 1;
                   10190:                 last;
                   10191:             }
                   10192:         }
                   10193:     }
                   10194:     unless ($changed) {
                   10195:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10196:         &logthis($logmsg);
                   10197:         return 'ok';
                   10198:     }
                   10199:     my $reply = &put('environment', \%names, $udom,$uname);
                   10200:     if ($reply ne 'ok') { 
                   10201:         return 'error: '.$reply;
                   10202:     }
1.1087    raeburn  10203:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10204:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10205:     }
1.1075    raeburn  10206:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10207:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10208:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10209:     &logthis($logmsg);
1.134     albertel 10210:     return 'ok';
1.80      www      10211: }
                   10212: 
1.81      www      10213: # -------------------------------------------------------------- Modify student
1.80      www      10214: 
1.81      www      10215: sub modifystudent {
                   10216:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10217:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10218:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10219:     if (!$cid) {
1.620     albertel 10220: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10221: 	    return 'not_in_class';
                   10222: 	}
1.80      www      10223:     }
                   10224: # --------------------------------------------------------------- Make the user
1.81      www      10225:     my $reply=&modifyuser
1.209     matthew  10226: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10227:          $desiredhome,$email,$inststatus);
1.80      www      10228:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10229:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10230:     # student's environment
1.297     matthew  10231:     $uid = undef if (!$forceid);
1.455     albertel 10232:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10233: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10234:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10235:     return $reply;
                   10236: }
                   10237: 
                   10238: sub modify_student_enrollment {
1.1172.2.23  raeburn  10239:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10240:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10241:     my ($cdom,$cnum,$chome);
                   10242:     if (!$cid) {
1.620     albertel 10243: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10244: 	    return 'not_in_class';
                   10245: 	}
1.620     albertel 10246: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10247: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10248:     } else {
                   10249: 	($cdom,$cnum)=split(/_/,$cid);
                   10250:     }
1.620     albertel 10251:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10252:     if (!$chome) {
1.457     raeburn  10253: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10254:     }
1.455     albertel 10255:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10256:     # Make sure the user exists
1.81      www      10257:     my $uhome=&homeserver($uname,$udom);
                   10258:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10259: 	return 'error: no such user';
                   10260:     }
1.297     matthew  10261:     # Get student data if we were not given enough information
                   10262:     if (!defined($first)  || $first  eq '' || 
                   10263:         !defined($last)   || $last   eq '' || 
                   10264:         !defined($uid)    || $uid    eq '' || 
                   10265:         !defined($middle) || $middle eq '' || 
                   10266:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10267:         # They did not supply us with enough data to enroll the student, so
                   10268:         # we need to pick up more information.
1.297     matthew  10269:         my %tmp = &get('environment',
1.294     matthew  10270:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10271:                        ,$udom,$uname);
                   10272: 
1.800     albertel 10273:         #foreach my $key (keys(%tmp)) {
                   10274:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10275:         #}
1.294     matthew  10276:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10277:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10278:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10279:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10280:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10281:     }
1.556     albertel 10282:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10283:     my $user = "$uname:$udom";
                   10284:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10285:     my $reply=cput('classlist',
1.1148    raeburn  10286: 		   {$user => 
1.1172.2.76  raeburn  10287: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10288: 		   $cdom,$cnum);
1.1148    raeburn  10289:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10290:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10291:     } else { 
1.81      www      10292: 	return 'error: '.$reply;
                   10293:     }
1.297     matthew  10294:     # Add student role to user
1.83      www      10295:     my $uurl='/'.$cid;
1.81      www      10296:     $uurl=~s/\_/\//g;
                   10297:     if ($usec) {
                   10298: 	$uurl.='/'.$usec;
                   10299:     }
1.1148    raeburn  10300:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10301:                              $selfenroll,$context);
                   10302:     if ($result ne 'ok') {
                   10303:         if ($old_entry{$user} ne '') {
                   10304:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10305:         } else {
                   10306:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10307:         }
                   10308:     }
                   10309:     return $result; 
1.21      www      10310: }
                   10311: 
1.556     albertel 10312: sub format_name {
                   10313:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10314:     my $name;
                   10315:     if ($first ne 'lastname') {
                   10316: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10317:     } else {
                   10318: 	if ($lastname=~/\S/) {
                   10319: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10320: 	    $name=~s/\s+,/,/;
                   10321: 	} else {
                   10322: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10323: 	}
                   10324:     }
                   10325:     $name=~s/^\s+//;
                   10326:     $name=~s/\s+$//;
                   10327:     $name=~s/\s+/ /g;
                   10328:     return $name;
                   10329: }
                   10330: 
1.84      www      10331: # ------------------------------------------------- Write to course preferences
                   10332: 
                   10333: sub writecoursepref {
                   10334:     my ($courseid,%prefs)=@_;
                   10335:     $courseid=~s/^\///;
                   10336:     $courseid=~s/\_/\//g;
                   10337:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10338:     my $chome=homeserver($cnum,$cdomain);
                   10339:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10340: 	return 'error: no such course';
                   10341:     }
                   10342:     my $cstring='';
1.800     albertel 10343:     foreach my $pref (keys(%prefs)) {
                   10344: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10345:     }
1.84      www      10346:     $cstring=~s/\&$//;
                   10347:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10348: }
                   10349: 
                   10350: # ---------------------------------------------------------- Make/modify course
                   10351: 
                   10352: sub createcourse {
1.741     raeburn  10353:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10354:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10355:     $url=&declutter($url);
                   10356:     my $cid='';
1.1028    raeburn  10357:     if ($context eq 'requestcourses') {
                   10358:         my $can_create = 0;
                   10359:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10360:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10361:20):             my $reload;
                   10362:20):             if (($callercontext eq 'auto') &&
                   10363:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10364:20):                 $reload = 'reload';
                   10365:20):             }
                   10366:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10367:                                   $context)) {
                   10368:                 $can_create = 1;
                   10369:             }
                   10370:         } else {
                   10371:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10372:                                            $category);
                   10373:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10374:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10375:                 if (@curr > 0) {
                   10376:                     my @options = qw(approval validate autolimit);
                   10377:                     my $optregex = join('|',@options);
                   10378:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10379:                         $can_create = 1;
                   10380:                     }
                   10381:                 }
                   10382:             }
                   10383:         }
                   10384:         if ($can_create) {
                   10385:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10386:                 unless (&allowed('ccc',$udom)) {
                   10387:                     return 'refused'; 
                   10388:                 }
1.1017    raeburn  10389:             }
                   10390:         } else {
                   10391:             return 'refused';
                   10392:         }
1.1028    raeburn  10393:     } elsif (!&allowed('ccc',$udom)) {
                   10394:         return 'refused';
1.84      www      10395:     }
1.1011    raeburn  10396: # --------------------------------------------------------------- Get Unique ID
                   10397:     my $uname;
                   10398:     if ($cnum =~ /^$match_courseid$/) {
                   10399:         my $chome=&homeserver($cnum,$udom,'true');
                   10400:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10401:             $uname = $cnum;
                   10402:         } else {
1.1038    raeburn  10403:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10404:         }
                   10405:     } else {
1.1038    raeburn  10406:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10407:     }
                   10408:     return $uname if ($uname =~ /^error/);
                   10409: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10410:     if (!defined($course_server)) {
                   10411:         if (defined(&domain($udom,'primary'))) {
                   10412:             $course_server = &domain($udom,'primary');
                   10413:         } else {
                   10414:             $course_server = $env{'user.home'}; 
                   10415:         }
                   10416:     }
                   10417:     my %host_servers =
                   10418:         &Apache::lonnet::get_servers($udom,'library');
                   10419:     unless ($host_servers{$course_server}) {
                   10420:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10421:     }
1.84      www      10422: # ------------------------------------------------------------- Make the course
                   10423:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10424:                       $course_server);
1.84      www      10425:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10426:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10427:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10428: 	return 'error: no such course';
                   10429:     }
1.271     www      10430: # ----------------------------------------------------------------- Course made
1.516     raeburn  10431: # log existence
1.1029    raeburn  10432:     my $now = time;
1.918     raeburn  10433:     my $newcourse = {
                   10434:                     $udom.'_'.$uname => {
1.921     raeburn  10435:                                      description => $description,
                   10436:                                      inst_code   => $inst_code,
                   10437:                                      owner       => $course_owner,
                   10438:                                      type        => $crstype,
1.1029    raeburn  10439:                                      creator     => $env{'user.name'}.':'.
                   10440:                                                     $env{'user.domain'},
                   10441:                                      created     => $now,
                   10442:                                      context     => $context,
1.918     raeburn  10443:                                                 },
                   10444:                     };
1.921     raeburn  10445:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10446: # set toplevel url
1.271     www      10447:     my $topurl=$url;
                   10448:     unless ($nonstandard) {
                   10449: # ------------------------------------------ For standard courses, make top url
                   10450:         my $mapurl=&clutter($url);
1.278     www      10451:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10452:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10453: <map>
                   10454: <resource id="1" type="start"></resource>
                   10455: <resource id="2" src="$mapurl"></resource>
                   10456: <resource id="3" type="finish"></resource>
                   10457: <link index="1" from="1" to="2"></link>
                   10458: <link index="2" from="2" to="3"></link>
                   10459: </map>
                   10460: ENDINITMAP
                   10461:         $topurl=&declutter(
1.638     albertel 10462:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10463:                           );
                   10464:     }
                   10465: # ----------------------------------------------------------- Write preferences
1.84      www      10466:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10467:                      ('description'              => $description,
                   10468:                       'url'                      => $topurl,
                   10469:                       'internal.creator'         => $env{'user.name'}.':'.
                   10470:                                                     $env{'user.domain'},
                   10471:                       'internal.created'         => $now,
                   10472:                       'internal.creationcontext' => $context)
                   10473:                     );
1.84      www      10474:     return '/'.$udom.'/'.$uname;
                   10475: }
                   10476: 
1.1011    raeburn  10477: # ------------------------------------------------------------------- Create ID
                   10478: sub generate_coursenum {
1.1038    raeburn  10479:     my ($udom,$crstype) = @_;
1.1011    raeburn  10480:     my $domdesc = &domain($udom);
                   10481:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10482:     my $first;
                   10483:     if ($crstype eq 'Community') {
                   10484:         $first = '0';
                   10485:     } else {
                   10486:         $first = int(1+rand(9)); 
                   10487:     } 
                   10488:     my $uname=$first.
1.1011    raeburn  10489:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10490:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10491:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10492: # ----------------------------------------------- Make sure that does not exist
                   10493:     my $uhome=&homeserver($uname,$udom,'true');
                   10494:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10495:         if ($crstype eq 'Community') {
                   10496:             $first = '0';
                   10497:         } else {
                   10498:             $first = int(1+rand(9));
                   10499:         }
                   10500:         $uname=$first.
1.1011    raeburn  10501:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10502:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10503:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10504:         $uhome=&homeserver($uname,$udom,'true');
                   10505:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10506:             return 'error: unable to generate unique course-ID';
                   10507:         }
                   10508:     }
                   10509:     return $uname;
                   10510: }
                   10511: 
1.813     albertel 10512: sub is_course {
1.1167    droeschl 10513:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10514:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10515:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10516:     my $uhome=&homeserver($cnum,$cdom);
                   10517:     my $iscourse;
                   10518:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10519:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10520:     } else {
                   10521:         my $hashid = $cdom.':'.$cnum;
                   10522:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10523:         unless (defined($cached)) {
                   10524:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10525:                                         $cnum,undef,undef,'.');
                   10526:             $iscourse = 0;
                   10527:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10528:                 $iscourse = 1;
                   10529:             }
                   10530:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10531:         }
                   10532:     }
                   10533:     return unless($iscourse);
1.1167    droeschl 10534:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10535: }
                   10536: 
1.1015    raeburn  10537: sub store_userdata {
                   10538:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10539:     my $result;
1.1016    raeburn  10540:     if ($datakey ne '') {
1.1013    raeburn  10541:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10542:             if ($udom eq '' || $uname eq '') {
                   10543:                 $udom = $env{'user.domain'};
                   10544:                 $uname = $env{'user.name'};
                   10545:             }
                   10546:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10547:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10548:                 $result = 'error: no_host';
                   10549:             } else {
1.1172.2.118.  .14(raeb 10550:-21):                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10551:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10552: 
                   10553:                 my $namevalue='';
                   10554:                 foreach my $key (keys(%{$storehash})) {
                   10555:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10556:                 }
                   10557:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10558:                 unless ($namespace eq 'courserequests') {
                   10559:                     $datakey = &escape($datakey);
                   10560:                 }
1.1105    raeburn  10561:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10562:                                   $namevalue,$uhome);
1.1013    raeburn  10563:             }
                   10564:         } else {
                   10565:             $result = 'error: data to store was not a hash reference'; 
                   10566:         }
                   10567:     } else {
                   10568:         $result= 'error: invalid requestkey'; 
                   10569:     }
                   10570:     return $result;
                   10571: }
                   10572: 
1.21      www      10573: # ---------------------------------------------------------- Assign Custom Role
                   10574: 
                   10575: sub assigncustomrole {
1.957     raeburn  10576:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10577:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10578:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10579: }
                   10580: 
                   10581: # ----------------------------------------------------------------- Revoke Role
                   10582: 
                   10583: sub revokerole {
1.957     raeburn  10584:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10585:     my $now=time;
1.965     raeburn  10586:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10587: }
                   10588: 
                   10589: # ---------------------------------------------------------- Revoke Custom Role
                   10590: 
                   10591: sub revokecustomrole {
1.957     raeburn  10592:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10593:     my $now=time;
1.357     www      10594:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10595:            $deleteflag,$selfenroll,$context);
1.17      www      10596: }
                   10597: 
1.533     banghart 10598: # ------------------------------------------------------------ Disk usage
1.535     albertel 10599: sub diskusage {
1.955     raeburn  10600:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10601:     $directorypath =~ s/\/$//;
                   10602:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10603:                        .&escape($getpropath).':'.&escape($uname).':'
                   10604:                        .&escape($udom),homeserver($uname,$udom));
                   10605:     if ($listing eq 'unknown_cmd') {
                   10606:         if ($getpropath) {
                   10607:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10608:         }
                   10609:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10610:     }
1.514     albertel 10611:     return $listing;
1.512     banghart 10612: }
                   10613: 
1.566     banghart 10614: sub is_locked {
1.1096    raeburn  10615:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10616:     my @check;
                   10617:     my $is_locked;
1.1093    raeburn  10618:     push (@check,$file_name);
1.613     albertel 10619:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10620: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10621:     my ($tmp)=keys(%locked);
                   10622:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10623:     
1.566     banghart 10624:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10625:         $is_locked = 'false';
                   10626:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10627:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10628:                $is_locked = 'true';
1.1096    raeburn  10629:                if (ref($which) eq 'ARRAY') {
                   10630:                    push(@{$which},$entry);
                   10631:                } else {
                   10632:                    last;
                   10633:                }
1.745     raeburn  10634:            }
                   10635:        }
1.566     banghart 10636:     } else {
                   10637:         $is_locked = 'false';
                   10638:     }
1.1093    raeburn  10639:     return $is_locked;
1.566     banghart 10640: }
                   10641: 
1.759     albertel 10642: sub declutter_portfile {
                   10643:     my ($file) = @_;
1.833     albertel 10644:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10645:     return $file;
                   10646: }
                   10647: 
1.559     banghart 10648: # ------------------------------------------------------------- Mark as Read Only
                   10649: 
                   10650: sub mark_as_readonly {
                   10651:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10652:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10653:     my ($tmp)=keys(%current_permissions);
                   10654:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10655:     foreach my $file (@{$files}) {
1.759     albertel 10656: 	$file = &declutter_portfile($file);
1.561     banghart 10657:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10658:     }
1.613     albertel 10659:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10660:     return;
                   10661: }
                   10662: 
1.572     banghart 10663: # ------------------------------------------------------------Save Selected Files
                   10664: 
                   10665: sub save_selected_files {
                   10666:     my ($user, $path, @files) = @_;
                   10667:     my $filename = $user."savedfiles";
1.573     banghart 10668:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10669:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10670:     foreach my $file (@files) {
1.620     albertel 10671:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10672:     }
                   10673:     foreach my $file (@other_files) {
1.574     banghart 10674:         print (OUT $file."\n");
1.572     banghart 10675:     }
1.574     banghart 10676:     close (OUT);
1.572     banghart 10677:     return 'ok';
                   10678: }
                   10679: 
1.574     banghart 10680: sub clear_selected_files {
                   10681:     my ($user) = @_;
                   10682:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10683:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10684:     print (OUT undef);
                   10685:     close (OUT);
                   10686:     return ("ok");    
                   10687: }
                   10688: 
1.572     banghart 10689: sub files_in_path {
                   10690:     my ($user, $path) = @_;
                   10691:     my $filename = $user."savedfiles";
                   10692:     my %return_files;
1.1172.2.96  raeburn  10693:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10694:     while (my $line_in = <IN>) {
1.574     banghart 10695:         chomp ($line_in);
                   10696:         my @paths_and_file = split (m!/!, $line_in);
                   10697:         my $file_part = pop (@paths_and_file);
                   10698:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10699:         $path_part.='/';
                   10700:         my $path_and_file = $path_part.$file_part;
                   10701:         if ($path_part eq $path) {
                   10702:             $return_files{$file_part}= 'selected';
                   10703:         }
                   10704:     }
1.574     banghart 10705:     close (IN);
                   10706:     return (\%return_files);
1.572     banghart 10707: }
                   10708: 
                   10709: # called in portfolio select mode, to show files selected NOT in current directory
                   10710: sub files_not_in_path {
                   10711:     my ($user, $path) = @_;
                   10712:     my $filename = $user."savedfiles";
                   10713:     my @return_files;
                   10714:     my $path_part;
1.1172.2.96  raeburn  10715:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10716:     while (my $line = <IN>) {
1.572     banghart 10717:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10718:         my @paths_and_file = split(m|/|, $line);
                   10719:         my $file_part = pop(@paths_and_file);
                   10720:         chomp($file_part);
                   10721:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10722:         $path_part .= '/';
                   10723:         my $path_and_file = $path_part.$file_part;
                   10724:         if ($path_part ne $path) {
1.800     albertel 10725:             push(@return_files, ($path_and_file));
1.572     banghart 10726:         }
                   10727:     }
1.800     albertel 10728:     close(OUT);
1.574     banghart 10729:     return (@return_files);
1.572     banghart 10730: }
                   10731: 
1.745     raeburn  10732: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10733: 
1.745     raeburn  10734: sub get_portfile_permissions {
                   10735:     my ($domain,$user) = @_;
1.613     albertel 10736:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10737:     my ($tmp)=keys(%current_permissions);
                   10738:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10739:     return \%current_permissions;
                   10740: }
                   10741: 
                   10742: #---------------------------------------------Get portfolio file access controls
                   10743: 
1.749     raeburn  10744: sub get_access_controls {
1.745     raeburn  10745:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10746:     my %access;
                   10747:     my $real_file = $file;
                   10748:     $file =~ s/\.meta$//;
1.745     raeburn  10749:     if (defined($file)) {
1.749     raeburn  10750:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10751:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10752:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10753:             }
                   10754:         }
1.745     raeburn  10755:     } else {
1.749     raeburn  10756:         foreach my $key (keys(%{$current_permissions})) {
                   10757:             if ($key =~ /\0accesscontrol$/) {
                   10758:                 if (defined($group)) {
                   10759:                     if ($key !~ m-^\Q$group\E/-) {
                   10760:                         next;
                   10761:                     }
                   10762:                 }
                   10763:                 my ($fullpath) = split(/\0/,$key);
                   10764:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10765:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10766:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10767:                     }
                   10768:                 }
                   10769:             }
                   10770:         }
                   10771:     }
                   10772:     return %access;
                   10773: }
                   10774: 
                   10775: sub modify_access_controls {
                   10776:     my ($file_name,$changes,$domain,$user)=@_;
                   10777:     my ($outcome,$deloutcome);
                   10778:     my %store_permissions;
                   10779:     my %new_values;
                   10780:     my %new_control;
                   10781:     my %translation;
                   10782:     my @deletions = ();
                   10783:     my $now = time;
                   10784:     if (exists($$changes{'activate'})) {
                   10785:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10786:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10787:             my $numnew = scalar(@newitems);
                   10788:             for (my $i=0; $i<$numnew; $i++) {
                   10789:                 my $newkey = $newitems[$i];
                   10790:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10791:                 if ($newkey =~ /^\d+:/) { 
                   10792:                     $newkey =~ s/^(\d+)/$newid/;
                   10793:                     $translation{$1} = $newid;
                   10794:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10795:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10796:                     $translation{$1} = $newid;
                   10797:                 }
1.749     raeburn  10798:                 $new_values{$file_name."\0".$newkey} = 
                   10799:                                           $$changes{'activate'}{$newitems[$i]};
                   10800:                 $new_control{$newkey} = $now;
                   10801:             }
                   10802:         }
                   10803:     }
                   10804:     my %todelete;
                   10805:     my %changed_items;
                   10806:     foreach my $action ('delete','update') {
                   10807:         if (exists($$changes{$action})) {
                   10808:             if (ref($$changes{$action}) eq 'HASH') {
                   10809:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10810:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10811:                     if ($action eq 'delete') { 
                   10812:                         $todelete{$itemnum} = 1;
                   10813:                     } else {
                   10814:                         $changed_items{$itemnum} = $key;
                   10815:                     }
                   10816:                 }
1.745     raeburn  10817:             }
                   10818:         }
1.749     raeburn  10819:     }
                   10820:     # get lock on access controls for file.
                   10821:     my $lockhash = {
                   10822:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10823:                                                        ':'.$env{'user.domain'},
                   10824:                    }; 
                   10825:     my $tries = 0;
                   10826:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10827:    
1.1172.2.79  raeburn  10828:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10829:         $tries ++;
1.1172.2.79  raeburn  10830:         sleep(0.1);
1.749     raeburn  10831:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10832:     }
                   10833:     if ($gotlock eq 'ok') {
                   10834:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10835:         my ($tmp)=keys(%curr_permissions);
                   10836:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10837:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10838:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10839:             if (ref($curr_controls) eq 'HASH') {
                   10840:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10841:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10842:                     if (defined($todelete{$itemnum})) {
                   10843:                         push(@deletions,$file_name."\0".$control_item);
                   10844:                     } else {
                   10845:                         if (defined($changed_items{$itemnum})) {
                   10846:                             $new_control{$changed_items{$itemnum}} = $now;
                   10847:                             push(@deletions,$file_name."\0".$control_item);
                   10848:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10849:                         } else {
                   10850:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10851:                         }
                   10852:                     }
1.745     raeburn  10853:                 }
                   10854:             }
                   10855:         }
1.970     raeburn  10856:         my ($group);
                   10857:         if (&is_course($domain,$user)) {
                   10858:             ($group,my $file) = split(/\//,$file_name,2);
                   10859:         }
1.749     raeburn  10860:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10861:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10862:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10863:         #  remove lock
                   10864:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10865:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10866:         my $sqlresult =
1.970     raeburn  10867:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10868:                                     $group);
1.749     raeburn  10869:     } else {
                   10870:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10871:     }
1.749     raeburn  10872:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10873: }
                   10874: 
1.827     raeburn  10875: sub make_public_indefinitely {
                   10876:     my ($requrl) = @_;
                   10877:     my $now = time;
                   10878:     my $action = 'activate';
                   10879:     my $aclnum = 0;
                   10880:     if (&is_portfolio_url($requrl)) {
                   10881:         my (undef,$udom,$unum,$file_name,$group) =
                   10882:             &parse_portfolio_url($requrl);
                   10883:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10884:         my %access_controls = &get_access_controls($current_perms,
                   10885:                                                    $group,$file_name);
                   10886:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10887:             my ($num,$scope,$end,$start) = 
                   10888:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10889:             if ($scope eq 'public') {
                   10890:                 if ($start <= $now && $end == 0) {
                   10891:                     $action = 'none';
                   10892:                 } else {
                   10893:                     $action = 'update';
                   10894:                     $aclnum = $num;
                   10895:                 }
                   10896:                 last;
                   10897:             }
                   10898:         }
                   10899:         if ($action eq 'none') {
                   10900:              return 'ok';
                   10901:         } else {
                   10902:             my %changes;
                   10903:             my $newend = 0;
                   10904:             my $newstart = $now;
                   10905:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10906:             $changes{$action}{$newkey} = {
                   10907:                 type => 'public',
                   10908:                 time => {
                   10909:                     start => $newstart,
                   10910:                     end   => $newend,
                   10911:                 },
                   10912:             };
                   10913:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10914:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10915:             return $outcome;
                   10916:         }
                   10917:     } else {
                   10918:         return 'invalid';
                   10919:     }
                   10920: }
                   10921: 
1.745     raeburn  10922: #------------------------------------------------------Get Marked as Read Only
                   10923: 
                   10924: sub get_marked_as_readonly {
                   10925:     my ($domain,$user,$what,$group) = @_;
                   10926:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10927:     my @readonly_files;
1.629     banghart 10928:     my $cmp1=$what;
                   10929:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10930:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10931:         if (defined($group)) {
                   10932:             if ($file_name !~ m-^\Q$group\E/-) {
                   10933:                 next;
                   10934:             }
                   10935:         }
1.561     banghart 10936:         if (ref($value) eq "ARRAY"){
                   10937:             foreach my $stored_what (@{$value}) {
1.629     banghart 10938:                 my $cmp2=$stored_what;
1.759     albertel 10939:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10940:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10941:                 }
1.629     banghart 10942:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10943:                     push(@readonly_files, $file_name);
1.745     raeburn  10944:                     last;
1.563     banghart 10945:                 } elsif (!defined($what)) {
                   10946:                     push(@readonly_files, $file_name);
1.745     raeburn  10947:                     last;
1.561     banghart 10948:                 }
                   10949:             }
1.745     raeburn  10950:         }
1.561     banghart 10951:     }
                   10952:     return @readonly_files;
                   10953: }
1.577     banghart 10954: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10955: 
1.577     banghart 10956: sub get_marked_as_readonly_hash {
1.745     raeburn  10957:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10958:     my %readonly_files;
1.745     raeburn  10959:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10960:         if (defined($group)) {
                   10961:             if ($file_name !~ m-^\Q$group\E/-) {
                   10962:                 next;
                   10963:             }
                   10964:         }
1.577     banghart 10965:         if (ref($value) eq "ARRAY"){
                   10966:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10967:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10968:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10969:                         if ($lock_descriptor eq 'graded') {
                   10970:                             $readonly_files{$file_name} = 'graded';
                   10971:                         } elsif ($lock_descriptor eq 'handback') {
                   10972:                             $readonly_files{$file_name} = 'handback';
                   10973:                         } else {
                   10974:                             if (!exists($readonly_files{$file_name})) {
                   10975:                                 $readonly_files{$file_name} = 'locked';
                   10976:                             }
                   10977:                         }
1.745     raeburn  10978:                     }
1.750     banghart 10979:                 } 
1.577     banghart 10980:             }
                   10981:         } 
                   10982:     }
                   10983:     return %readonly_files;
                   10984: }
1.559     banghart 10985: # ------------------------------------------------------------ Unmark as Read Only
                   10986: 
                   10987: sub unmark_as_readonly {
1.629     banghart 10988:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10989:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10990:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10991:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10992:     my $symb_crs = $what;
                   10993:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10994:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10995:     my ($tmp)=keys(%current_permissions);
                   10996:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10997:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10998:     foreach my $file (@readonly_files) {
1.759     albertel 10999: 	my $clean_file = &declutter_portfile($file);
                   11000: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11001: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11002:         my @new_locks;
                   11003:         my @del_keys;
                   11004:         if (ref($current_locks) eq "ARRAY"){
                   11005:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11006:                 my $compare=$locker;
1.749     raeburn  11007:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11008:                     $compare=join('',@{$locker});
1.746     raeburn  11009:                     if ($compare ne $symb_crs) {
                   11010:                         push(@new_locks, $locker);
                   11011:                     }
1.563     banghart 11012:                 }
                   11013:             }
1.650     albertel 11014:             if (scalar(@new_locks) > 0) {
1.563     banghart 11015:                 $current_permissions{$file} = \@new_locks;
                   11016:             } else {
                   11017:                 push(@del_keys, $file);
1.613     albertel 11018:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11019:                 delete($current_permissions{$file});
1.563     banghart 11020:             }
                   11021:         }
1.561     banghart 11022:     }
1.613     albertel 11023:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11024:     return;
                   11025: }
1.512     banghart 11026: 
1.17      www      11027: # ------------------------------------------------------------ Directory lister
                   11028: 
                   11029: sub dirlist {
1.955     raeburn  11030:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11031:     $uri=~s/^\///;
                   11032:     $uri=~s/\/$//;
1.253     stredwic 11033:     my ($udom, $uname);
1.955     raeburn  11034:     if ($getuserdir) {
1.253     stredwic 11035:         $udom = $userdomain;
                   11036:         $uname = $username;
1.955     raeburn  11037:     } else {
                   11038:         (undef,$udom,$uname)=split(/\//,$uri);
                   11039:         if(defined($userdomain)) {
                   11040:             $udom = $userdomain;
                   11041:         }
                   11042:         if(defined($username)) {
                   11043:             $uname = $username;
                   11044:         }
1.253     stredwic 11045:     }
1.955     raeburn  11046:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11047: 
1.955     raeburn  11048:     $dirRoot = $perlvar{'lonDocRoot'};
                   11049:     if (defined($getpropath)) {
                   11050:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11051:         $dirRoot =~ s/\/$//;
1.955     raeburn  11052:     } elsif (defined($getuserdir)) {
                   11053:         my $subdir=$uname.'__';
                   11054:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11055:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11056:                    ."/$udom/$subdir/$uname";
                   11057:     } elsif (defined($alternateRoot)) {
                   11058:         $dirRoot = $alternateRoot;
1.751     banghart 11059:     }
1.253     stredwic 11060: 
                   11061:     if($udom) {
                   11062:         if($uname) {
1.1135    raeburn  11063:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11064:             if ($uhome eq 'no_host') {
                   11065:                 return ([],'no_host');
                   11066:             }
1.955     raeburn  11067:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11068:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11069:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11070:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11071:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11072:             } else {
                   11073:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11074:             }
1.605     matthew  11075:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11076:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11077:                 @listing_results = split(/:/,$listing);
                   11078:             } else {
                   11079:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11080:             }
1.1135    raeburn  11081:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11082:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11083:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11084:                 return ([],$listing);
                   11085:             } else {
                   11086:                 return (\@listing_results);
1.1135    raeburn  11087:             }
1.955     raeburn  11088:         } elsif(!$alternateRoot) {
1.1136    raeburn  11089:             my (%allusers,%listerror);
1.841     albertel 11090: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11091:  	    foreach my $tryserver (keys(%servers)) {
                   11092:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11093:                                   &escape($udom),$tryserver);
                   11094:                 if ($listing eq 'unknown_cmd') {
                   11095: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11096: 				      $udom, $tryserver);
                   11097:                 } else {
                   11098:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11099:                 }
1.841     albertel 11100: 		if ($listing eq 'unknown_cmd') {
                   11101: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11102: 				      $udom, $tryserver);
                   11103: 		    @listing_results = split(/:/,$listing);
                   11104: 		} else {
                   11105: 		    @listing_results =
                   11106: 			map { &unescape($_); } split(/:/,$listing);
                   11107: 		}
1.1136    raeburn  11108:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11109:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11110:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11111:                     $listerror{$tryserver} = $listing;
                   11112:                 } else {
1.841     albertel 11113: 		    foreach my $line (@listing_results) {
                   11114: 			my ($entry) = split(/&/,$line,2);
                   11115: 			$allusers{$entry} = 1;
                   11116: 		    }
                   11117: 		}
1.253     stredwic 11118:             }
1.1136    raeburn  11119:             my @alluserslist=();
1.800     albertel 11120:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11121:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11122:             }
1.1172.2.80  raeburn  11123:             if (!%listerror) {
                   11124:                 # no errors
                   11125:                 return (\@alluserslist);
                   11126:             } elsif (scalar(keys(%servers)) == 1) {
                   11127:                 # one library server, one error
                   11128:                 my ($key) = keys(%listerror);
                   11129:                 return (\@alluserslist, $listerror{$key});
                   11130:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11131:                 # con_lost indicates that we might miss data from at least one
                   11132:                 # library server
                   11133:                 return (\@alluserslist, 'con_lost');
                   11134:             } else {
                   11135:                 # multiple library servers and no con_lost -> data should be
                   11136:                 # complete.
                   11137:                 return (\@alluserslist);
                   11138:             }
                   11139: 
1.253     stredwic 11140:         } else {
1.1136    raeburn  11141:             return ([],'missing username');
1.253     stredwic 11142:         }
1.955     raeburn  11143:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11144:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11145:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11146:         return (\@all_domains);
1.955     raeburn  11147:     } else {
1.1136    raeburn  11148:         return ([],'missing domain');
1.275     stredwic 11149:     }
                   11150: }
                   11151: 
                   11152: # --------------------------------------------- GetFileTimestamp
                   11153: # This function utilizes dirlist and returns the date stamp for
                   11154: # when it was last modified.  It will also return an error of -1
                   11155: # if an error occurs
                   11156: 
                   11157: sub GetFileTimestamp {
1.955     raeburn  11158:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11159:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11160:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11161:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11162:                                     undef,$getuserdir);
                   11163:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11164:         return -1;
                   11165:     }
                   11166:     if (ref($fileref) eq 'ARRAY') {
                   11167:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11168:         # @stats contains first the filename, then the stat output
                   11169:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11170:     } else {
                   11171:         return -1;
1.253     stredwic 11172:     }
1.26      www      11173: }
                   11174: 
1.712     albertel 11175: sub stat_file {
                   11176:     my ($uri) = @_;
1.787     albertel 11177:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11178: 
1.955     raeburn  11179:     my ($udom,$uname,$file);
1.712     albertel 11180:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11181: 	($udom,$uname,$file) =
1.811     albertel 11182: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11183: 	$file = 'userfiles/'.$file;
                   11184:     }
                   11185:     if ($uri =~ m-^/res/-) {
                   11186: 	($udom,$uname) = 
1.807     albertel 11187: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11188: 	$file = $uri;
                   11189:     }
                   11190: 
                   11191:     if (!$udom || !$uname || !$file) {
                   11192: 	# unable to handle the uri
                   11193: 	return ();
                   11194:     }
1.956     raeburn  11195:     my $getpropath;
                   11196:     if ($file =~ /^userfiles\//) {
                   11197:         $getpropath = 1;
                   11198:     }
1.1136    raeburn  11199:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11200:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11201:         return ();
                   11202:     } else {
                   11203:         if (ref($listref) eq 'ARRAY') {
                   11204:             my @stats = split('&',$listref->[0]);
                   11205: 	    shift(@stats); #filename is first
                   11206: 	    return @stats;
                   11207:         }
1.712     albertel 11208:     }
                   11209:     return ();
                   11210: }
                   11211: 
1.26      www      11212: # -------------------------------------------------------- Value of a Condition
                   11213: 
1.713     albertel 11214: # gets the value of a specific preevaluated condition
                   11215: #    stored in the string  $env{user.state.<cid>}
                   11216: # or looks up a condition reference in the bighash and if if hasn't
                   11217: # already been evaluated recurses into docondval to get the value of
                   11218: # the condition, then memoizing it to 
                   11219: #   $env{user.state.<cid>.<condition>}
1.40      www      11220: sub directcondval {
                   11221:     my $number=shift;
1.620     albertel 11222:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11223: 	&Apache::lonuserstate::evalstate();
                   11224:     }
1.713     albertel 11225:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11226: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11227:     } elsif ($number =~ /^_/) {
                   11228: 	my $sub_condition;
                   11229: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11230: 		&GDBM_READER(),0640)) {
                   11231: 	    $sub_condition=$bighash{'conditions'.$number};
                   11232: 	    untie(%bighash);
                   11233: 	}
                   11234: 	my $value = &docondval($sub_condition);
1.949     raeburn  11235: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11236: 	return $value;
                   11237:     }
1.620     albertel 11238:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11239:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11240:     } else {
                   11241:        return 2;
                   11242:     }
                   11243: }
                   11244: 
1.713     albertel 11245: # get the collection of conditions for this resource
1.26      www      11246: sub condval {
                   11247:     my $condidx=shift;
1.54      www      11248:     my $allpathcond='';
1.713     albertel 11249:     foreach my $cond (split(/\|/,$condidx)) {
                   11250: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11251: 	    $allpathcond.=
                   11252: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11253: 	}
1.191     harris41 11254:     }
1.54      www      11255:     $allpathcond=~s/\|$//;
1.713     albertel 11256:     return &docondval($allpathcond);
                   11257: }
                   11258: 
                   11259: #evaluates an expression of conditions
                   11260: sub docondval {
                   11261:     my ($allpathcond) = @_;
                   11262:     my $result=0;
                   11263:     if ($env{'request.course.id'}
                   11264: 	&& defined($allpathcond)) {
                   11265: 	my $operand='|';
                   11266: 	my @stack;
                   11267: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11268: 	    if ($chunk eq '(') {
                   11269: 		push @stack,($operand,$result);
                   11270: 	    } elsif ($chunk eq ')') {
                   11271: 		my $before=pop @stack;
                   11272: 		if (pop @stack eq '&') {
                   11273: 		    $result=$result>$before?$before:$result;
                   11274: 		} else {
                   11275: 		    $result=$result>$before?$result:$before;
                   11276: 		}
                   11277: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11278: 		$operand=$chunk;
                   11279: 	    } else {
                   11280: 		my $new=directcondval($chunk);
                   11281: 		if ($operand eq '&') {
                   11282: 		    $result=$result>$new?$new:$result;
                   11283: 		} else {
                   11284: 		    $result=$result>$new?$result:$new;
                   11285: 		}
                   11286: 	    }
                   11287: 	}
1.26      www      11288:     }
                   11289:     return $result;
1.421     albertel 11290: }
                   11291: 
                   11292: # ---------------------------------------------------- Devalidate courseresdata
                   11293: 
                   11294: sub devalidatecourseresdata {
                   11295:     my ($coursenum,$coursedomain)=@_;
                   11296:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11297:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11298: }
                   11299: 
1.763     www      11300: 
1.200     www      11301: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11302: #
                   11303: #  Parameters:
                   11304: #      $coursenum    - Number of the course.
                   11305: #      $coursedomain - Domain at which the course was created.
                   11306: #  Returns:
                   11307: #     A hash of the course parameters along (I think) with timestamps
                   11308: #     and version info.
1.877     foxr     11309: 
1.624     albertel 11310: sub get_courseresdata {
                   11311:     my ($coursenum,$coursedomain)=@_;
1.200     www      11312:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11313:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11314:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11315:     my %dumpreply;
1.417     albertel 11316:     unless (defined($cached)) {
1.624     albertel 11317: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11318: 	$result=\%dumpreply;
1.251     albertel 11319: 	my ($tmp) = keys(%dumpreply);
                   11320: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11321: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11322: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11323: 	    return $tmp;
1.416     albertel 11324: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11325: 	    $result=undef;
1.599     albertel 11326: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11327: 	}
                   11328:     }
1.624     albertel 11329:     return $result;
                   11330: }
                   11331: 
1.633     albertel 11332: sub devalidateuserresdata {
                   11333:     my ($uname,$udom)=@_;
                   11334:     my $hashid="$udom:$uname";
                   11335:     &devalidate_cache_new('userres',$hashid);
                   11336: }
                   11337: 
1.624     albertel 11338: sub get_userresdata {
                   11339:     my ($uname,$udom)=@_;
                   11340:     #most student don\'t have any data set, check if there is some data
                   11341:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11342: 
                   11343:     my $hashid="$udom:$uname";
                   11344:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11345:     if (!defined($cached)) {
                   11346: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11347: 	$result=\%resourcedata;
                   11348: 	&do_cache_new('userres',$hashid,$result,600);
                   11349:     }
                   11350:     my ($tmp)=keys(%$result);
                   11351:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11352: 	return $result;
                   11353:     }
                   11354:     #error 2 occurs when the .db doesn't exist
                   11355:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11356:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11357: 	    &logthis("<font color=\"blue\">WARNING:".
                   11358: 		     " Trying to get resource data for ".
                   11359: 		     $uname." at ".$udom.": ".
                   11360: 		     $tmp."</font>");
                   11361:         }
1.624     albertel 11362:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11363: 	#&EXT_cache_set($udom,$uname);
                   11364: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11365: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11366:     }
                   11367:     return $tmp;
                   11368: }
1.879     foxr     11369: #----------------------------------------------- resdata - return resource data
                   11370: #  Purpose:
                   11371: #    Return resource data for either users or for a course.
                   11372: #  Parameters:
                   11373: #     $name      - Course/user name.
                   11374: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11375:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11376: #     @which     - Array of names of resources desired.
                   11377: #  Returns:
                   11378: #     The value of the first reasource in @which that is found in the
                   11379: #     resource hash.
                   11380: #  Exceptional Conditions:
                   11381: #     If the $type passed in is not valid (not the string 'course' or 
                   11382: #     'user', an undefined  reference is returned.
                   11383: #     If none of the resources are found, an undef is returned
1.624     albertel 11384: sub resdata {
                   11385:     my ($name,$domain,$type,@which)=@_;
                   11386:     my $result;
                   11387:     if ($type eq 'course') {
                   11388: 	$result=&get_courseresdata($name,$domain);
                   11389:     } elsif ($type eq 'user') {
                   11390: 	$result=&get_userresdata($name,$domain);
                   11391:     }
                   11392:     if (!ref($result)) { return $result; }    
1.251     albertel 11393:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11394:20): 	if (defined($result->{$item->[0]})) {
                   11395:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11396:20):         }
1.250     albertel 11397:     }
1.291     albertel 11398:     return undef;
1.200     www      11399: }
                   11400: 
1.1172.2.118.  .10(raeb 11401:-20): sub get_domain_lti {
                   11402:-20):     my ($cdom,$context) = @_;
                   11403:-20):     my ($name,%lti);
                   11404:-20):     if ($context eq 'consumer') {
                   11405:-20):         $name = 'ltitools';
                   11406:-20):     } elsif ($context eq 'provider') {
                   11407:-20):         $name = 'lti';
                   11408:-20):     } else {
                   11409:-20):         return %lti;
                   11410:-20):     }
                   11411:-20):     my ($result,$cached)=&is_cached_new($name,$cdom);
          .1(raebu 11412:20):     if (defined($cached)) {
                   11413:20):         if (ref($result) eq 'HASH') {
          .10(raeb 11414:-20):             %lti = %{$result};
          .1(raebu 11415:20):         }
                   11416:20):     } else {
          .10(raeb 11417:-20):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11418:-20):         if (ref($domconfig{$name}) eq 'HASH') {
                   11419:-20):             %lti = %{$domconfig{$name}};
                   11420:-20):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11421:-20):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11422:-20):                 foreach my $id (keys(%lti)) {
                   11423:-20):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
          .1(raebu 11424:20):                         foreach my $item ('key','secret') {
          .10(raeb 11425:-20):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
          .1(raebu 11426:20):                         }
                   11427:20):                     }
                   11428:20):                 }
                   11429:20):             }
                   11430:20):         }
                   11431:20):         my $cachetime = 24*60*60;
          .10(raeb 11432:-20):         &do_cache_new($name,$cdom,\%lti,$cachetime);
          .1(raebu 11433:20):     }
          .10(raeb 11434:-20):     return %lti;
          .1(raebu 11435:20): }
                   11436:20): 
1.1172.2.31  raeburn  11437: sub get_numsuppfiles {
                   11438:     my ($cnum,$cdom,$ignorecache)=@_;
                   11439:     my $hashid=$cnum.':'.$cdom;
                   11440:     my ($suppcount,$cached);
                   11441:     unless ($ignorecache) {
                   11442:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11443:     }
                   11444:     unless (defined($cached)) {
                   11445:         my $chome=&homeserver($cnum,$cdom);
                   11446:         unless ($chome eq 'no_host') {
                   11447:             ($suppcount,my $errors) = (0,0);
                   11448:             my $suppmap = 'supplemental.sequence';
                   11449:             ($suppcount,$errors) =
                   11450:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11451:         }
                   11452:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11453:     }
                   11454:     return $suppcount;
                   11455: }
                   11456: 
1.379     matthew  11457: #
                   11458: # EXT resource caching routines
                   11459: #
                   11460: 
                   11461: sub clear_EXT_cache_status {
1.383     albertel 11462:     &delenv('cache.EXT.');
1.379     matthew  11463: }
                   11464: 
                   11465: sub EXT_cache_status {
                   11466:     my ($target_domain,$target_user) = @_;
1.383     albertel 11467:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11468:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11469:         # We know already the user has no data
                   11470:         return 1;
                   11471:     } else {
                   11472:         return 0;
                   11473:     }
                   11474: }
                   11475: 
                   11476: sub EXT_cache_set {
                   11477:     my ($target_domain,$target_user) = @_;
1.383     albertel 11478:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11479:     #&appenv({$cachename => time});
1.379     matthew  11480: }
                   11481: 
1.28      www      11482: # --------------------------------------------------------- Value of a Variable
1.58      www      11483: sub EXT {
1.715     albertel 11484: 
1.1172.2.28  raeburn  11485:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11486:     unless ($varname) { return ''; }
1.218     albertel 11487:     #get real user name/domain, courseid and symb
                   11488:     my $courseid;
1.359     albertel 11489:     my $publicuser;
1.427     www      11490:     if ($symbparm) {
                   11491: 	$symbparm=&get_symb_from_alias($symbparm);
                   11492:     }
1.218     albertel 11493:     if (!($uname && $udom)) {
1.790     albertel 11494:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11495:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11496:     } else {
1.620     albertel 11497: 	$courseid=$env{'request.course.id'};
1.218     albertel 11498:     }
1.48      www      11499:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11500:     my $rest;
1.320     albertel 11501:     if (defined($therest[0])) {
1.48      www      11502:        $rest=join('.',@therest);
                   11503:     } else {
                   11504:        $rest='';
                   11505:     }
1.320     albertel 11506: 
1.57      www      11507:     my $qualifierrest=$qualifier;
                   11508:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11509:     my $spacequalifierrest=$space;
                   11510:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11511:     if ($realm eq 'user') {
1.48      www      11512: # --------------------------------------------------------------- user.resource
                   11513: 	if ($space eq 'resource') {
1.651     albertel 11514: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11515: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11516: 		 &&
1.744     albertel 11517: 		 ($symbparm eq &symbread()) ) {	
                   11518: 		# if we are in the middle of processing the resource the
                   11519: 		# get the value we are planning on committing
                   11520:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11521:                     return $Apache::lonhomework::results{$qualifierrest};
                   11522:                 } else {
                   11523:                     return $Apache::lonhomework::history{$qualifierrest};
                   11524:                 }
1.335     albertel 11525: 	    } else {
1.359     albertel 11526: 		my %restored;
1.620     albertel 11527: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11528: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11529: 		} else {
                   11530: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11531: 		}
1.335     albertel 11532: 		return $restored{$qualifierrest};
                   11533: 	    }
1.48      www      11534: # ----------------------------------------------------------------- user.access
                   11535:         } elsif ($space eq 'access') {
1.218     albertel 11536: 	    # FIXME - not supporting calls for a specific user
1.48      www      11537:             return &allowed($qualifier,$rest);
                   11538: # ------------------------------------------ user.preferences, user.environment
                   11539:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11540: 	    if (($uname eq $env{'user.name'}) &&
                   11541: 		($udom eq $env{'user.domain'})) {
                   11542: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11543: 	    } else {
1.359     albertel 11544: 		my %returnhash;
                   11545: 		if (!$publicuser) {
                   11546: 		    %returnhash=&userenvironment($udom,$uname,
                   11547: 						 $qualifierrest);
                   11548: 		}
1.218     albertel 11549: 		return $returnhash{$qualifierrest};
                   11550: 	    }
1.48      www      11551: # ----------------------------------------------------------------- user.course
                   11552:         } elsif ($space eq 'course') {
1.218     albertel 11553: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11554:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11555: # ------------------------------------------------------------------- user.role
                   11556:         } elsif ($space eq 'role') {
1.218     albertel 11557: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11558:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11559:             if ($qualifier eq 'value') {
                   11560: 		return $role;
                   11561:             } elsif ($qualifier eq 'extent') {
                   11562:                 return $where;
                   11563:             }
                   11564: # ----------------------------------------------------------------- user.domain
                   11565:         } elsif ($space eq 'domain') {
1.218     albertel 11566:             return $udom;
1.48      www      11567: # ------------------------------------------------------------------- user.name
                   11568:         } elsif ($space eq 'name') {
1.218     albertel 11569:             return $uname;
1.48      www      11570: # ---------------------------------------------------- Any other user namespace
1.29      www      11571:         } else {
1.359     albertel 11572: 	    my %reply;
                   11573: 	    if (!$publicuser) {
                   11574: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11575: 	    }
                   11576: 	    return $reply{$qualifierrest};
1.48      www      11577:         }
1.236     www      11578:     } elsif ($realm eq 'query') {
                   11579: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11580:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11581: 						[$spacequalifierrest]);
1.620     albertel 11582: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11583:    } elsif ($realm eq 'request') {
1.48      www      11584: # ------------------------------------------------------------- request.browser
                   11585:         if ($space eq 'browser') {
1.1145    bisitz   11586:             return $env{'browser.'.$qualifier};
1.57      www      11587: # ------------------------------------------------------------ request.filename
                   11588:         } else {
1.620     albertel 11589:             return $env{'request.'.$spacequalifierrest};
1.29      www      11590:         }
1.28      www      11591:     } elsif ($realm eq 'course') {
1.48      www      11592: # ---------------------------------------------------------- course.description
1.620     albertel 11593:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11594:     } elsif ($realm eq 'resource') {
1.165     www      11595: 
1.620     albertel 11596: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11597: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11598: 	}
1.693     albertel 11599: 
1.1172.2.30  raeburn  11600:         if ($qualifier eq '') {
                   11601: 	    if ($space eq 'title') {
                   11602: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11603: 	        return &gettitle($symbparm);
                   11604: 	    }
1.693     albertel 11605: 	
1.1172.2.30  raeburn  11606: 	    if ($space eq 'map') {
                   11607: 	        my ($map) = &decode_symb($symbparm);
                   11608: 	        return &symbread($map);
                   11609: 	    }
                   11610:             if ($space eq 'maptitle') {
                   11611:                 my ($map) = &decode_symb($symbparm);
                   11612:                 return &gettitle($map);
                   11613:             }
                   11614: 	    if ($space eq 'filename') {
                   11615: 	        if ($symbparm) {
                   11616: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11617: 	        }
                   11618: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11619: 	    }
1.1172.2.30  raeburn  11620: 
                   11621:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11622:                 if ($space eq 'visibleparts') {
                   11623:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11624:                     my $item;
                   11625:                     if (ref($navmap)) {
                   11626:                         my $res = $navmap->getBySymb($symbparm);
                   11627:                         my $parts = $res->parts();
                   11628:                         if (ref($parts) eq 'ARRAY') {
                   11629:                             $item = join(',',@{$parts});
                   11630:                         }
                   11631:                         undef($navmap);
                   11632:                     }
                   11633:                     return $item;
                   11634:                 }
                   11635:             }
                   11636:         }
1.693     albertel 11637: 
                   11638: 	my ($section, $group, @groups);
1.593     albertel 11639: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11640:         if (($courseid eq '') && ($cid)) {
                   11641:             $courseid = $cid;
                   11642:         }
                   11643: 	if (($symbparm && $courseid) && 
                   11644: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11645: 
1.218     albertel 11646: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11647: 
1.60      www      11648: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11649: 	    my $symbp=$symbparm;
1.735     albertel 11650: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11651: 
                   11652: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11653: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11654: 
1.620     albertel 11655: 	    if (($env{'user.name'} eq $uname) &&
                   11656: 		($env{'user.domain'} eq $udom)) {
                   11657: 		$section=$env{'request.course.sec'};
1.733     raeburn  11658:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11659:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11660: 	    } else {
1.539     albertel 11661: 		if (! defined($usection)) {
1.551     albertel 11662: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11663: 		} else {
                   11664: 		    $section = $usection;
                   11665: 		}
1.733     raeburn  11666:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11667: 	    }
                   11668: 
                   11669: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11670: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11671: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11672: 
1.593     albertel 11673: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11674: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11675: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11676: 
1.60      www      11677: # ----------------------------------------------------------- first, check user
1.624     albertel 11678: 
                   11679: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11680: 				       ([$courselevelr,'resource'],
                   11681: 					[$courselevelm,'map'     ],
                   11682: 					[$courselevel, 'course'  ]));
1.931     albertel 11683: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11684: 
1.594     albertel 11685: # ------------------------------------------------ second, check some of course
1.684     raeburn  11686:             my $coursereply;
1.691     raeburn  11687:             if (@groups > 0) {
                   11688:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11689:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11690:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11691:             }
1.96      www      11692: 
1.684     raeburn  11693: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11694: 				  $env{'course.'.$courseid.'.domain'},
                   11695: 				  'course',
                   11696: 				  ([$seclevelr,   'resource'],
                   11697: 				   [$seclevelm,   'map'     ],
                   11698: 				   [$seclevel,    'course'  ],
                   11699: 				   [$courselevelr,'resource']));
                   11700: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11701: 
1.60      www      11702: # ------------------------------------------------------ third, check map parms
1.218     albertel 11703: 	    my %parmhash=();
                   11704: 	    my $thisparm='';
                   11705: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11706: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11707: 		    &GDBM_READER(),0640)) {
1.218     albertel 11708: 		$thisparm=$parmhash{$symbparm};
                   11709: 		untie(%parmhash);
                   11710: 	    }
1.927     albertel 11711: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11712: 	}
1.594     albertel 11713: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11714: 
1.218     albertel 11715: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11716: 	my $filename;
                   11717: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11718: 	if ($symbparm) {
1.409     www      11719: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11720: 	} else {
1.620     albertel 11721: 	    $filename=$env{'request.filename'};
1.282     albertel 11722: 	}
                   11723: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11724: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11725: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11726: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11727: 
1.927     albertel 11728: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11729: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11730: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11731: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11732: 				     $env{'course.'.$courseid.'.domain'},
                   11733: 				     'course',
1.927     albertel 11734: 				     ([$courselevelm,'map'   ],
                   11735: 				      [$courselevel, 'course']));
                   11736: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11737: 	}
1.145     www      11738: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11739: 	unless ($space eq '0') {
1.336     albertel 11740: 	    my @parts=split(/_/,$space);
                   11741: 	    my $id=pop(@parts);
                   11742: 	    my $part=join('_',@parts);
                   11743: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11744: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11745: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11746: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11747: 	}
1.395     albertel 11748: 	if ($recurse) { return undef; }
                   11749: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11750: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11751: # ---------------------------------------------------- Any other user namespace
                   11752:     } elsif ($realm eq 'environment') {
                   11753: # ----------------------------------------------------------------- environment
1.620     albertel 11754: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11755: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11756: 	} else {
1.770     albertel 11757: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11758: 		return '';
                   11759: 	    }
1.219     albertel 11760: 	    my %returnhash=&userenvironment($udom,$uname,
                   11761: 					    $spacequalifierrest);
                   11762: 	    return $returnhash{$spacequalifierrest};
                   11763: 	}
1.28      www      11764:     } elsif ($realm eq 'system') {
1.48      www      11765: # ----------------------------------------------------------------- system.time
                   11766: 	if ($space eq 'time') {
                   11767: 	    return time;
                   11768:         }
1.696     albertel 11769:     } elsif ($realm eq 'server') {
                   11770: # ----------------------------------------------------------------- system.time
                   11771: 	if ($space eq 'name') {
                   11772: 	    return $ENV{'SERVER_NAME'};
                   11773:         }
1.28      www      11774:     }
1.48      www      11775:     return '';
1.61      www      11776: }
                   11777: 
1.927     albertel 11778: sub get_reply {
                   11779:     my ($reply_value) = @_;
1.940     raeburn  11780:     if (ref($reply_value) eq 'ARRAY') {
                   11781:         if (wantarray) {
                   11782: 	    return @$reply_value;
                   11783:         }
                   11784:         return $reply_value->[0];
                   11785:     } else {
                   11786:         return $reply_value;
1.927     albertel 11787:     }
                   11788: }
                   11789: 
1.691     raeburn  11790: sub check_group_parms {
                   11791:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11792:     my @groupitems = ();
                   11793:     my $resultitem;
1.927     albertel 11794:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11795:     foreach my $group (@{$groups}) {
                   11796:         foreach my $level (@levels) {
1.927     albertel 11797:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11798:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11799:         }
                   11800:     }
                   11801:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11802:                             $env{'course.'.$courseid.'.domain'},
                   11803:                                      'course',@groupitems);
                   11804:     return $coursereply;
                   11805: }
                   11806: 
                   11807: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11808:     my ($courseid,@groups) = @_;
                   11809:     @groups = sort(@groups);
1.691     raeburn  11810:     return @groups;
                   11811: }
                   11812: 
1.395     albertel 11813: sub packages_tab_default {
                   11814:     my ($uri,$varname)=@_;
                   11815:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11816: 
                   11817:     my (@extension,@specifics,$do_default);
                   11818:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11819: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11820: 	if ($pack_type eq 'default') {
                   11821: 	    $do_default=1;
                   11822: 	} elsif ($pack_type eq 'extension') {
                   11823: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11824: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11825: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11826: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11827: 	}
                   11828:     }
                   11829:     # first look for a package that matches the requested part id
                   11830:     foreach my $package (@specifics) {
                   11831: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11832: 	next if ($pack_part ne $part);
                   11833: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11834: 	    return $packagetab{"$pack_type&$name&default"};
                   11835: 	}
                   11836:     }
                   11837:     # look for any possible matching non extension_ package
                   11838:     foreach my $package (@specifics) {
                   11839: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11840: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11841: 	    return $packagetab{"$pack_type&$name&default"};
                   11842: 	}
1.585     albertel 11843: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11844: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11845: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11846: 	}
                   11847:     }
1.738     albertel 11848:     # look for any posible extension_ match
                   11849:     foreach my $package (@extension) {
                   11850: 	my ($package,$pack_type)=@{$package};
                   11851: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11852: 	    return $packagetab{"$pack_type&$name&default"};
                   11853: 	}
                   11854: 	if (defined($packagetab{$package."&$name&default"})) {
                   11855: 	    return $packagetab{$package."&$name&default"};
                   11856: 	}
                   11857:     }
                   11858:     # look for a global default setting
                   11859:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11860: 	return $packagetab{"default&$name&default"};
                   11861:     }
1.395     albertel 11862:     return undef;
                   11863: }
                   11864: 
1.334     albertel 11865: sub add_prefix_and_part {
                   11866:     my ($prefix,$part)=@_;
                   11867:     my $keyroot;
                   11868:     if (defined($prefix) && $prefix !~ /^__/) {
                   11869: 	# prefix that has a part already
                   11870: 	$keyroot=$prefix;
                   11871:     } elsif (defined($prefix)) {
                   11872: 	# prefix that is missing a part
                   11873: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11874:     } else {
                   11875: 	# no prefix at all
                   11876: 	if (defined($part)) { $keyroot='_'.$part; }
                   11877:     }
                   11878:     return $keyroot;
                   11879: }
                   11880: 
1.71      www      11881: # ---------------------------------------------------------------- Get metadata
                   11882: 
1.599     albertel 11883: my %metaentry;
1.1070    www      11884: my %importedpartids;
1.1172.2.99  raeburn  11885: my %importedrespids;
1.71      www      11886: sub metadata {
1.176     www      11887:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11888:     $uri=&declutter($uri);
1.288     albertel 11889:     # if it is a non metadata possible uri return quickly
1.529     albertel 11890:     if (($uri eq '') || 
                   11891: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11892:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11893:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11894: 	return undef;
                   11895:     }
1.1172.2.49  raeburn  11896:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11897: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11898: 	return undef;
1.288     albertel 11899:     }
1.73      www      11900:     my $filename=$uri;
                   11901:     $uri=~s/\.meta$//;
1.172     www      11902: #
                   11903: # Is the metadata already cached?
1.177     www      11904: # Look at timestamp of caching
1.172     www      11905: # Everything is cached by the main uri, libraries are never directly cached
                   11906: #
1.428     albertel 11907:     if (!defined($liburi)) {
1.599     albertel 11908: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11909: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11910:     }
                   11911:     {
1.1069    www      11912: # Imported parts would go here
1.1172.2.99  raeburn  11913:         my @origfiletagids=();
1.1069    www      11914:         my $importedparts=0;
1.1172.2.99  raeburn  11915: 
                   11916: # Imported responseids would go here
                   11917:         my $importedresponses=0;
1.172     www      11918: #
                   11919: # Is this a recursive call for a library?
                   11920: #
1.599     albertel 11921: #	if (! exists($metacache{$uri})) {
                   11922: #	    $metacache{$uri}={};
                   11923: #	}
1.924     albertel 11924: 	my $cachetime = 60*60;
1.171     www      11925:         if ($liburi) {
                   11926: 	    $liburi=&declutter($liburi);
                   11927:             $filename=$liburi;
1.401     bowersj2 11928:         } else {
1.599     albertel 11929: 	    &devalidate_cache_new('meta',$uri);
                   11930: 	    undef(%metaentry);
1.401     bowersj2 11931: 	}
1.140     www      11932:         my %metathesekeys=();
1.73      www      11933:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11934: 	my $metastring;
1.1140    www      11935: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11936: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11937: 	    $metastring = 
1.929     albertel 11938: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11939: 					  ('grade_target' => 'meta'));
                   11940: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11941: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11942:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11943: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11944: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11945: 	    $metastring=&getfile($file);
1.489     albertel 11946: 	}
1.208     albertel 11947:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11948:         my $token;
1.140     www      11949:         undef %metathesekeys;
1.71      www      11950:         while ($token=$parser->get_token) {
1.339     albertel 11951: 	    if ($token->[0] eq 'S') {
                   11952: 		if (defined($token->[2]->{'package'})) {
1.172     www      11953: #
                   11954: # This is a package - get package info
                   11955: #
1.339     albertel 11956: 		    my $package=$token->[2]->{'package'};
                   11957: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11958: 		    if (defined($token->[2]->{'id'})) { 
                   11959: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11960: 		    }
1.599     albertel 11961: 		    if ($metaentry{':packages'}) {
                   11962: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11963: 		    } else {
1.599     albertel 11964: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11965: 		    }
1.736     albertel 11966: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11967: 			my $part=$keyroot;
                   11968: 			$part=~s/^\_//;
1.736     albertel 11969: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11970: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11971: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11972: 			    # ignore package.tab specified default values
                   11973:                             # here &package_tab_default() will fetch those
                   11974: 			    if ($subp eq 'default') { next; }
1.736     albertel 11975: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11976: 			    my $unikey;
                   11977: 			    if ($pack =~ /_0$/) {
                   11978: 				$unikey='parameter_0_'.$name;
                   11979: 				$part=0;
                   11980: 			    } else {
                   11981: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11982: 			    }
1.339     albertel 11983: 			    if ($subp eq 'display') {
                   11984: 				$value.=' [Part: '.$part.']';
                   11985: 			    }
1.599     albertel 11986: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11987: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11988: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11989: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11990: 			    }
1.599     albertel 11991: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11992: 				$metaentry{':'.$unikey}=
                   11993: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11994: 			    }
1.339     albertel 11995: 			}
                   11996: 		    }
                   11997: 		} else {
1.172     www      11998: #
                   11999: # This is not a package - some other kind of start tag
1.339     albertel 12000: #
                   12001: 		    my $entry=$token->[1];
1.1068    www      12002: 		    my $unikey='';
1.175     www      12003: 
1.339     albertel 12004: 		    if ($entry eq 'import') {
1.175     www      12005: #
                   12006: # Importing a library here
1.339     albertel 12007: #
1.1067    www      12008:                         my $location=$parser->get_text('/import');
                   12009:                         my $dir=$filename;
                   12010:                         $dir=~s|[^/]*$||;
                   12011:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12012: 
                   12013:                         my $importid=$token->[2]->{'id'};
1.1068    www      12014:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12015: #
                   12016: # Check metadata for imported file to
                   12017: # see if it contained response items
                   12018: #
                   12019:                         my %currmetaentry = %metaentry;
                   12020:                         my $libresponseorder = &metadata($location,'responseorder');
                   12021:                         my $origfile;
                   12022:                         if ($libresponseorder ne '') {
                   12023:                             if ($#origfiletagids<0) {
                   12024:                                 undef(%importedrespids);
                   12025:                                 undef(%importedpartids);
                   12026:                             }
                   12027:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12028:                             if (@{$importedrespids{$importid}} > 0) {
                   12029:                                 $importedresponses = 1;
                   12030: # We need to get the original file and the imported file to get the response order correct
                   12031: # Load and inspect original file
                   12032:                                 if ($#origfiletagids<0) {
                   12033:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12034:                                     $origfile=&getfile($origfilelocation);
                   12035:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12036:                                 }
                   12037:                             }
                   12038:                         }
                   12039: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12040: # hash populated for imported library file
                   12041:                         %metaentry = %currmetaentry;
                   12042:                         undef(%currmetaentry);
1.1068    www      12043:                         if ($importmode eq 'problem') {
1.1069    www      12044: # Import as problem/response
1.1068    www      12045:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12046:                         } elsif ($importmode eq 'part') {
                   12047: # Import as part(s)
1.1069    www      12048:                            $importedparts=1;
                   12049: # We need to get the original file and the imported file to get the part order correct
                   12050: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12051: # Load and inspect original file if we didn't do that already
                   12052:                            if ($#origfiletagids<0) {
                   12053:                                undef(%importedrespids);
                   12054:                                undef(%importedpartids);
                   12055:                                if ($origfile eq '') {
                   12056:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12057:                                    $origfile=&getfile($origfilelocation);
                   12058:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12059:                                }
1.1070    www      12060:                            }
                   12061: 
1.1069    www      12062: # Load and inspect imported file
                   12063:                            my $impfile=&getfile($location);
                   12064:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12065:                            if ($#impfilepartids>=0) {
                   12066: # This problem had parts
1.1070    www      12067:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12068:                            } else {
                   12069: # Importing by turning a single problem into a problem part
                   12070: # It gets the import-tags ID as part-ID
                   12071:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12072:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12073:                            }
1.1068    www      12074:                         } else {
                   12075: # Normal import
                   12076:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12077:                            if (defined($token->[2]->{'id'})) {
                   12078:                               $unikey.='_'.$token->[2]->{'id'};
                   12079:                            }
1.1067    www      12080:                         }
                   12081: 
1.339     albertel 12082: 			if ($depthcount<20) {
1.736     albertel 12083: 			    my $metadata = 
                   12084: 				&metadata($uri,'keys', $location,$unikey,
                   12085: 					  $depthcount+1);
                   12086: 			    foreach my $meta (split(',',$metadata)) {
                   12087: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12088: 				$metathesekeys{$meta}=1;
1.339     albertel 12089: 			    }
1.1068    www      12090: 			
                   12091:                         }
1.1067    www      12092: 		    } else {
                   12093: #
                   12094: # Not importing, some other kind of non-package, non-library start tag
                   12095: # 
                   12096:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12097:                         if (defined($token->[2]->{'id'})) {
                   12098:                             $unikey.='_'.$token->[2]->{'id'};
                   12099:                         }
1.339     albertel 12100: 			if (defined($token->[2]->{'name'})) { 
                   12101: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12102: 			}
                   12103: 			$metathesekeys{$unikey}=1;
1.736     albertel 12104: 			foreach my $param (@{$token->[3]}) {
                   12105: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12106: 				$token->[2]->{$param};
1.339     albertel 12107: 			}
                   12108: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12109: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12110: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12111: 		 # only ws inside the tag, and not in default, so use default
                   12112: 		 # as value
1.599     albertel 12113: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12114: 			} elsif ( $internaltext =~ /\S/ ) {
                   12115: 		  # something interesting inside the tag
                   12116: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12117: 			} else {
1.908     albertel 12118: 		  # no interesting values, don't set a default
1.339     albertel 12119: 			}
1.172     www      12120: # end of not-a-package not-a-library import
1.339     albertel 12121: 		    }
1.172     www      12122: # end of not-a-package start tag
1.339     albertel 12123: 		}
1.172     www      12124: # the next is the end of "start tag"
1.339     albertel 12125: 	    }
                   12126: 	}
1.483     albertel 12127: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12128: 	$extension = lc($extension);
                   12129: 	if ($extension eq 'htm') { $extension='html'; }
                   12130: 
1.737     albertel 12131: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12132: 	    #no specific packages #how's our extension
                   12133: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12134: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12135: 					 \%metathesekeys);
                   12136: 	}
1.883     albertel 12137: 
                   12138: 	if (!exists($metaentry{':packages'})
                   12139: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12140: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12141: 		#no specific packages well let's get default then
                   12142: 		if ($key!~/^default&/) { next; }
1.488     albertel 12143: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12144: 					     \%metathesekeys);
                   12145: 	    }
                   12146: 	}
1.338     www      12147: # are there custom rights to evaluate
1.599     albertel 12148: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12149: 
1.338     www      12150:     #
                   12151:     # Importing a rights file here
1.339     albertel 12152:     #
                   12153: 	    unless ($depthcount) {
1.599     albertel 12154: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12155: 		my $dir=$filename;
                   12156: 		$dir=~s|[^/]*$||;
                   12157: 		$location=&filelocation($dir,$location);
1.736     albertel 12158: 		my $rights_metadata =
                   12159: 		    &metadata($uri,'keys',$location,'_rights',
                   12160: 			      $depthcount+1);
                   12161: 		foreach my $rights (split(',',$rights_metadata)) {
                   12162: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12163: 		    $metathesekeys{$rights}=1;
1.339     albertel 12164: 		}
                   12165: 	    }
                   12166: 	}
1.737     albertel 12167: 	# uniqifiy package listing
                   12168: 	my %seen;
                   12169: 	my @uniq_packages =
                   12170: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12171: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12172: 
1.1172.2.99  raeburn  12173:         if (($importedresponses) || ($importedparts)) {
                   12174:             if ($importedparts) {
1.1070    www      12175: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12176:                 $metaentry{':partorder'}='';
                   12177:                 $metathesekeys{'partorder'}=1;
                   12178:             }
                   12179:             if ($importedresponses) {
                   12180: # We had imported responses and need to rebuild responseorder
                   12181:                 $metaentry{':responseorder'}='';
                   12182:                 $metathesekeys{'responseorder'}=1;
                   12183:             }
                   12184:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12185:                 my $origid = $origfiletagids[$index+1];
                   12186:                 if ($origfiletagids[$index] eq 'part') {
                   12187: # Original part, part of the problem
                   12188:                     if ($importedparts) {
                   12189:                         $metaentry{':partorder'}.=','.$origid;
                   12190:                     }
                   12191:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12192:                     if ($importedparts) {
                   12193: # We have imported parts at this position
                   12194:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12195:                     }
                   12196:                     if ($importedresponses) {
                   12197: # We have imported responses at this position
                   12198:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12199:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12200:                         }
                   12201:                     }
                   12202:                 } else {
                   12203: # Original response item, part of the problem
                   12204:                     if ($importedresponses) {
                   12205:                         $metaentry{':responseorder'}.=','.$origid;
                   12206:                     }
                   12207:                 }
                   12208:             }
                   12209:             if ($importedparts) {
                   12210:                 $metaentry{':partorder'}=~s/^\,//;
                   12211:             }
                   12212:             if ($importedresponses) {
                   12213:                 $metaentry{':responseorder'}=~s/^\,//;
                   12214:             }
1.1070    www      12215:         }
                   12216: 
1.737     albertel 12217: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12218: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12219: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12220: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12221: # this is the end of "was not already recently cached
1.71      www      12222:     }
1.599     albertel 12223:     return $metaentry{':'.$what};
1.261     albertel 12224: }
                   12225: 
1.488     albertel 12226: sub metadata_create_package_def {
1.483     albertel 12227:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12228:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12229:     if ($subp eq 'default') { next; }
                   12230:     
1.599     albertel 12231:     if (defined($metaentry{':packages'})) {
                   12232: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12233:     } else {
1.599     albertel 12234: 	$metaentry{':packages'}=$package;
1.483     albertel 12235:     }
                   12236:     my $value=$packagetab{$key};
                   12237:     my $unikey;
                   12238:     $unikey='parameter_0_'.$name;
1.599     albertel 12239:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12240:     $$metathesekeys{$unikey}=1;
1.599     albertel 12241:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12242: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12243:     }
1.599     albertel 12244:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12245: 	$metaentry{':'.$unikey}=
                   12246: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12247:     }
                   12248: }
                   12249: 
1.261     albertel 12250: sub metadata_generate_part0 {
                   12251:     my ($metadata,$metacache,$uri) = @_;
                   12252:     my %allnames;
1.737     albertel 12253:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12254: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12255: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12256: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12257: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12258: 	    $allnames{$name}=$part;
                   12259: 	  }
                   12260: 	}
                   12261:     }
                   12262:     foreach my $name (keys(%allnames)) {
                   12263:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12264:       my $key=":parameter_0_$name";
1.261     albertel 12265:       $$metacache{"$key.part"}='0';
                   12266:       $$metacache{"$key.name"}=$name;
1.428     albertel 12267:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12268: 					   $allnames{$name}.'_'.$name.
                   12269: 					   '.type'};
1.428     albertel 12270:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12271: 			     '.display'};
1.644     www      12272:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12273:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12274:       $$metacache{"$key.display"}=$olddis;
                   12275:     }
1.71      www      12276: }
                   12277: 
1.764     albertel 12278: # ------------------------------------------------------ Devalidate title cache
                   12279: 
                   12280: sub devalidate_title_cache {
                   12281:     my ($url)=@_;
                   12282:     if (!$env{'request.course.id'}) { return; }
                   12283:     my $symb=&symbread($url);
                   12284:     if (!$symb) { return; }
                   12285:     my $key=$env{'request.course.id'}."\0".$symb;
                   12286:     &devalidate_cache_new('title',$key);
                   12287: }
                   12288: 
1.1014    droeschl 12289: # ------------------------------------------------- Get the title of a course
                   12290: 
                   12291: sub current_course_title {
                   12292:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12293: }
1.301     www      12294: # ------------------------------------------------- Get the title of a resource
                   12295: 
                   12296: sub gettitle {
                   12297:     my $urlsymb=shift;
                   12298:     my $symb=&symbread($urlsymb);
1.534     albertel 12299:     if ($symb) {
1.620     albertel 12300: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12301: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12302: 	if (defined($cached)) { 
                   12303: 	    return $result;
                   12304: 	}
1.534     albertel 12305: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12306: 	my $title='';
1.907     albertel 12307: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12308: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12309: 	} else {
                   12310: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12311: 		    &GDBM_READER(),0640)) {
                   12312: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12313: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12314: 		untie(%bighash);
                   12315: 	    }
1.534     albertel 12316: 	}
                   12317: 	$title=~s/\&colon\;/\:/gs;
                   12318: 	if ($title) {
1.1159    www      12319: # Remember both $symb and $title for dynamic metadata
                   12320:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12321:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12322: # Cache this title and then return it
1.599     albertel 12323: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12324: 	}
                   12325: 	$urlsymb=$url;
                   12326:     }
                   12327:     my $title=&metadata($urlsymb,'title');
                   12328:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12329:     return $title;
1.301     www      12330: }
1.613     albertel 12331: 
1.614     albertel 12332: sub get_slot {
                   12333:     my ($which,$cnum,$cdom)=@_;
                   12334:     if (!$cnum || !$cdom) {
1.790     albertel 12335: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12336: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12337: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12338:     }
1.703     albertel 12339:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12340:     my %slotinfo;
                   12341:     if (exists($remembered{$key})) {
                   12342: 	$slotinfo{$which} = $remembered{$key};
                   12343:     } else {
                   12344: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12345: 	&Apache::lonhomework::showhash(%slotinfo);
                   12346: 	my ($tmp)=keys(%slotinfo);
                   12347: 	if ($tmp=~/^error:/) { return (); }
                   12348: 	$remembered{$key} = $slotinfo{$which};
                   12349:     }
1.616     albertel 12350:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12351: 	return %{$slotinfo{$which}};
                   12352:     }
                   12353:     return $slotinfo{$which};
1.614     albertel 12354: }
1.1150    raeburn  12355: 
                   12356: sub get_reservable_slots {
                   12357:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12358:     my $now = time;
                   12359:     my $reservable_info;
                   12360:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12361:     if (exists($remembered{$key})) {
                   12362:         $reservable_info = $remembered{$key};
                   12363:     } else {
                   12364:         my %resv;
                   12365:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12366:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12367:         $reservable_info = \%resv;
                   12368:         $remembered{$key} = $reservable_info;
                   12369:     }
                   12370:     return $reservable_info;
                   12371: }
                   12372: 
                   12373: sub get_course_slots {
                   12374:     my ($cnum,$cdom) = @_;
                   12375:     my $hashid=$cnum.':'.$cdom;
                   12376:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12377:     if (defined($cached)) {
                   12378:         if (ref($result) eq 'HASH') {
                   12379:             return %{$result};
                   12380:         }
                   12381:     } else {
                   12382:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12383:         my ($tmp) = keys(%slots);
                   12384:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12385:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12386:             return %slots;
                   12387:         }
                   12388:     }
                   12389:     return;
                   12390: }
                   12391: 
                   12392: sub devalidate_slots_cache {
                   12393:     my ($cnum,$cdom)=@_;
                   12394:     my $hashid=$cnum.':'.$cdom;
                   12395:     &devalidate_cache_new('allslots',$hashid);
                   12396: }
                   12397: 
1.1172.2.8  raeburn  12398: sub get_coursechange {
                   12399:     my ($cdom,$cnum) = @_;
                   12400:     if ($cdom eq '' || $cnum eq '') {
                   12401:         return unless ($env{'request.course.id'});
                   12402:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12403:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12404:     }
                   12405:     my $hashid=$cdom.'_'.$cnum;
                   12406:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12407:     if ((defined($cached)) && ($change ne '')) {
                   12408:         return $change;
                   12409:     } else {
                   12410:         my %crshash;
                   12411:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12412:         if ($crshash{'internal.contentchange'} eq '') {
                   12413:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12414:             if ($change eq '') {
                   12415:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12416:                 $change = $crshash{'internal.created'};
                   12417:             }
                   12418:         } else {
                   12419:             $change = $crshash{'internal.contentchange'};
                   12420:         }
                   12421:         my $cachetime = 600;
                   12422:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12423:     }
                   12424:     return $change;
                   12425: }
                   12426: 
                   12427: sub devalidate_coursechange_cache {
                   12428:     my ($cnum,$cdom)=@_;
                   12429:     my $hashid=$cnum.':'.$cdom;
                   12430:     &devalidate_cache_new('crschange',$hashid);
                   12431: }
                   12432: 
1.31      www      12433: # ------------------------------------------------- Update symbolic store links
                   12434: 
                   12435: sub symblist {
                   12436:     my ($mapname,%newhash)=@_;
1.438     www      12437:     $mapname=&deversion(&declutter($mapname));
1.31      www      12438:     my %hash;
1.620     albertel 12439:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12440:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12441:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12442: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12443: 		next if ($url eq 'last_known'
                   12444: 			 && $env{'form.no_update_last_known'});
                   12445: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12446: 						    $newhash{$url}->[1],
                   12447: 						    $newhash{$url}->[0]);
1.191     harris41 12448:             }
1.31      www      12449:             if (untie(%hash)) {
                   12450: 		return 'ok';
                   12451:             }
                   12452:         }
                   12453:     }
                   12454:     return 'error';
1.212     www      12455: }
                   12456: 
                   12457: # --------------------------------------------------------------- Verify a symb
                   12458: 
                   12459: sub symbverify {
1.1172.2.11  raeburn  12460:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12461:     my $thisfn=$thisurl;
1.439     www      12462:     $thisfn=&declutter($thisfn);
1.215     www      12463: # direct jump to resource in page or to a sequence - will construct own symbs
                   12464:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12465: # check URL part
1.409     www      12466:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12467: 
1.431     www      12468:     unless ($url eq $thisfn) { return 0; }
1.213     www      12469: 
1.216     www      12470:     $symb=&symbclean($symb);
1.510     www      12471:     $thisurl=&deversion($thisurl);
1.439     www      12472:     $thisfn=&deversion($thisfn);
1.213     www      12473: 
                   12474:     my %bighash;
                   12475:     my $okay=0;
1.431     www      12476: 
1.620     albertel 12477:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12478:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12479:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12480:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12481:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12482:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12483:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12484:             }
                   12485:         }
                   12486:         my $ids;
1.1172.2.118.  .5(raebu 12487:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12488:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12489:         } else {
                   12490:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12491:         }
1.1102    raeburn  12492:         unless ($ids) {
1.1172.2.13  raeburn  12493:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12494:             $ids=$bighash{$idkey};
1.216     www      12495:         }
                   12496:         if ($ids) {
                   12497: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12498:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12499:                 $symb =~ s/\?.+$//;
                   12500:             }
1.800     albertel 12501: 	    foreach my $id (split(/\,/,$ids)) {
                   12502: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12503:                if (
                   12504:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12505:    eq $symb) {
1.1172.2.11  raeburn  12506:                    if (ref($encstate)) {
                   12507:                        $$encstate = $bighash{'encrypted_'.$id};
                   12508:                    }
1.1172.2.13  raeburn  12509:                    if (($env{'request.role.adv'}) ||
                   12510:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12511:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12512:                        $okay=1;
                   12513:                        last;
                   12514:                    }
                   12515:                }
                   12516:            }
1.216     www      12517:         }
1.213     www      12518: 	untie(%bighash);
                   12519:     }
                   12520:     return $okay;
1.31      www      12521: }
                   12522: 
1.210     www      12523: # --------------------------------------------------------------- Clean-up symb
                   12524: 
                   12525: sub symbclean {
                   12526:     my $symb=shift;
1.568     albertel 12527:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12528: # remove version from map
                   12529:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12530: 
1.210     www      12531: # remove version from URL
                   12532:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12533: 
1.507     www      12534: # remove wrapper
                   12535: 
1.510     www      12536:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12537:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12538:     return $symb;
1.409     www      12539: }
                   12540: 
                   12541: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12542: 
                   12543: sub encode_symb {
                   12544:     my ($map,$resid,$url)=@_;
                   12545:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12546: }
1.409     www      12547: 
                   12548: sub decode_symb {
1.568     albertel 12549:     my $symb=shift;
                   12550:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12551:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12552:     return (&fixversion($map),$resid,&fixversion($url));
                   12553: }
                   12554: 
                   12555: sub fixversion {
                   12556:     my $fn=shift;
1.609     banghart 12557:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12558:     my %bighash;
                   12559:     my $uri=&clutter($fn);
1.620     albertel 12560:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12561: # is this cached?
1.599     albertel 12562:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12563:     if (defined($cached)) { return $result; }
                   12564: # unfortunately not cached, or expired
1.620     albertel 12565:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12566: 	    &GDBM_READER(),0640)) {
                   12567:  	if ($bighash{'version_'.$uri}) {
                   12568:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12569:  	    unless (($version eq 'mostrecent') || 
                   12570: 		    ($version==&getversion($uri))) {
1.440     www      12571:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12572:  	    }
                   12573:  	}
                   12574:  	untie %bighash;
1.413     www      12575:     }
1.599     albertel 12576:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12577: }
                   12578: 
                   12579: sub deversion {
                   12580:     my $url=shift;
                   12581:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12582:     return $url;
1.210     www      12583: }
                   12584: 
1.31      www      12585: # ------------------------------------------------------ Return symb list entry
                   12586: 
                   12587: sub symbread {
1.1172.2.118.  .8(raebu 12588:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12589:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12590:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12591:20):     if (defined($env{$cache_str})) {
          .8(raebu 12592:20):         unless (ref($possibles) eq 'HASH') {
                   12593:20):             if ($ignorecachednull) {
                   12594:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12595:20):             } else {
                   12596:20):                 return $env{$cache_str};
                   12597:20):             }
1.1172.2.66  raeburn  12598:         }
                   12599:     }
1.242     www      12600: # no filename provided? try from environment
1.1172.2.54  raeburn  12601:     unless ($thisfn) {
1.620     albertel 12602:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12603:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12604:         }
                   12605:         $thisfn=$env{'request.filename'};
1.44      www      12606:     }
1.569     albertel 12607:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12608: # is that filename actually a symb? Verify, clean, and return
                   12609:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12610: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12611:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12612: 	}
1.242     www      12613:     }
1.44      www      12614:     $thisfn=declutter($thisfn);
1.31      www      12615:     my %hash;
1.37      www      12616:     my %bighash;
                   12617:     my $syval='';
1.620     albertel 12618:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12619:         my $targetfn = $thisfn;
1.609     banghart 12620:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12621:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12622:         }
1.687     albertel 12623: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12624: 	    $targetfn=$1;
                   12625: 	}
1.1172.2.118.  .9(raebu 12626:20):         unless ($ignoresymbdb) {
          .8(raebu 12627:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12628:20):                           &GDBM_READER(),0640)) {
                   12629:20): 	        $syval=$hash{$targetfn};
                   12630:20):                 untie(%hash);
                   12631:20):             }
          .9(raebu 12632:20):             if ($syval && $checkforblock) {
                   12633:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12634:20):                 if (@blockers) {
                   12635:20):                     $syval='';
                   12636:20):                 }
                   12637:20):             }
1.37      www      12638:         }
                   12639: # ---------------------------------------------------------- There was an entry
                   12640:         if ($syval) {
1.601     albertel 12641: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12642: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12643: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12644: 		    #return $env{$cache_str}='';
1.601     albertel 12645: 		#}    
                   12646: 		#$syval.=$1;
                   12647: 	    #}
1.37      www      12648:         } else {
                   12649: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12650:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12651:                             &GDBM_READER(),0640)) {
1.37      www      12652: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12653:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12654:               unless ($ids) { 
                   12655:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12656:               }
                   12657:               unless ($ids) {
                   12658: # alias?
                   12659: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12660:               }
1.37      www      12661:               if ($ids) {
                   12662: # ------------------------------------------------------------------- Has ID(s)
                   12663:                  my @possibilities=split(/\,/,$ids);
1.39      www      12664:                  if ($#possibilities==0) {
                   12665: # ----------------------------------------------- There is only one possibility
1.37      www      12666: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12667: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12668: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12669:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12670:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12671:20):                              $possibles->{$syval} = 1;
                   12672:20):                          }
1.1172.2.66  raeburn  12673:                      }
                   12674:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12675:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12676:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12677:20):                              if (@blockers) {
                   12678:20):                                  $syval = '';
                   12679:20):                                  untie(%bighash);
                   12680:20):                                  return $env{$cache_str}='';
                   12681:20):                              }
1.1172.2.66  raeburn  12682:                          }
                   12683:                      }
                   12684:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12685: # ------------------------------------------ There is more than one possibility
                   12686:                      my $realpossible=0;
1.800     albertel 12687:                      foreach my $id (@possibilities) {
                   12688: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12689:                          my $canaccess;
                   12690:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12691:                              $canaccess = 1;
                   12692:                          } else {
                   12693:                              $canaccess = &allowed('bre',$file);
                   12694:                          }
                   12695:                          if ($canaccess) {
                   12696:          		     my ($mapid,$resid)=split(/\./,$id);
                   12697:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12698:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12699:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12700:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12701:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12702:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12703:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12704:20):                                      if (@blockers > 0) {
                   12705:20):                                          $syval = '';
                   12706:20):                                      } else {
1.1172.2.66  raeburn  12707:                                          $syval = $poss_syval;
                   12708:                                          $realpossible++;
                   12709:                                      }
                   12710:                                  } else {
                   12711:                                      $syval = $poss_syval;
                   12712:                                      $realpossible++;
                   12713:                                  }
1.1172.2.118.  .8(raebu 12714:20):                                  if ($syval) {
                   12715:20):                                      if (ref($possibles) eq 'HASH') {
                   12716:20):                                          $possibles->{$syval} = 1;
                   12717:20):                                      }
                   12718:20):                                  }
1.1172.2.66  raeburn  12719:                              }
1.39      www      12720: 			 }
1.191     harris41 12721:                      }
1.39      www      12722: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12723:                  } else {
                   12724:                      $syval='';
1.37      www      12725:                  }
                   12726: 	      }
1.1172.2.66  raeburn  12727:               untie(%bighash);
1.481     raeburn  12728:            }
1.31      www      12729:         }
1.62      www      12730:         if ($syval) {
1.1172.2.118.  .9(raebu 12731:20): 	    return $env{$cache_str}=$syval;
1.62      www      12732:         }
1.31      www      12733:     }
1.949     raeburn  12734:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12735:     return $env{$cache_str}='';
1.31      www      12736: }
                   12737: 
                   12738: # ---------------------------------------------------------- Return random seed
                   12739: 
1.32      www      12740: sub numval {
                   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;
1.564     albertel 12749:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12750:     return int($txt);
1.368     albertel 12751: }
                   12752: 
1.484     albertel 12753: sub numval2 {
                   12754:     my $txt=shift;
                   12755:     $txt=~tr/A-J/0-9/;
                   12756:     $txt=~tr/a-j/0-9/;
                   12757:     $txt=~tr/K-T/0-9/;
                   12758:     $txt=~tr/k-t/0-9/;
                   12759:     $txt=~tr/U-Z/0-5/;
                   12760:     $txt=~tr/u-z/0-5/;
                   12761:     $txt=~s/\D//g;
                   12762:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12763:     my $total;
                   12764:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12765:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12766:     return int($total);
                   12767: }
                   12768: 
1.575     albertel 12769: sub numval3 {
                   12770:     use integer;
                   12771:     my $txt=shift;
                   12772:     $txt=~tr/A-J/0-9/;
                   12773:     $txt=~tr/a-j/0-9/;
                   12774:     $txt=~tr/K-T/0-9/;
                   12775:     $txt=~tr/k-t/0-9/;
                   12776:     $txt=~tr/U-Z/0-5/;
                   12777:     $txt=~tr/u-z/0-5/;
                   12778:     $txt=~s/\D//g;
                   12779:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12780:     my $total;
                   12781:     foreach my $val (@txts) { $total+=$val; }
                   12782:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12783:     return $total;
                   12784: }
                   12785: 
1.675     albertel 12786: sub digest {
                   12787:     my ($data)=@_;
                   12788:     my $digest=&Digest::MD5::md5($data);
                   12789:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12790:     my ($e,$f);
                   12791:     {
                   12792:         use integer;
                   12793:         $e=($a+$b);
                   12794:         $f=($c+$d);
                   12795:         if ($_64bit) {
                   12796:             $e=(($e<<32)>>32);
                   12797:             $f=(($f<<32)>>32);
                   12798:         }
                   12799:     }
                   12800:     if (wantarray) {
                   12801: 	return ($e,$f);
                   12802:     } else {
                   12803: 	my $g;
                   12804: 	{
                   12805: 	    use integer;
                   12806: 	    $g=($e+$f);
                   12807: 	    if ($_64bit) {
                   12808: 		$g=(($g<<32)>>32);
                   12809: 	    }
                   12810: 	}
                   12811: 	return $g;
                   12812:     }
                   12813: }
                   12814: 
1.368     albertel 12815: sub latest_rnd_algorithm_id {
1.675     albertel 12816:     return '64bit5';
1.366     albertel 12817: }
1.32      www      12818: 
1.503     albertel 12819: sub get_rand_alg {
                   12820:     my ($courseid)=@_;
1.790     albertel 12821:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12822:     if ($courseid) {
1.620     albertel 12823: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12824:     }
                   12825:     return &latest_rnd_algorithm_id();
                   12826: }
                   12827: 
1.562     albertel 12828: sub validCODE {
                   12829:     my ($CODE)=@_;
                   12830:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12831:     return 0;
                   12832: }
                   12833: 
1.491     albertel 12834: sub getCODE {
1.620     albertel 12835:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12836:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12837: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12838: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12839: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12840:     }
                   12841:     return undef;
                   12842: }
1.1133    foxr     12843: #
                   12844: #  Determines the random seed for a specific context:
                   12845: #
                   12846: # parameters:
                   12847: #   symb      - in course context the symb for the seed.
                   12848: #   course_id - The course id of the form domain_coursenum.
                   12849: #   domain    - Domain for the user.
                   12850: #   course    - Course for the user.
                   12851: #   cenv      - environment of the course.
                   12852: #
                   12853: # NOTE:
                   12854: #   All parameters are picked out of the environment if missing
                   12855: #   or not defined.
                   12856: #   If a symb cannot be determined the current time is used instead.
                   12857: #
                   12858: #  For a given well defined symb, courside, domain, username,
                   12859: #  and course environment, the seed is reproducible.
                   12860: #
1.31      www      12861: sub rndseed {
1.1133    foxr     12862:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12863:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12864:     if (!defined($symb)) {
1.366     albertel 12865: 	unless ($symb=$wsymb) { return time; }
                   12866:     }
1.1146    foxr     12867:     if (!defined $courseid) { 
                   12868: 	$courseid=$wcourseid; 
                   12869:     }
                   12870:     if (!defined $domain) { $domain=$wdomain; }
                   12871:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12872: 
                   12873:     my $which;
                   12874:     if (defined($cenv->{'rndseed'})) {
                   12875: 	$which = $cenv->{'rndseed'};
                   12876:     } else {
                   12877: 	$which =&get_rand_alg($courseid);
                   12878:     }
1.491     albertel 12879:     if (defined(&getCODE())) {
1.675     albertel 12880: 	if ($which eq '64bit5') {
                   12881: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12882: 	} elsif ($which eq '64bit4') {
1.575     albertel 12883: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12884: 	} else {
                   12885: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12886: 	}
1.675     albertel 12887:     } elsif ($which eq '64bit5') {
                   12888: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12889:     } elsif ($which eq '64bit4') {
                   12890: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12891:     } elsif ($which eq '64bit3') {
                   12892: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12893:     } elsif ($which eq '64bit2') {
                   12894: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12895:     } elsif ($which eq '64bit') {
                   12896: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12897:     }
                   12898:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12899: }
                   12900: 
                   12901: sub rndseed_32bit {
                   12902:     my ($symb,$courseid,$domain,$username)=@_;
                   12903:     {
                   12904: 	use integer;
                   12905: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12906: 	my $symbseed=numval($symb) << 22;
                   12907: 	my $namechck=unpack("%32C*",$username) << 17;
                   12908: 	my $nameseed=numval($username) << 12;
                   12909: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12910: 	my $courseseed=unpack("%32C*",$courseid);
                   12911: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12912: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12913: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12914: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12915: 	return $num;
                   12916:     }
                   12917: }
                   12918: 
                   12919: sub rndseed_64bit {
                   12920:     my ($symb,$courseid,$domain,$username)=@_;
                   12921:     {
                   12922: 	use integer;
                   12923: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12924: 	my $symbseed=numval($symb) << 10;
                   12925: 	my $namechck=unpack("%32S*",$username);
                   12926: 	
                   12927: 	my $nameseed=numval($username) << 21;
                   12928: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12929: 	my $courseseed=unpack("%32S*",$courseid);
                   12930: 	
                   12931: 	my $num1=$symbchck+$symbseed+$namechck;
                   12932: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12933: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12934: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12935: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12936: 	return "$num1,$num2";
1.155     albertel 12937:     }
1.366     albertel 12938: }
                   12939: 
1.443     albertel 12940: sub rndseed_64bit2 {
                   12941:     my ($symb,$courseid,$domain,$username)=@_;
                   12942:     {
                   12943: 	use integer;
                   12944: 	# strings need to be an even # of cahracters long, it it is odd the
                   12945:         # last characters gets thrown away
                   12946: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12947: 	my $symbseed=numval($symb) << 10;
                   12948: 	my $namechck=unpack("%32S*",$username.' ');
                   12949: 	
                   12950: 	my $nameseed=numval($username) << 21;
1.501     albertel 12951: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12952: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12953: 	
                   12954: 	my $num1=$symbchck+$symbseed+$namechck;
                   12955: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12956: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12957: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12958: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12959: 	return "$num1,$num2";
                   12960:     }
                   12961: }
                   12962: 
                   12963: sub rndseed_64bit3 {
                   12964:     my ($symb,$courseid,$domain,$username)=@_;
                   12965:     {
                   12966: 	use integer;
                   12967: 	# strings need to be an even # of cahracters long, it it is odd the
                   12968:         # last characters gets thrown away
                   12969: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12970: 	my $symbseed=numval2($symb) << 10;
                   12971: 	my $namechck=unpack("%32S*",$username.' ');
                   12972: 	
                   12973: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12974: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12975: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12976: 	
                   12977: 	my $num1=$symbchck+$symbseed+$namechck;
                   12978: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12979: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12980: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12981: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12982: 	
1.503     albertel 12983: 	return "$num1:$num2";
1.443     albertel 12984:     }
                   12985: }
                   12986: 
1.575     albertel 12987: sub rndseed_64bit4 {
                   12988:     my ($symb,$courseid,$domain,$username)=@_;
                   12989:     {
                   12990: 	use integer;
                   12991: 	# strings need to be an even # of cahracters long, it it is odd the
                   12992:         # last characters gets thrown away
                   12993: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12994: 	my $symbseed=numval3($symb) << 10;
                   12995: 	my $namechck=unpack("%32S*",$username.' ');
                   12996: 	
                   12997: 	my $nameseed=numval3($username) << 21;
                   12998: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12999: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13000: 	
                   13001: 	my $num1=$symbchck+$symbseed+$namechck;
                   13002: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13003: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13004: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13005: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13006: 	
1.575     albertel 13007: 	return "$num1:$num2";
                   13008:     }
                   13009: }
                   13010: 
1.675     albertel 13011: sub rndseed_64bit5 {
                   13012:     my ($symb,$courseid,$domain,$username)=@_;
                   13013:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13014:     return "$num1:$num2";
                   13015: }
                   13016: 
1.366     albertel 13017: sub rndseed_CODE_64bit {
                   13018:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13019:     {
1.366     albertel 13020: 	use integer;
1.443     albertel 13021: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13022: 	my $symbseed=numval2($symb);
1.491     albertel 13023: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13024: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13025: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13026: 	my $num1=$symbseed+$CODEchck;
                   13027: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13028: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13029: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13030: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13031: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13032: 	return "$num1:$num2";
1.366     albertel 13033:     }
                   13034: }
                   13035: 
1.575     albertel 13036: sub rndseed_CODE_64bit4 {
                   13037:     my ($symb,$courseid,$domain,$username)=@_;
                   13038:     {
                   13039: 	use integer;
                   13040: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13041: 	my $symbseed=numval3($symb);
                   13042: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13043: 	my $CODEseed=numval3(&getCODE());
                   13044: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13045: 	my $num1=$symbseed+$CODEchck;
                   13046: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13047: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13048: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13049: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13050: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13051: 	return "$num1:$num2";
                   13052:     }
                   13053: }
                   13054: 
1.675     albertel 13055: sub rndseed_CODE_64bit5 {
                   13056:     my ($symb,$courseid,$domain,$username)=@_;
                   13057:     my $code = &getCODE();
                   13058:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13059:     return "$num1:$num2";
                   13060: }
                   13061: 
1.366     albertel 13062: sub setup_random_from_rndseed {
                   13063:     my ($rndseed)=@_;
1.503     albertel 13064:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13065: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13066:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13067:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13068:         } else {
                   13069:             &Math::Random::random_set_seed($num1,$num2);
                   13070:         }
1.366     albertel 13071:     } else {
                   13072: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13073:     }
1.36      albertel 13074: }
                   13075: 
1.474     albertel 13076: sub latest_receipt_algorithm_id {
1.835     albertel 13077:     return 'receipt3';
1.474     albertel 13078: }
                   13079: 
1.480     www      13080: sub recunique {
                   13081:     my $fucourseid=shift;
                   13082:     my $unique;
1.835     albertel 13083:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13084: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13085: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13086:     } else {
                   13087: 	$unique=$perlvar{'lonReceipt'};
                   13088:     }
                   13089:     return unpack("%32C*",$unique);
                   13090: }
                   13091: 
                   13092: sub recprefix {
                   13093:     my $fucourseid=shift;
                   13094:     my $prefix;
1.835     albertel 13095:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13096: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13097: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13098:     } else {
                   13099: 	$prefix=$perlvar{'lonHostID'};
                   13100:     }
                   13101:     return unpack("%32C*",$prefix);
                   13102: }
                   13103: 
1.76      www      13104: sub ireceipt {
1.474     albertel 13105:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13106: 
                   13107:     my $return =&recprefix($fucourseid).'-';
                   13108: 
                   13109:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13110: 	$env{'request.state'} eq 'construct') {
                   13111: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13112: 	return $return;
                   13113:     }
                   13114: 
1.76      www      13115:     my $cuname=unpack("%32C*",$funame);
                   13116:     my $cudom=unpack("%32C*",$fudom);
                   13117:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13118:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13119:     my $cunique=&recunique($fucourseid);
1.474     albertel 13120:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13121:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13122: 
1.790     albertel 13123: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13124: 			       
                   13125: 	$return.= ($cunique%$cuname+
                   13126: 		   $cunique%$cudom+
                   13127: 		   $cusymb%$cuname+
                   13128: 		   $cusymb%$cudom+
                   13129: 		   $cucourseid%$cuname+
                   13130: 		   $cucourseid%$cudom+
                   13131: 		   $cpart%$cuname+
                   13132: 		   $cpart%$cudom);
                   13133:     } else {
                   13134: 	$return.= ($cunique%$cuname+
                   13135: 		   $cunique%$cudom+
                   13136: 		   $cusymb%$cuname+
                   13137: 		   $cusymb%$cudom+
                   13138: 		   $cucourseid%$cuname+
                   13139: 		   $cucourseid%$cudom);
                   13140:     }
                   13141:     return $return;
1.76      www      13142: }
                   13143: 
                   13144: sub receipt {
1.474     albertel 13145:     my ($part)=@_;
1.790     albertel 13146:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13147:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13148: }
1.260     ng       13149: 
1.790     albertel 13150: sub whichuser {
                   13151:     my ($passedsymb)=@_;
                   13152:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13153:     if (defined($env{'form.grade_symb'})) {
                   13154: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13155: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13156: 	if (!$allowed &&
                   13157: 	    exists($env{'request.course.sec'}) &&
                   13158: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13159: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13160: 			      '/'.$env{'request.course.sec'});
                   13161: 	}
                   13162: 	if ($allowed) {
                   13163: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13164: 	    $courseid=$tmp_courseid;
                   13165: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13166: 	    ($name)=&get_env_multiple('form.grade_username');
                   13167: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13168: 	}
                   13169:     }
                   13170:     if (!$passedsymb) {
                   13171: 	$symb=&symbread();
                   13172:     } else {
                   13173: 	$symb=$passedsymb;
                   13174:     }
                   13175:     $courseid=$env{'request.course.id'};
                   13176:     $domain=$env{'user.domain'};
                   13177:     $name=$env{'user.name'};
                   13178:     if ($name eq 'public' && $domain eq 'public') {
                   13179: 	if (!defined($env{'form.username'})) {
                   13180: 	    $env{'form.username'}.=time.rand(10000000);
                   13181: 	}
                   13182: 	$name.=$env{'form.username'};
                   13183:     }
                   13184:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13185: 
                   13186: }
                   13187: 
1.36      albertel 13188: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13189: # returns either the contents of the file or 
                   13190: # -1 if the file doesn't exist
1.481     raeburn  13191: #
                   13192: # if the target is a file that was uploaded via DOCS, 
                   13193: # a check will be made to see if a current copy exists on the local server,
                   13194: # if it does this will be served, otherwise a copy will be retrieved from
                   13195: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13196: # the local server.   
1.472     albertel 13197: 
1.36      albertel 13198: sub getfile {
1.538     albertel 13199:     my ($file) = @_;
1.609     banghart 13200:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13201:     &repcopy($file);
                   13202:     return &readfile($file);
                   13203: }
                   13204: 
                   13205: sub repcopy_userfile {
                   13206:     my ($file)=@_;
1.1142    raeburn  13207:     my $londocroot = $perlvar{'lonDocRoot'};
                   13208:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13209:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13210:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13211: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13212:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13213:     if (-e "$file") {
1.828     www      13214: # we already have a local copy, check it out
1.538     albertel 13215: 	my @fileinfo = stat($file);
1.828     www      13216: 	my $rtncode;
                   13217: 	my $info;
1.538     albertel 13218: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13219: 	if ($lwpresp ne 'ok') {
1.828     www      13220: # there is no such file anymore, even though we had a local copy
1.482     albertel 13221: 	    if ($rtncode eq '404') {
1.538     albertel 13222: 		unlink($file);
1.482     albertel 13223: 	    }
                   13224: 	    return -1;
                   13225: 	}
                   13226: 	if ($info < $fileinfo[9]) {
1.828     www      13227: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13228: 	    return 'ok';
1.828     www      13229: 	} else {
                   13230: # the file is outdated, get rid of it
                   13231: 	    unlink($file);
1.482     albertel 13232: 	}
1.828     www      13233:     }
                   13234: # one way or the other, at this point, we don't have the file
                   13235: # construct the correct path for the file
                   13236:     my @parts = ($cdom,$cnum); 
                   13237:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13238: 	push @parts, split(/\//,$1);
                   13239:     }
                   13240:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13241:     foreach my $part (@parts) {
                   13242: 	$path .= '/'.$part;
                   13243: 	if (!-e $path) {
                   13244: 	    mkdir($path,0770);
1.482     albertel 13245: 	}
                   13246:     }
1.828     www      13247: # now the path exists for sure
                   13248: # get a user agent
                   13249:     my $ua=new LWP::UserAgent;
                   13250:     my $transferfile=$file.'.in.transfer';
                   13251: # FIXME: this should flock
                   13252:     if (-e $transferfile) { return 'ok'; }
                   13253:     my $request;
                   13254:     $uri=~s/^\///;
1.980     raeburn  13255:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13256:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13257:     my $protocol = $protocol{$homeserver};
                   13258:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13259:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13260:     my $response=$ua->request($request,$transferfile);
                   13261: # did it work?
                   13262:     if ($response->is_error()) {
                   13263: 	unlink($transferfile);
                   13264: 	&logthis("Userfile repcopy failed for $uri");
                   13265: 	return -1;
                   13266:     }
                   13267: # worked, rename the transfer file
                   13268:     rename($transferfile,$file);
1.607     raeburn  13269:     return 'ok';
1.481     raeburn  13270: }
                   13271: 
1.517     albertel 13272: sub tokenwrapper {
                   13273:     my $uri=shift;
1.980     raeburn  13274:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13275:     $uri=~s|^/||;
1.620     albertel 13276:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13277:     my $token=$1;
1.552     albertel 13278:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13279:     if ($udom && $uname && $file) {
                   13280: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13281:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13282:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13283:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13284:         my $protocol = $protocol{$homeserver};
                   13285:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13286:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13287:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13288:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13289:     } else {
                   13290:         return '/adm/notfound.html';
                   13291:     }
                   13292: }
                   13293: 
1.828     www      13294: # call with reqtype HEAD: get last modification time
                   13295: # call with reqtype GET: get the file contents
                   13296: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13297: #
1.481     raeburn  13298: sub getuploaded {
                   13299:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13300:     $uri=~s/^\///;
1.980     raeburn  13301:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13302:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13303:     my $protocol = $protocol{$homeserver};
                   13304:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13305:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13306:     my $ua=new LWP::UserAgent;
                   13307:     my $request=new HTTP::Request($reqtype,$uri);
                   13308:     my $response=$ua->request($request);
                   13309:     $$rtncode = $response->code;
1.482     albertel 13310:     if (! $response->is_success()) {
                   13311: 	return 'failed';
                   13312:     }      
                   13313:     if ($reqtype eq 'HEAD') {
1.486     www      13314: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13315:     } elsif ($reqtype eq 'GET') {
                   13316: 	$$info = $response->content;
1.472     albertel 13317:     }
1.482     albertel 13318:     return 'ok';
1.36      albertel 13319: }
                   13320: 
1.481     raeburn  13321: sub readfile {
                   13322:     my $file = shift;
                   13323:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13324:     my $fh;
1.1172.2.96  raeburn  13325:     open($fh,"<",$file);
1.481     raeburn  13326:     my $a='';
1.800     albertel 13327:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13328:     return $a;
                   13329: }
                   13330: 
1.36      albertel 13331: sub filelocation {
1.590     banghart 13332:     my ($dir,$file) = @_;
                   13333:     my $location;
                   13334:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13335: 
                   13336:     if ($file =~ m-^/adm/-) {
                   13337: 	$file=~s-^/adm/wrapper/-/-;
                   13338: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13339:     }
1.882     albertel 13340: 
1.1139    www      13341:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13342:         $location = $file;
1.609     banghart 13343:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13344:         my ($udom,$uname,$filename)=
1.811     albertel 13345:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13346:         my $home=&homeserver($uname,$udom);
                   13347:         my $is_me=0;
                   13348:         my @ids=&current_machine_ids();
                   13349:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13350:         if ($is_me) {
1.1117    foxr     13351:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13352:         } else {
                   13353:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13354:   	      $udom.'/'.$uname.'/'.$filename;
                   13355:         }
1.882     albertel 13356:     } elsif ($file =~ m-^/adm/-) {
                   13357: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13358:     } else {
                   13359:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13360:         $file=~s:^/(res|priv)/:/:;
                   13361:         my $space=$1;
1.590     banghart 13362:         if ( !( $file =~ m:^/:) ) {
                   13363:             $location = $dir. '/'.$file;
                   13364:         } else {
1.1142    raeburn  13365:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13366:         }
1.59      albertel 13367:     }
1.590     banghart 13368:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13369:     while ($location=~m{/\.\./}) {
                   13370: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13371: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13372: 	} else {
                   13373: 	    $location=~ s{/\.\./}{/}g;
                   13374: 	}
                   13375:     } #remove dir/..
1.590     banghart 13376:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13377:     return $location;
1.46      www      13378: }
1.36      albertel 13379: 
1.46      www      13380: sub hreflocation {
                   13381:     my ($dir,$file)=@_;
1.980     raeburn  13382:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13383: 	$file=filelocation($dir,$file);
1.700     albertel 13384:     } elsif ($file=~m-^/adm/-) {
                   13385: 	$file=~s-^/adm/wrapper/-/-;
                   13386: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13387:     }
                   13388:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13389: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13390:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13391: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13392: 	        {/uploaded/$1/$2/}x;
1.46      www      13393:     }
1.913     albertel 13394:     if ($file=~ m{^/userfiles/}) {
                   13395: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13396:     }
1.462     albertel 13397:     return $file;
1.465     albertel 13398: }
                   13399: 
1.1139    www      13400: 
                   13401: 
                   13402: 
                   13403: 
1.465     albertel 13404: sub current_machine_domains {
1.853     albertel 13405:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13406: }
                   13407: 
                   13408: sub machine_domains {
                   13409:     my ($hostname) = @_;
1.465     albertel 13410:     my @domains;
1.838     albertel 13411:     my %hostname = &all_hostnames();
1.465     albertel 13412:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13413: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13414: 	if ($hostname eq $name) {
1.844     albertel 13415: 	    push(@domains,&host_domain($id));
1.465     albertel 13416: 	}
                   13417:     }
                   13418:     return @domains;
                   13419: }
                   13420: 
                   13421: sub current_machine_ids {
1.853     albertel 13422:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13423: }
                   13424: 
                   13425: sub machine_ids {
                   13426:     my ($hostname) = @_;
                   13427:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13428:     my @ids;
1.888     albertel 13429:     my %name_to_host = &all_names();
1.889     albertel 13430:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13431: 	return @{ $name_to_host{$hostname} };
                   13432:     }
                   13433:     return;
1.31      www      13434: }
                   13435: 
1.824     raeburn  13436: sub additional_machine_domains {
                   13437:     my @domains;
1.1172.2.96  raeburn  13438:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13439:     while( my $line = <$fh>) {
                   13440:         $line =~ s/\s//g;
                   13441:         push(@domains,$line);
                   13442:     }
                   13443:     return @domains;
                   13444: }
                   13445: 
                   13446: sub default_login_domain {
                   13447:     my $domain = $perlvar{'lonDefDomain'};
                   13448:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13449:     foreach my $posdom (&current_machine_domains(),
                   13450:                         &additional_machine_domains()) {
                   13451:         if (lc($posdom) eq lc($testdomain)) {
                   13452:             $domain=$posdom;
                   13453:             last;
                   13454:         }
                   13455:     }
                   13456:     return $domain;
                   13457: }
                   13458: 
1.1172.2.106  raeburn  13459: sub shared_institution {
1.1172.2.118.  .15(raeb 13460:-21):     my ($dom,$lonhost) = @_;
                   13461:-21):     if ($lonhost eq '') {
                   13462:-21):         $lonhost = $perlvar{'lonHostID'};
                   13463:-21):     }
1.1172.2.106  raeburn  13464:     my $same_intdom;
1.1172.2.118.  .15(raeb 13465:-21):     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13466:     if ($hostintdom ne '') {
                   13467:         my %iphost = &get_iphost();
                   13468:         my $primary_id = &domain($dom,'primary');
                   13469:         my $primary_ip = &get_host_ip($primary_id);
                   13470:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13471:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13472:                 my $intdom = &internet_dom($id);
                   13473:                 if ($intdom eq $hostintdom) {
                   13474:                     $same_intdom = 1;
                   13475:                     last;
                   13476:                 }
                   13477:             }
                   13478:         }
                   13479:     }
                   13480:     return $same_intdom;
                   13481: }
                   13482: 
1.1172.2.118.  .3(raebu 13483:20): sub uses_sts {
                   13484:20):     my ($ignore_cache) = @_;
                   13485:20):     my $lonhost = $perlvar{'lonHostID'};
                   13486:20):     my $hostname = &hostname($lonhost);
                   13487:20):     my $sts_on;
                   13488:20):     if ($protocol{$lonhost} eq 'https') {
                   13489:20):         my $cachetime = 12*3600;
                   13490:20):         if (!$ignore_cache) {
                   13491:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13492:20):             if (defined($cached)) {
                   13493:20):                 return $sts_on;
                   13494:20):             }
                   13495:20):         }
          .4(raebu 13496:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13497:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13498:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13499:20):         my $response=$ua->request($request);
          .3(raebu 13500:20):         if ($response->is_success) {
                   13501:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13502:20):             if ($has_sts eq '') {
                   13503:20):                 $sts_on = 0;
                   13504:20):             } else {
                   13505:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13506:20):                     my $maxage = $1;
                   13507:20):                     if ($maxage) {
                   13508:20):                         $sts_on = 1;
                   13509:20):                     } else {
                   13510:20):                         $sts_on = 0;
                   13511:20):                     }
                   13512:20):                 } else {
                   13513:20):                     $sts_on = 0;
                   13514:20):                 }
                   13515:20):             }
                   13516:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13517:20):         }
                   13518:20):     }
                   13519:20):     return;
                   13520:20): }
                   13521:20): 
          .14(raeb 13522:-21): sub get_requestor_ip {
                   13523:-21):     my ($r,$nolookup,$noproxy) = @_;
                   13524:-21):     my $from_ip;
                   13525:-21):     if (ref($r)) {
                   13526:-21):         $from_ip = $r->get_remote_host($nolookup);
                   13527:-21):     } else {
                   13528:-21):         $from_ip = $ENV{'REMOTE_ADDR'};
                   13529:-21):     }
                   13530:-21):     return $from_ip;
                   13531:-21): }
                   13532:-21): 
1.31      www      13533: # ------------------------------------------------------------- Declutters URLs
                   13534: 
                   13535: sub declutter {
                   13536:     my $thisfn=shift;
1.569     albertel 13537:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13538:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13539:         $thisfn=~s{^/home/httpd/html}{};
                   13540:     }
1.31      www      13541:     $thisfn=~s/^\///;
1.697     albertel 13542:     $thisfn=~s|^adm/wrapper/||;
                   13543:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13544:     $thisfn=~s/^res\///;
1.1172    bisitz   13545:     $thisfn=~s/^priv\///;
1.1032    raeburn  13546:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13547:         $thisfn=~s/\?.+$//;
                   13548:     }
1.268     www      13549:     return $thisfn;
                   13550: }
                   13551: 
                   13552: # ------------------------------------------------------------- Clutter up URLs
                   13553: 
                   13554: sub clutter {
                   13555:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13556:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13557: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13558:        $thisfn='/res'.$thisfn; 
                   13559:     }
1.1031    raeburn  13560:     if ($thisfn !~m|^/adm|) {
                   13561: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13562: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13563: 	} else {
                   13564: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13565: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13566: 	    if ($embstyle eq 'ssi'
                   13567: 		|| ($embstyle eq 'hdn')
                   13568: 		|| ($embstyle eq 'rat')
                   13569: 		|| ($embstyle eq 'prv')
                   13570: 		|| ($embstyle eq 'ign')) {
                   13571: 		#do nothing with these
                   13572: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13573: 		|| ($embstyle eq 'emb')
                   13574: 		|| ($embstyle eq 'wrp')) {
                   13575: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13576: 	    } elsif ($embstyle eq 'unk'
                   13577: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13578: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13579: 	    } else {
1.718     www      13580: #		&logthis("Got a blank emb style");
1.695     albertel 13581: 	    }
1.694     albertel 13582: 	}
1.1172.2.118.  .1(raebu 13583:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13584:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13585:     }
1.31      www      13586:     return $thisfn;
1.12      www      13587: }
                   13588: 
1.787     albertel 13589: sub clutter_with_no_wrapper {
                   13590:     my $uri = &clutter(shift);
                   13591:     if ($uri =~ m-^/adm/-) {
                   13592: 	$uri =~ s-^/adm/wrapper/-/-;
                   13593: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13594:     }
                   13595:     return $uri;
                   13596: }
                   13597: 
1.557     albertel 13598: sub freeze_escape {
                   13599:     my ($value)=@_;
                   13600:     if (ref($value)) {
                   13601: 	$value=&nfreeze($value);
                   13602: 	return '__FROZEN__'.&escape($value);
                   13603:     }
                   13604:     return &escape($value);
                   13605: }
                   13606: 
1.11      www      13607: 
1.557     albertel 13608: sub thaw_unescape {
                   13609:     my ($value)=@_;
                   13610:     if ($value =~ /^__FROZEN__/) {
                   13611: 	substr($value,0,10,undef);
                   13612: 	$value=&unescape($value);
                   13613: 	return &thaw($value);
                   13614:     }
                   13615:     return &unescape($value);
                   13616: }
                   13617: 
1.436     albertel 13618: sub correct_line_ends {
                   13619:     my ($result)=@_;
                   13620:     $$result =~s/\r\n/\n/mg;
                   13621:     $$result =~s/\r/\n/mg;
1.415     albertel 13622: }
1.1       albertel 13623: # ================================================================ Main Program
                   13624: 
1.184     www      13625: sub goodbye {
1.204     albertel 13626:    &logthis("Starting Shut down");
1.443     albertel 13627: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13628:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13629: #converted
1.599     albertel 13630: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13631:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13632: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13633: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13634: #1.1 only
1.870     albertel 13635: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13636: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13637: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13638: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13639:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13640:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13641:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13642:    &flushcourselogs();
                   13643:    &logthis("Shutting down");
                   13644: }
                   13645: 
1.852     albertel 13646: sub get_dns {
1.1172.2.17  raeburn  13647:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13648:     if (!$ignore_cache) {
                   13649: 	my ($content,$cached)=
                   13650: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13651: 	if ($cached) {
1.1172.2.17  raeburn  13652: 	    &$func($content,$hashref);
1.869     albertel 13653: 	    return;
                   13654: 	}
                   13655:     }
                   13656: 
                   13657:     my %alldns;
1.1172.2.96  raeburn  13658:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13659:         foreach my $dns (<$config>) {
                   13660: 	    next if ($dns !~ /^\^(\S*)/x);
                   13661:             my $line = $1;
                   13662:             my ($host,$protocol) = split(/:/,$line);
                   13663:             if ($protocol ne 'https') {
                   13664:                 $protocol = 'http';
                   13665:             }
                   13666: 	    $alldns{$host} = $protocol;
1.979     raeburn  13667:         }
1.1172.2.96  raeburn  13668:         close($config);
1.869     albertel 13669:     }
                   13670:     while (%alldns) {
1.1172.2.52  raeburn  13671: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13672: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13673:         $ua->timeout(30);
1.979     raeburn  13674: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13675: 	my $response=$ua->request($request);
1.979     raeburn  13676:         delete($alldns{$dns});
1.852     albertel 13677: 	next if ($response->is_error());
                   13678: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13679:         unless ($nocache) {
1.1172.2.23  raeburn  13680: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13681:         }
                   13682: 	&$func(\@content,$hashref);
1.869     albertel 13683: 	return;
1.852     albertel 13684:     }
1.871     albertel 13685:     my $which = (split('/',$url))[3];
                   13686:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13687:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13688:         my @content = <$config>;
                   13689:         &$func(\@content,$hashref);
                   13690:     }
1.1172.2.17  raeburn  13691:     return;
                   13692: }
                   13693: 
                   13694: # ------------------------------------------------------Get DNS checksums file
                   13695: sub parse_dns_checksums_tab {
                   13696:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13697:     my $lonhost = $perlvar{'lonHostID'};
                   13698:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13699:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13700:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13701:     my $webconfdir = '/etc/httpd/conf';
                   13702:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13703:         $webconfdir = '/etc/apache2';
                   13704:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13705:         if ($1 >= 10) {
                   13706:             $webconfdir = '/etc/apache2';
                   13707:         }
                   13708:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13709:         if ($1 >= 10.0) {
                   13710:             $webconfdir = '/etc/apache2';
                   13711:         }
                   13712:     }
1.1172.2.17  raeburn  13713:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13714:     my (%chksum,%revnum);
                   13715:     if (ref($lines) eq 'ARRAY') {
                   13716:         chomp(@{$lines});
1.1172.2.34  raeburn  13717:         my $version = shift(@{$lines});
                   13718:         if ($version eq $release) {
1.1172.2.17  raeburn  13719:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13720:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13721:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13722:                     if ($webconfdir eq '/etc/apache2') {
                   13723:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13724:                     }
                   13725:                 }
1.1172.2.34  raeburn  13726:                 $chksum{$file} = $shasum;
                   13727:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13728:             }
                   13729:             if (ref($hashref) eq 'HASH') {
                   13730:                 %{$hashref} = (
                   13731:                                 sums     => \%chksum,
                   13732:                                 versions => \%revnum,
                   13733:                               );
                   13734:             }
                   13735:         }
                   13736:     }
1.869     albertel 13737:     return;
1.852     albertel 13738: }
1.1172.2.17  raeburn  13739: 
                   13740: sub fetch_dns_checksums {
                   13741:     my %checksums;
1.1172.2.34  raeburn  13742:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13743:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13744:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13745:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13746:              \%checksums);
                   13747:     return \%checksums;
                   13748: }
                   13749: 
1.327     albertel 13750: # ------------------------------------------------------------ Read domain file
                   13751: {
1.852     albertel 13752:     my $loaded;
1.846     albertel 13753:     my %domain;
                   13754: 
1.852     albertel 13755:     sub parse_domain_tab {
                   13756: 	my ($lines) = @_;
                   13757: 	foreach my $line (@$lines) {
                   13758: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13759: 
1.846     albertel 13760: 	    chomp($line);
1.852     albertel 13761: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13762: 	    my %this_domain;
                   13763: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13764: 			       'lang_def', 'city', 'longi', 'lati',
                   13765: 			       'primary') {
                   13766: 		$this_domain{$field} = shift(@elements);
                   13767: 	    }
                   13768: 	    $domain{$name} = \%this_domain;
1.852     albertel 13769: 	}
                   13770:     }
1.864     albertel 13771: 
                   13772:     sub reset_domain_info {
                   13773: 	undef($loaded);
                   13774: 	undef(%domain);
                   13775:     }
                   13776: 
1.852     albertel 13777:     sub load_domain_tab {
1.1172.2.70  raeburn  13778: 	my ($ignore_cache,$nocache) = @_;
                   13779: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13780: 	my $fh;
1.1172.2.96  raeburn  13781: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13782: 	    my @lines = <$fh>;
                   13783: 	    &parse_domain_tab(\@lines);
1.448     albertel 13784: 	}
1.852     albertel 13785: 	close($fh);
                   13786: 	$loaded = 1;
1.327     albertel 13787:     }
1.846     albertel 13788: 
                   13789:     sub domain {
1.852     albertel 13790: 	&load_domain_tab() if (!$loaded);
                   13791: 
1.846     albertel 13792: 	my ($name,$what) = @_;
                   13793: 	return if ( !exists($domain{$name}) );
                   13794: 
                   13795: 	if (!$what) {
                   13796: 	    return $domain{$name}{'description'};
                   13797: 	}
                   13798: 	return $domain{$name}{$what};
                   13799:     }
1.974     raeburn  13800: 
                   13801:     sub domain_info {
                   13802:         &load_domain_tab() if (!$loaded);
                   13803:         return %domain;
                   13804:     }
                   13805: 
1.327     albertel 13806: }
                   13807: 
                   13808: 
1.1       albertel 13809: # ------------------------------------------------------------- Read hosts file
                   13810: {
1.838     albertel 13811:     my %hostname;
1.844     albertel 13812:     my %hostdom;
1.845     albertel 13813:     my %libserv;
1.852     albertel 13814:     my $loaded;
1.888     albertel 13815:     my %name_to_host;
1.1074    raeburn  13816:     my %internetdom;
1.1107    raeburn  13817:     my %LC_dns_serv;
1.852     albertel 13818: 
                   13819:     sub parse_hosts_tab {
                   13820: 	my ($file) = @_;
                   13821: 	foreach my $configline (@$file) {
                   13822: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13823:             chomp($configline);
                   13824: 	    if ($configline =~ /^\^/) {
                   13825:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13826:                     $LC_dns_serv{$1} = 1;
                   13827:                 }
                   13828:                 next;
                   13829:             }
1.1074    raeburn  13830: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13831: 	    $name=~s/\s//g;
                   13832: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13833:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13834:                     my $curr = $hostname{$id};
                   13835:                     my $skip;
                   13836:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13837:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13838:                             $skip = 1;
                   13839:                         } else {
                   13840:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13841:                         }
                   13842:                     }
                   13843:                     unless ($skip) {
                   13844:                         push(@{$name_to_host{$name}},$id);
                   13845:                     }
                   13846:                 } else {
                   13847:                     push(@{$name_to_host{$name}},$id);
                   13848:                 }
1.852     albertel 13849: 		$hostname{$id}=$name;
                   13850: 		$hostdom{$id}=$domain;
                   13851: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13852:                 if (defined($protocol)) {
                   13853:                     if ($protocol eq 'https') {
                   13854:                         $protocol{$id} = $protocol;
                   13855:                     } else {
                   13856:                         $protocol{$id} = 'http'; 
                   13857:                     }
1.968     raeburn  13858:                 } else {
1.969     raeburn  13859:                     $protocol{$id} = 'http';
1.968     raeburn  13860:                 }
1.1074    raeburn  13861:                 if (defined($intdom)) {
                   13862:                     $internetdom{$id} = $intdom;
                   13863:                 }
1.852     albertel 13864: 	    }
                   13865: 	}
                   13866:     }
1.864     albertel 13867:     
                   13868:     sub reset_hosts_info {
1.897     albertel 13869: 	&purge_remembered();
1.864     albertel 13870: 	&reset_domain_info();
                   13871: 	&reset_hosts_ip_info();
1.892     albertel 13872: 	undef(%name_to_host);
1.864     albertel 13873: 	undef(%hostname);
                   13874: 	undef(%hostdom);
                   13875: 	undef(%libserv);
                   13876: 	undef($loaded);
                   13877:     }
1.1       albertel 13878: 
1.852     albertel 13879:     sub load_hosts_tab {
1.1172.2.70  raeburn  13880: 	my ($ignore_cache,$nocache) = @_;
                   13881: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13882: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13883: 	my @config = <$config>;
                   13884: 	&parse_hosts_tab(\@config);
                   13885: 	close($config);
                   13886: 	$loaded=1;
1.1       albertel 13887:     }
1.852     albertel 13888: 
1.838     albertel 13889:     sub hostname {
1.852     albertel 13890: 	&load_hosts_tab() if (!$loaded);
                   13891: 
1.838     albertel 13892: 	my ($lonid) = @_;
                   13893: 	return $hostname{$lonid};
                   13894:     }
1.845     albertel 13895: 
1.838     albertel 13896:     sub all_hostnames {
1.852     albertel 13897: 	&load_hosts_tab() if (!$loaded);
                   13898: 
1.838     albertel 13899: 	return %hostname;
                   13900:     }
1.845     albertel 13901: 
1.888     albertel 13902:     sub all_names {
1.1172.2.70  raeburn  13903:         my ($ignore_cache,$nocache) = @_;
                   13904: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13905: 
                   13906: 	return %name_to_host;
                   13907:     }
                   13908: 
1.974     raeburn  13909:     sub all_host_domain {
                   13910:         &load_hosts_tab() if (!$loaded);
                   13911:         return %hostdom;
                   13912:     }
                   13913: 
1.845     albertel 13914:     sub is_library {
1.852     albertel 13915: 	&load_hosts_tab() if (!$loaded);
                   13916: 
1.845     albertel 13917: 	return exists($libserv{$_[0]});
                   13918:     }
                   13919: 
                   13920:     sub all_library {
1.852     albertel 13921: 	&load_hosts_tab() if (!$loaded);
                   13922: 
1.845     albertel 13923: 	return %libserv;
                   13924:     }
                   13925: 
1.1062    droeschl 13926:     sub unique_library {
                   13927: 	#2x reverse removes all hostnames that appear more than once
                   13928:         my %unique = reverse &all_library();
                   13929:         return reverse %unique;
                   13930:     }
                   13931: 
1.841     albertel 13932:     sub get_servers {
1.852     albertel 13933: 	&load_hosts_tab() if (!$loaded);
                   13934: 
1.841     albertel 13935: 	my ($domain,$type) = @_;
                   13936: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13937: 	                                          : %hostname;
                   13938: 	my %result;
1.842     albertel 13939: 	if (ref($domain) eq 'ARRAY') {
                   13940: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13941: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13942: 		    $result{$host} = $hostname;
                   13943: 		}
                   13944: 	    }
                   13945: 	} else {
                   13946: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13947: 		if ($hostdom{$host} eq $domain) {
                   13948: 		    $result{$host} = $hostname;
                   13949: 		}
1.841     albertel 13950: 	    }
                   13951: 	}
                   13952: 	return %result;
                   13953:     }
1.845     albertel 13954: 
1.1062    droeschl 13955:     sub get_unique_servers {
                   13956:         my %unique = reverse &get_servers(@_);
                   13957: 	return reverse %unique;
                   13958:     }
                   13959: 
1.844     albertel 13960:     sub host_domain {
1.852     albertel 13961: 	&load_hosts_tab() if (!$loaded);
                   13962: 
1.844     albertel 13963: 	my ($lonid) = @_;
                   13964: 	return $hostdom{$lonid};
                   13965:     }
                   13966: 
1.841     albertel 13967:     sub all_domains {
1.852     albertel 13968: 	&load_hosts_tab() if (!$loaded);
                   13969: 
1.841     albertel 13970: 	my %seen;
                   13971: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13972: 	return @uniq;
                   13973:     }
1.1074    raeburn  13974: 
                   13975:     sub internet_dom {
                   13976:         &load_hosts_tab() if (!$loaded);
                   13977: 
                   13978:         my ($lonid) = @_;
                   13979:         return $internetdom{$lonid};
                   13980:     }
1.1107    raeburn  13981: 
                   13982:     sub is_LC_dns {
                   13983:         &load_hosts_tab() if (!$loaded);
                   13984: 
                   13985:         my ($hostname) = @_;
                   13986:         return exists($LC_dns_serv{$hostname});
                   13987:     }
                   13988: 
1.1       albertel 13989: }
                   13990: 
1.847     albertel 13991: { 
                   13992:     my %iphost;
1.856     albertel 13993:     my %name_to_ip;
                   13994:     my %lonid_to_ip;
1.869     albertel 13995: 
1.847     albertel 13996:     sub get_hosts_from_ip {
                   13997: 	my ($ip) = @_;
                   13998: 	my %iphosts = &get_iphost();
                   13999: 	if (ref($iphosts{$ip})) {
                   14000: 	    return @{$iphosts{$ip}};
                   14001: 	}
                   14002: 	return;
1.839     albertel 14003:     }
1.864     albertel 14004:     
                   14005:     sub reset_hosts_ip_info {
                   14006: 	undef(%iphost);
                   14007: 	undef(%name_to_ip);
                   14008: 	undef(%lonid_to_ip);
                   14009:     }
1.856     albertel 14010: 
                   14011:     sub get_host_ip {
                   14012: 	my ($lonid) = @_;
                   14013: 	if (exists($lonid_to_ip{$lonid})) {
                   14014: 	    return $lonid_to_ip{$lonid};
                   14015: 	}
                   14016: 	my $name=&hostname($lonid);
                   14017:    	my $ip = gethostbyname($name);
                   14018: 	return if (!$ip || length($ip) ne 4);
                   14019: 	$ip=inet_ntoa($ip);
                   14020: 	$name_to_ip{$name}   = $ip;
                   14021: 	$lonid_to_ip{$lonid} = $ip;
                   14022: 	return $ip;
                   14023:     }
1.847     albertel 14024:     
                   14025:     sub get_iphost {
1.1172.2.70  raeburn  14026: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14027: 
1.869     albertel 14028: 	if (!$ignore_cache) {
                   14029: 	    if (%iphost) {
                   14030: 		return %iphost;
                   14031: 	    }
                   14032: 	    my ($ip_info,$cached)=
                   14033: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14034: 	    if ($cached) {
                   14035: 		%iphost      = %{$ip_info->[0]};
                   14036: 		%name_to_ip  = %{$ip_info->[1]};
                   14037: 		%lonid_to_ip = %{$ip_info->[2]};
                   14038: 		return %iphost;
                   14039: 	    }
                   14040: 	}
1.894     albertel 14041: 
                   14042: 	# get yesterday's info for fallback
                   14043: 	my %old_name_to_ip;
                   14044: 	my ($ip_info,$cached)=
                   14045: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14046: 	if ($cached) {
                   14047: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14048: 	}
                   14049: 
1.1172.2.70  raeburn  14050: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14051: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14052: 	    my $ip;
                   14053: 	    if (!exists($name_to_ip{$name})) {
                   14054: 		$ip = gethostbyname($name);
                   14055: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14056: 		    if (defined($old_name_to_ip{$name})) {
                   14057: 			$ip = $old_name_to_ip{$name};
                   14058: 			&logthis("Can't find $name defaulting to old $ip");
                   14059: 		    } else {
                   14060: 			&logthis("Name $name no IP found");
                   14061: 			next;
                   14062: 		    }
                   14063: 		} else {
                   14064: 		    $ip=inet_ntoa($ip);
1.847     albertel 14065: 		}
                   14066: 		$name_to_ip{$name} = $ip;
                   14067: 	    } else {
                   14068: 		$ip = $name_to_ip{$name};
1.653     albertel 14069: 	    }
1.888     albertel 14070: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14071: 		$lonid_to_ip{$id} = $ip;
                   14072: 	    }
                   14073: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14074: 	}
1.1172.2.70  raeburn  14075:         unless ($nocache) {
                   14076: 	    &do_cache_new('iphost','iphost',
                   14077: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14078: 		          48*60*60);
                   14079:         }
1.869     albertel 14080: 
1.847     albertel 14081: 	return %iphost;
1.598     albertel 14082:     }
                   14083: 
1.992     raeburn  14084:     #
                   14085:     #  Given a DNS returns the loncapa host name for that DNS 
                   14086:     # 
                   14087:     sub host_from_dns {
                   14088:         my ($dns) = @_;
                   14089:         my @hosts;
                   14090:         my $ip;
                   14091: 
1.993     raeburn  14092:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14093:             $ip = $name_to_ip{$dns};
                   14094:         }
                   14095:         if (!$ip) {
                   14096:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14097:             if (length($ip) == 4) { 
                   14098: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14099:             }
                   14100:         }
                   14101:         if ($ip) {
                   14102: 	    @hosts = get_hosts_from_ip($ip);
                   14103: 	    return $hosts[0];
                   14104:         }
                   14105:         return undef;
1.986     foxr     14106:     }
1.992     raeburn  14107: 
1.1074    raeburn  14108:     sub get_internet_names {
                   14109:         my ($lonid) = @_;
                   14110:         return if ($lonid eq '');
                   14111:         my ($idnref,$cached)=
                   14112:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14113:         if ($cached) {
                   14114:             return $idnref;
                   14115:         }
                   14116:         my $ip = &get_host_ip($lonid);
                   14117:         my @hosts = &get_hosts_from_ip($ip);
                   14118:         my %iphost = &get_iphost();
                   14119:         my (@idns,%seen);
                   14120:         foreach my $id (@hosts) {
                   14121:             my $dom = &host_domain($id);
                   14122:             my $prim_id = &domain($dom,'primary');
                   14123:             my $prim_ip = &get_host_ip($prim_id);
                   14124:             next if ($seen{$prim_ip});
                   14125:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14126:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14127:                     my $intdom = &internet_dom($id);
                   14128:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14129:                         push(@idns,$intdom);
                   14130:                     }
                   14131:                 }
                   14132:             }
                   14133:             $seen{$prim_ip} = 1;
                   14134:         }
1.1172.2.23  raeburn  14135:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14136:     }
                   14137: 
1.986     foxr     14138: }
                   14139: 
1.1079    raeburn  14140: sub all_loncaparevs {
1.1172.2.39  raeburn  14141:     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  14142: }
                   14143: 
1.1172.2.27  raeburn  14144: # ------------------------------------------------------- Read loncaparev table
                   14145: {
                   14146:     sub load_loncaparevs {
                   14147:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14148:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14149:                 while (my $configline=<$config>) {
                   14150:                     chomp($configline);
                   14151:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14152:                     $loncaparevs{$hostid}=$loncaparev;
                   14153:                 }
                   14154:                 close($config);
                   14155:             }
                   14156:         }
                   14157:     }
                   14158: }
                   14159: 
                   14160: # ----------------------------------------------------- Read serverhostID table
                   14161: {
                   14162:     sub load_serverhomeIDs {
                   14163:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14164:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14165:                 while (my $configline=<$config>) {
                   14166:                     chomp($configline);
                   14167:                     my ($name,$id)=split(/:/,$configline);
                   14168:                     $serverhomeIDs{$name}=$id;
                   14169:                 }
                   14170:                 close($config);
                   14171:             }
                   14172:         }
                   14173:     }
                   14174: }
                   14175: 
                   14176: 
1.862     albertel 14177: BEGIN {
                   14178: 
                   14179: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14180:     unless ($readit) {
                   14181: {
                   14182:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14183:     %perlvar = (%perlvar,%{$configvars});
                   14184: }
                   14185: 
                   14186: 
1.1       albertel 14187: # ------------------------------------------------------ Read spare server file
                   14188: {
1.1172.2.96  raeburn  14189:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14190: 
                   14191:     while (my $configline=<$config>) {
                   14192:        chomp($configline);
1.284     matthew  14193:        if ($configline) {
1.784     albertel 14194: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14195: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14196: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14197:        }
                   14198:     }
1.448     albertel 14199:     close($config);
1.1       albertel 14200: }
1.11      www      14201: # ------------------------------------------------------------ Read permissions
                   14202: {
1.1172.2.96  raeburn  14203:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14204: 
                   14205:     while (my $configline=<$config>) {
1.448     albertel 14206: 	chomp($configline);
                   14207: 	if ($configline) {
                   14208: 	    my ($role,$perm)=split(/ /,$configline);
                   14209: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14210: 	}
1.11      www      14211:     }
1.448     albertel 14212:     close($config);
1.11      www      14213: }
                   14214: 
                   14215: # -------------------------------------------- Read plain texts for permissions
                   14216: {
1.1172.2.96  raeburn  14217:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14218: 
                   14219:     while (my $configline=<$config>) {
1.448     albertel 14220: 	chomp($configline);
                   14221: 	if ($configline) {
1.742     raeburn  14222: 	    my ($short,@plain)=split(/:/,$configline);
                   14223:             %{$prp{$short}} = ();
                   14224: 	    if (@plain > 0) {
                   14225:                 $prp{$short}{'std'} = $plain[0];
                   14226:                 for (my $i=1; $i<@plain; $i++) {
                   14227:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14228:                 }
                   14229:             }
1.448     albertel 14230: 	}
1.135     www      14231:     }
1.448     albertel 14232:     close($config);
1.135     www      14233: }
                   14234: 
                   14235: # ---------------------------------------------------------- Read package table
                   14236: {
1.1172.2.96  raeburn  14237:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14238: 
                   14239:     while (my $configline=<$config>) {
1.483     albertel 14240: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14241: 	chomp($configline);
                   14242: 	my ($short,$plain)=split(/:/,$configline);
                   14243: 	my ($pack,$name)=split(/\&/,$short);
                   14244: 	if ($plain ne '') {
                   14245: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14246: 	    $packagetab{$short}=$plain; 
                   14247: 	}
1.11      www      14248:     }
1.448     albertel 14249:     close($config);
1.329     matthew  14250: }
                   14251: 
1.1172.2.27  raeburn  14252: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14253: 
1.1172.2.27  raeburn  14254: &load_loncaparevs();
                   14255: 
                   14256: # ------------------------------------------------------- Read serverhostID table
                   14257: 
                   14258: &load_serverhomeIDs();
1.1074    raeburn  14259: 
1.1172.2.27  raeburn  14260: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14261: {
                   14262:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14263:     if (-e $file) {
                   14264:         my $parser = HTML::LCParser->new($file);
                   14265:         while (my $token = $parser->get_token()) {
                   14266:             if ($token->[0] eq 'S') {
                   14267:                 my $item = $token->[1];
                   14268:                 my $name = $token->[2]{'name'};
                   14269:                 my $value = $token->[2]{'value'};
                   14270:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14271:                     my $release = $parser->get_text();
                   14272:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14273:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14274:                 }
                   14275:             }
                   14276:         }
                   14277:     }
1.1073    raeburn  14278: }
                   14279: 
1.1138    raeburn  14280: # ---------------------------------------------------------- Read managers table
                   14281: {
                   14282:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14283:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14284:             while (my $configline=<$config>) {
                   14285:                 chomp($configline);
                   14286:                 next if ($configline =~ /^\#/);
                   14287:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14288:                     $managerstab{$configline} = 1;
                   14289:                 }
                   14290:             }
                   14291:             close($config);
                   14292:         }
                   14293:     }
                   14294: }
                   14295: 
1.329     matthew  14296: # ------------- set up temporary directory
                   14297: {
1.1117    foxr     14298:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14299: 
1.11      www      14300: }
                   14301: 
1.1172.2.104  raeburn  14302: # ------------- set default texengine (domain default overrides this)
                   14303: {
                   14304:     $deftex = LONCAPA::texengine();
                   14305: }
                   14306: 
1.1172.2.114  raeburn  14307: # ------------- set default minimum length for passwords for internal auth users
                   14308: {
                   14309:     $passwdmin = LONCAPA::passwd_min();
                   14310: }
                   14311: 
1.794     albertel 14312: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14313: 				'compress_threshold'=> 20_000,
                   14314:  			        });
1.185     www      14315: 
1.281     www      14316: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14317: $dumpcount=0;
1.958     www      14318: $locknum=0;
1.22      www      14319: 
1.163     harris41 14320: &logtouch();
1.672     albertel 14321: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14322: $readit=1;
1.564     albertel 14323:     {
                   14324: 	use integer;
                   14325: 	my $test=(2**32)+1;
1.568     albertel 14326: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14327: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14328:     }
1.195     www      14329: }
1.1       albertel 14330: }
1.179     www      14331: 
1.1       albertel 14332: 1;
1.191     harris41 14333: __END__
                   14334: 
1.243     albertel 14335: =pod
                   14336: 
1.191     harris41 14337: =head1 NAME
                   14338: 
1.243     albertel 14339: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14340: 
                   14341: =head1 SYNOPSIS
                   14342: 
1.243     albertel 14343: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14344: 
                   14345:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14346: 
1.243     albertel 14347: Common parameters:
                   14348: 
                   14349: =over 4
                   14350: 
                   14351: =item *
                   14352: 
                   14353: $uname : an internal username (if $cname expecting a course Id specifically)
                   14354: 
                   14355: =item *
                   14356: 
                   14357: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14358: 
                   14359: =item *
                   14360: 
                   14361: $symb : a resource instance identifier
                   14362: 
                   14363: =item *
                   14364: 
                   14365: $namespace : the name of a .db file that contains the data needed or
                   14366: being set.
                   14367: 
                   14368: =back
                   14369: 
1.394     bowersj2 14370: =head1 OVERVIEW
1.191     harris41 14371: 
1.394     bowersj2 14372: lonnet provides subroutines which interact with the
                   14373: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14374: about classes, users, and resources.
1.243     albertel 14375: 
                   14376: For many of these objects you can also use this to store data about
                   14377: them or modify them in various ways.
1.191     harris41 14378: 
1.394     bowersj2 14379: =head2 Symbs
1.191     harris41 14380: 
1.394     bowersj2 14381: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14382: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14383: map, the resource number of the resource in the map, and the URL of
                   14384: the resource itself. The latter is somewhat redundant, but might help
                   14385: if maps change.
                   14386: 
                   14387: An example is
                   14388: 
                   14389:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14390: 
                   14391: The respective map entry is
                   14392: 
                   14393:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14394:   title="Problem 2">
                   14395:  </resource>
                   14396: 
                   14397: Symbs are used by the random number generator, as well as to store and
                   14398: restore data specific to a certain instance of for example a problem.
                   14399: 
                   14400: =head2 Storing And Retrieving Data
                   14401: 
                   14402: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14403: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14404: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14405: is is the non-critical message twin of cstore. These functions are for
                   14406: handlers to store a perl hash to a user's permanent data space in an
                   14407: easy manner, and to retrieve it again on another call. It is expected
                   14408: that a handler would use this once at the beginning to retrieve data,
                   14409: and then again once at the end to send only the new data back.
                   14410: 
                   14411: The data is stored in the user's data directory on the user's
                   14412: homeserver under the ID of the course.
                   14413: 
                   14414: The hash that is returned by restore will have all of the previous
                   14415: value for all of the elements of the hash.
                   14416: 
                   14417: Example:
                   14418: 
                   14419:  #creating a hash
                   14420:  my %hash;
                   14421:  $hash{'foo'}='bar';
                   14422: 
                   14423:  #storing it
                   14424:  &Apache::lonnet::cstore(\%hash);
                   14425: 
                   14426:  #changing a value
                   14427:  $hash{'foo'}='notbar';
                   14428: 
                   14429:  #adding a new value
                   14430:  $hash{'bar'}='foo';
                   14431:  &Apache::lonnet::cstore(\%hash);
                   14432: 
                   14433:  #retrieving the hash
                   14434:  my %history=&Apache::lonnet::restore();
                   14435: 
                   14436:  #print the hash
                   14437:  foreach my $key (sort(keys(%history))) {
                   14438:    print("\%history{$key} = $history{$key}");
                   14439:  }
                   14440: 
                   14441: Will print out:
1.191     harris41 14442: 
1.394     bowersj2 14443:  %history{1:foo} = bar
                   14444:  %history{1:keys} = foo:timestamp
                   14445:  %history{1:timestamp} = 990455579
                   14446:  %history{2:bar} = foo
                   14447:  %history{2:foo} = notbar
                   14448:  %history{2:keys} = foo:bar:timestamp
                   14449:  %history{2:timestamp} = 990455580
                   14450:  %history{bar} = foo
                   14451:  %history{foo} = notbar
                   14452:  %history{timestamp} = 990455580
                   14453:  %history{version} = 2
                   14454: 
                   14455: Note that the special hash entries C<keys>, C<version> and
                   14456: C<timestamp> were added to the hash. C<version> will be equal to the
                   14457: total number of versions of the data that have been stored. The
                   14458: C<timestamp> attribute will be the UNIX time the hash was
                   14459: stored. C<keys> is available in every historical section to list which
                   14460: keys were added or changed at a specific historical revision of a
                   14461: hash.
                   14462: 
                   14463: B<Warning>: do not store the hash that restore returns directly. This
                   14464: will cause a mess since it will restore the historical keys as if the
                   14465: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14466: 
1.394     bowersj2 14467: Calling convention:
1.191     harris41 14468: 
1.1172.2.27  raeburn  14469:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14470:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14471: 
1.394     bowersj2 14472: For more detailed information, see lonnet specific documentation.
1.191     harris41 14473: 
1.394     bowersj2 14474: =head1 RETURN MESSAGES
1.191     harris41 14475: 
1.394     bowersj2 14476: =over 4
1.191     harris41 14477: 
1.394     bowersj2 14478: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14479: 
1.394     bowersj2 14480: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14481: when the connection is brought back up
1.191     harris41 14482: 
1.394     bowersj2 14483: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14484: for later delivery
1.191     harris41 14485: 
1.967     bisitz   14486: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14487: 
1.394     bowersj2 14488: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14489: that was requested
1.191     harris41 14490: 
1.243     albertel 14491: =back
1.191     harris41 14492: 
1.243     albertel 14493: =head1 PUBLIC SUBROUTINES
1.191     harris41 14494: 
1.243     albertel 14495: =head2 Session Environment Functions
1.191     harris41 14496: 
1.243     albertel 14497: =over 4
1.191     harris41 14498: 
1.394     bowersj2 14499: =item * 
                   14500: X<appenv()>
1.949     raeburn  14501: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14502: the user envirnoment file, and will be restored for each access this
1.620     albertel 14503: user makes during this session, also modifies the %env for the current
1.949     raeburn  14504: process. Optional rolesarrayref - if defined contains a reference to an array
                   14505: of roles which are exempt from the restriction on modifying user.role entries 
                   14506: in the user's environment.db and in %env.    
1.191     harris41 14507: 
                   14508: =item *
1.394     bowersj2 14509: X<delenv()>
1.987     raeburn  14510: B<delenv($delthis,$regexp)>: removes all items from the session
                   14511: environment file that begin with $delthis. If the 
                   14512: optional second arg - $regexp - is true, $delthis is treated as a 
                   14513: regular expression, otherwise \Q$delthis\E is used. 
                   14514: The values are also deleted from the current processes %env.
1.191     harris41 14515: 
1.795     albertel 14516: =item * get_env_multiple($name) 
                   14517: 
                   14518: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14519: values may be defined and end up as an array ref.
                   14520: 
                   14521: returns an array of values
                   14522: 
1.243     albertel 14523: =back
                   14524: 
                   14525: =head2 User Information
1.191     harris41 14526: 
1.243     albertel 14527: =over 4
1.191     harris41 14528: 
                   14529: =item *
1.394     bowersj2 14530: X<queryauthenticate()>
                   14531: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14532: authentication scheme
                   14533: 
                   14534: =item *
1.394     bowersj2 14535: X<authenticate()>
1.1073    raeburn  14536: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14537: authenticate user from domain's lib servers (first use the current
                   14538: one). C<$upass> should be the users password.
1.1073    raeburn  14539: $checkdefauth is optional (value is 1 if a check should be made to
                   14540:    authenticate user using default authentication method, and allow
                   14541:    account creation if username does not have account in the domain).
                   14542: $clientcancheckhost is optional (value is 1 if checking whether the
                   14543:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14544: 
                   14545: =item *
1.394     bowersj2 14546: X<homeserver()>
                   14547: B<homeserver($uname,$udom)>: find the server which has
                   14548: the user's directory and files (there must be only one), this caches
                   14549: the answer, and also caches if there is a borken connection.
1.191     harris41 14550: 
                   14551: =item *
1.394     bowersj2 14552: X<idget()>
                   14553: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14554: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14555: username, and only 1 username per ID in a specific domain) (returns
                   14556: hash: id=>name,id=>name)
1.191     harris41 14557: 
                   14558: =item *
1.394     bowersj2 14559: X<idrget()>
                   14560: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14561: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14562: 
                   14563: =item *
1.394     bowersj2 14564: X<idput()>
                   14565: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14566: 
                   14567: =item *
1.394     bowersj2 14568: X<rolesinit()>
1.1169    droeschl 14569: B<rolesinit($udom,$username)>: get user privileges.
                   14570: returns user role, first access and timer interval hashes
1.243     albertel 14571: 
                   14572: =item *
1.1171    droeschl 14573: X<privileged()>
                   14574: B<privileged($username,$domain)>: returns a true if user has a
                   14575: privileged and active role (i.e. su or dc), false otherwise.
                   14576: 
                   14577: =item *
1.551     albertel 14578: X<getsection()>
                   14579: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14580: course $cname, return section name/number or '' for "not in course"
                   14581: and '-1' for "no section"
                   14582: 
                   14583: =item *
1.394     bowersj2 14584: X<userenvironment()>
                   14585: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14586: passed in @what from the requested user's environment, returns a hash
                   14587: 
1.858     raeburn  14588: =item * 
                   14589: X<userlog_query()>
1.859     albertel 14590: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14591: activity.log file. %filters defines filters applied when parsing the
                   14592: log file. These can be start or end timestamps, or the type of action
                   14593: - log to look for Login or Logout events, check for Checkin or
                   14594: Checkout, role for role selection. The response is in the form
                   14595: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14596: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14597: 
1.243     albertel 14598: =back
                   14599: 
                   14600: =head2 User Roles
                   14601: 
                   14602: =over 4
                   14603: 
                   14604: =item *
                   14605: 
1.1172.2.65  raeburn  14606: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14607: returns codes for allowed actions.
                   14608: 
                   14609: The first argument is required, all others are optional.
                   14610: 
                   14611: $priv is the privilege being checked.
                   14612: $uri contains additional information about what is being checked for access (e.g.,
                   14613: URL, course ID etc.).
                   14614: $symb is the unique resource instance identifier in a course; if needed,
                   14615: but not provided, it will be retrieved via a call to &symbread().
                   14616: $role is the role for which a priv is being checked (only used if priv is evb).
                   14617: $clientip is the user's IP address (only used when checking for access to portfolio
                   14618: files).
                   14619: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14620: prevents recursive calls to &allowed.
                   14621: 
1.243     albertel 14622:  F: full access
                   14623:  U,I,K: authentication modes (cxx only)
                   14624:  '': forbidden
                   14625:  1: user needs to choose course
                   14626:  2: browse allowed
1.766     albertel 14627:  A: passphrase authentication needed
1.1172.2.65  raeburn  14628:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14629: 
                   14630: =item *
                   14631: 
1.1172.2.13  raeburn  14632: constructaccess($url,$setpriv) : check for access to construction space URL
                   14633: 
                   14634: See if the owner domain and name in the URL match those in the
                   14635: expected environment.  If so, return three element list
                   14636: ($ownername,$ownerdomain,$ownerhome).
                   14637: 
                   14638: Otherwise return the null string.
                   14639: 
                   14640: If second argument 'setpriv' is true, it assigns the privileges,
                   14641: and returns the same three element list, unless the owner has
                   14642: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14643: in which case the null string is returned.
                   14644: 
                   14645: =item *
                   14646: 
1.1172.2.84  raeburn  14647: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14648: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14649: for system, domain, and course level. $uname and $udom are optional (current
                   14650: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14651: 
                   14652: =item *
                   14653: 
1.988     raeburn  14654: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14655: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14656: $type is Course (default) or Community.
1.988     raeburn  14657: If $forcedefault evaluates to true, text returned will be default 
                   14658: text for $type. Otherwise, if this is a course, the text returned 
                   14659: will be a custom name for the role (if defined in the course's 
                   14660: environment).  If no custom name is defined the default is returned.
                   14661:    
1.832     raeburn  14662: =item *
                   14663: 
1.1172.2.23  raeburn  14664: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14665: All arguments are optional. Returns a hash of a roles, either for
                   14666: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14667: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14668: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14669: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14670: For each key, value is set to colon-separated start and end times for
                   14671: the role.  If no username and domain are specified, will default to
1.934     raeburn  14672: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14673: of role statuses (active, future or previous), roles 
                   14674: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14675: to restrict the list of roles reported. If no array ref is 
                   14676: provided for types, will default to return only active roles.
1.834     albertel 14677: 
1.1172.2.13  raeburn  14678: =item *
                   14679: 
                   14680: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14681: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14682: 
                   14683: Additional optional arguments are: $type (if role checking is to be restricted
                   14684: to certain user status types -- previous (expired roles), active (currently
                   14685: available roles) or future (roles available in the future), and
                   14686: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14687: have active Domain Coordinator role in course's domain or in additional
                   14688: domains (specified in 'Domains to check for privileged users' in course
                   14689: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14690: 
                   14691: =item *
                   14692: 
                   14693: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14694: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14695: $possdomains and $possroles are optional array refs -- to domains to check and
                   14696: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14697: users' roles.db to check for a dc or su role in any domain. This can be
                   14698: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14699: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14700: this then allows &privileged_by_domain() to be used, which caches the identity
                   14701: of privileged users, eliminating the need for repeated calls to &dump().
                   14702: 
                   14703: =item *
                   14704: 
                   14705: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14706: where the outer hash keys are domains specified in the $possdomains array ref,
                   14707: next inner hash keys are privileged roles specified in the $roles array ref,
                   14708: and the innermost hash contains key = value pairs for username:domain = end:start
                   14709: for active or future "privileged" users with that role in that domain. To avoid
                   14710: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14711: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14712: 
1.243     albertel 14713: =back
                   14714: 
                   14715: =head2 User Modification
                   14716: 
                   14717: =over 4
                   14718: 
                   14719: =item *
                   14720: 
1.957     raeburn  14721: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14722: user for the level given by URL.  Optional start and end dates (leave empty
                   14723: string or zero for "no date")
1.191     harris41 14724: 
                   14725: =item *
                   14726: 
1.243     albertel 14727: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14728: change a users, password, possible return values are: ok,
                   14729: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14730: refused
1.191     harris41 14731: 
                   14732: =item *
                   14733: 
1.243     albertel 14734: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14735: 
                   14736: =item *
                   14737: 
1.1058    raeburn  14738: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14739:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14740: 
                   14741: will update user information (firstname,middlename,lastname,generation,
                   14742: permanentemail), and if forceid is true, student/employee ID also.
                   14743: A user's institutional affiliation(s) can also be updated.
                   14744: User information fields will not be overwritten with empty entries 
                   14745: unless the field is included in the $candelete array reference.
                   14746: This array is included when a single user is modified via "Manage Users",
                   14747: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14748: 
                   14749: =item *
                   14750: 
1.286     matthew  14751: modifystudent
                   14752: 
1.957     raeburn  14753: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14754: The course id is resolved based on the current user's environment.  
                   14755: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14756: associated with a course.
                   14757: 
1.297     matthew  14758: This call is essentially a wrapper for lonnet::modifyuser and
                   14759: lonnet::modify_student_enrollment
1.286     matthew  14760: 
                   14761: Inputs: 
                   14762: 
                   14763: =over 4
                   14764: 
1.957     raeburn  14765: =item B<$udom> Student's loncapa domain
1.286     matthew  14766: 
1.957     raeburn  14767: =item B<$uname> Student's loncapa login name
1.286     matthew  14768: 
1.964     bisitz   14769: =item B<$uid> Student/Employee ID
1.286     matthew  14770: 
1.957     raeburn  14771: =item B<$umode> Student's authentication mode
1.286     matthew  14772: 
1.957     raeburn  14773: =item B<$upass> Student's password
1.286     matthew  14774: 
1.957     raeburn  14775: =item B<$first> Student's first name
1.286     matthew  14776: 
1.957     raeburn  14777: =item B<$middle> Student's middle name
1.286     matthew  14778: 
1.957     raeburn  14779: =item B<$last> Student's last name
1.286     matthew  14780: 
1.957     raeburn  14781: =item B<$gene> Student's generation
1.286     matthew  14782: 
1.957     raeburn  14783: =item B<$usec> Student's section in course
1.286     matthew  14784: 
                   14785: =item B<$end> Unix time of the roles expiration
                   14786: 
                   14787: =item B<$start> Unix time of the roles start date
                   14788: 
                   14789: =item B<$forceid> If defined, allow $uid to be changed
                   14790: 
                   14791: =item B<$desiredhome> server to use as home server for student
                   14792: 
1.957     raeburn  14793: =item B<$email> Student's permanent e-mail address
                   14794: 
                   14795: =item B<$type> Type of enrollment (auto or manual)
                   14796: 
1.963     raeburn  14797: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14798: 
                   14799: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14800: 
1.963     raeburn  14801: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14802: 
1.963     raeburn  14803: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14804: 
1.1172.2.19  raeburn  14805: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14806: 
                   14807: =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  14808: 
1.286     matthew  14809: =back
1.297     matthew  14810: 
                   14811: =item *
                   14812: 
                   14813: modify_student_enrollment
                   14814: 
1.1172.2.31  raeburn  14815: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14816: 'role.request.course' must be defined for this function to proceed.
                   14817: 
                   14818: Inputs:
                   14819: 
                   14820: =over 4
                   14821: 
1.1172.2.31  raeburn  14822: =item $udom, student's domain
1.297     matthew  14823: 
1.1172.2.31  raeburn  14824: =item $uname, student's name
1.297     matthew  14825: 
1.1172.2.31  raeburn  14826: =item $uid, student's user id
1.297     matthew  14827: 
1.1172.2.31  raeburn  14828: =item $first, student's first name
1.297     matthew  14829: 
                   14830: =item $middle
                   14831: 
                   14832: =item $last
                   14833: 
                   14834: =item $gene
                   14835: 
                   14836: =item $usec
                   14837: 
                   14838: =item $end
                   14839: 
                   14840: =item $start
                   14841: 
1.957     raeburn  14842: =item $type
                   14843: 
                   14844: =item $locktype
                   14845: 
                   14846: =item $cid
                   14847: 
                   14848: =item $selfenroll
                   14849: 
                   14850: =item $context
                   14851: 
1.1172.2.19  raeburn  14852: =item $credits, number of credits student will earn from this class
                   14853: 
1.1172.2.76  raeburn  14854: =item $instsec, institutional course section code for student
                   14855: 
1.297     matthew  14856: =back
                   14857: 
1.191     harris41 14858: 
                   14859: =item *
                   14860: 
1.243     albertel 14861: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14862: custom role; give a custom role to a user for the level given by URL.  Specify
                   14863: name and domain of role author, and role name
1.191     harris41 14864: 
                   14865: =item *
                   14866: 
1.243     albertel 14867: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14868: 
                   14869: =item *
                   14870: 
1.243     albertel 14871: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14872: 
                   14873: =back
                   14874: 
                   14875: =head2 Course Infomation
                   14876: 
                   14877: =over 4
1.191     harris41 14878: 
                   14879: =item *
                   14880: 
1.1118    foxr     14881: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14882: specified course id, including all environment settings for the
                   14883: course, the description of the course will be in the hash under the
                   14884: key 'description'
1.191     harris41 14885: 
1.1118    foxr     14886: $options is an optional parameter that if supplied is a hash reference that controls
                   14887: what how this function works.  It has the following key/values:
                   14888: 
                   14889: =over 4
                   14890: 
                   14891: =item freshen_cache
                   14892: 
                   14893: If defined, and the environment cache for the course is valid, it is 
                   14894: returned in the returned hash.
                   14895: 
                   14896: =item one_time
                   14897: 
                   14898: If defined, the last cache time is set to _now_
                   14899: 
                   14900: =item user
                   14901: 
                   14902: If defined, the supplied username is used instead of the current user.
                   14903: 
                   14904: 
                   14905: =back
                   14906: 
1.191     harris41 14907: =item *
                   14908: 
1.624     albertel 14909: resdata($name,$domain,$type,@which) : request for current parameter
                   14910: setting for a specific $type, where $type is either 'course' or 'user',
                   14911: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14912: answers for 10 minutes.
1.243     albertel 14913: 
1.877     foxr     14914: =item *
                   14915: 
                   14916: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14917: data base, returning a hash that is keyed by the resource name and has
                   14918: values that are the resource value.  I believe that the timestamps and
                   14919: versions are also returned.
                   14920: 
1.1172.2.31  raeburn  14921: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14922: supplemental content area. This routine caches the number of files for
                   14923: 10 minutes.
                   14924: 
1.243     albertel 14925: =back
                   14926: 
                   14927: =head2 Course Modification
                   14928: 
                   14929: =over 4
1.191     harris41 14930: 
                   14931: =item *
                   14932: 
1.243     albertel 14933: writecoursepref($courseid,%prefs) : write preferences (environment
                   14934: database) for a course
1.191     harris41 14935: 
                   14936: =item *
                   14937: 
1.1011    raeburn  14938: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14939: 
                   14940: =item *
                   14941: 
1.1038    raeburn  14942: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14943: 
1.1167    droeschl 14944: =item *
                   14945: 
                   14946: is_course($courseid), is_course($cdom, $cnum)
                   14947: 
                   14948: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14949: two component version $cdom, $cnum. It checks if the specified course exists.
                   14950: 
                   14951: Returns:
                   14952:     undef if the course doesn't exist, otherwise
                   14953:     in scalar context the combined courseid.
                   14954:     in list context the two components of the course identifier, domain and 
                   14955:     courseid.    
                   14956: 
1.243     albertel 14957: =back
                   14958: 
1.1172.2.109  raeburn  14959: =head2 Bubblesheet Configuration
                   14960: 
                   14961: =over 4
                   14962: 
                   14963: =item *
                   14964: 
                   14965: get_scantron_config($which)
                   14966: 
                   14967: $which - the name of the configuration to parse from the file.
                   14968: 
                   14969: Parses and returns the bubblesheet configuration line selected as a
                   14970: hash of configuration file fields.
                   14971: 
                   14972: 
                   14973: Returns:
                   14974:     If the named configuration is not in the file, an empty
                   14975:     hash is returned.
                   14976: 
                   14977:     a hash with the fields
                   14978:       name         - internal name for the this configuration setup
                   14979:       description  - text to display to operator that describes this config
                   14980:       CODElocation - if 0 or the string 'none'
                   14981:                           - no CODE exists for this config
                   14982:                      if -1 || the string 'letter'
                   14983:                           - a CODE exists for this config and is
                   14984:                             a string of letters
                   14985:                      Unsupported value (but planned for future support)
                   14986:                           if a positive integer
                   14987:                                - The CODE exists as the first n items from
                   14988:                                  the question section of the form
                   14989:                           if the string 'number'
                   14990:                                - The CODE exists for this config and is
                   14991:                                  a string of numbers
                   14992:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14993:                      the CODE starts
                   14994:       CODElength  - length of the CODE
                   14995:       IDstart     - column where the student/employee ID starts
                   14996:       IDlength    - length of the student/employee ID info
                   14997:       Qstart      - column where the information from the bubbled
                   14998:                     'questions' start
                   14999:       Qlength     - number of columns comprising a single bubble line from
                   15000:                     the sheet. (usually either 1 or 10)
                   15001:       Qon         - either a single character representing the character used
                   15002:                     to signal a bubble was chosen in the positional setup, or
                   15003:                     the string 'letter' if the letter of the chosen bubble is
                   15004:                     in the final, or 'number' if a number representing the
                   15005:                     chosen bubble is in the file (1->A 0->J)
                   15006:       Qoff        - the character used to represent that a bubble was
                   15007:                     left blank
                   15008:       PaperID     - if the scanning process generates a unique number for each
                   15009:                     sheet scanned the column that this ID number starts in
                   15010:       PaperIDlength - number of columns that comprise the unique ID number
                   15011:                       for the sheet of paper
                   15012:       FirstName   - column that the first name starts in
                   15013:       FirstNameLength - number of columns that the first name spans
                   15014:       LastName    - column that the last name starts in
                   15015:       LastNameLength - number of columns that the last name spans
                   15016:       BubblesPerRow - number of bubbles available in each row used to
                   15017:                       bubble an answer. (If not specified, 10 assumed).
                   15018: 
                   15019: 
                   15020: =item *
                   15021: 
                   15022: get_scantronformat_file($cdom)
                   15023: 
                   15024: $cdom - the course's domain (optional); if not supplied, uses
                   15025: domain for current $env{'request.course.id'}.
                   15026: 
                   15027: Returns an array containing lines from the scantron format file for
                   15028: the domain of the course.
                   15029: 
                   15030: If a url for a custom.tab file is listed in domain's configuration.db,
                   15031: lines are from this file.
                   15032: 
                   15033: Otherwise, if a default.tab has been published in RES space by the
                   15034: domainconfig user, lines are from this file.
                   15035: 
                   15036: Otherwise, fall back to getting lines from the legacy file on the
                   15037: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15038: 
                   15039: =back
                   15040: 
1.243     albertel 15041: =head2 Resource Subroutines
                   15042: 
                   15043: =over 4
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.243     albertel 15047: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15048: 
                   15049: =item *
                   15050: 
1.243     albertel 15051: repcopy($filename) : subscribes to the requested file, and attempts to
                   15052: replicate from the owning library server, Might return
1.607     raeburn  15053: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15054: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15055: resource. Expects the local filesystem pathname
                   15056: (/home/httpd/html/res/....)
                   15057: 
                   15058: =back
                   15059: 
                   15060: =head2 Resource Information
                   15061: 
                   15062: =over 4
1.191     harris41 15063: 
                   15064: =item *
                   15065: 
1.1172.2.28  raeburn  15066: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15067: and returns the value of a variety of different possible values,
                   15068: $varname should be a request string, and the other parameters can be
                   15069: used to specify who and what one is asking about. Ordinarily, $cid 
                   15070: does not need to be specified, as it is retrived from 
                   15071: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15072: within lonuserstate::loadmap() when initializing a course, before
                   15073: $env{'request.course.id'} has been set, so it needs to be provided
                   15074: in that one case.
1.243     albertel 15075: 
                   15076: Possible values for $varname are environment.lastname (or other item
                   15077: from the envirnment hash), user.name (or someother aspect about the
                   15078: user), resource.0.maxtries (or some other part and parameter of a
                   15079: resource)
1.204     albertel 15080: 
                   15081: =item *
                   15082: 
1.243     albertel 15083: directcondval($number) : get current value of a condition; reads from a state
                   15084: string
1.204     albertel 15085: 
                   15086: =item *
                   15087: 
1.243     albertel 15088: condval($condidx) : value of condition index based on state
1.204     albertel 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15093: resource's metadata, $what should be either a specific key, or either
                   15094: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15095: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15096: 
                   15097: this function automatically caches all requests
1.191     harris41 15098: 
                   15099: =item *
                   15100: 
1.243     albertel 15101: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15102: network of library servers; returns file handle of where SQL and regex results
                   15103: will be stored for query
1.191     harris41 15104: 
                   15105: =item *
                   15106: 
1.1172.2.66  raeburn  15107: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15108: return symbolic list entry (all arguments optional).
                   15109: 
                   15110: Args: filename is the filename (including path) for the file for which a symb
                   15111: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15112: to check access status if more than one resource was found in the bighash
                   15113: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15114: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15115: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15116: cause possible symbs to be checked to determine if they are subject to content
                   15117: blocking, if so they will not be included as possible symbs; possibles is a
                   15118: ref to a hash, which, as a side effect, will be populated with all possible
                   15119: symbs (content blocking not tested).
                   15120: 
1.243     albertel 15121: returns the data handle
1.191     harris41 15122: 
                   15123: =item *
                   15124: 
1.1172.2.17  raeburn  15125: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15126: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15127: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15128: on failure, user must be in a course, as it assumes the existence of
                   15129: the course initial hash, and uses $env('request.course.id'}.  The third
                   15130: arg is an optional reference to a scalar.  If this arg is passed in the
                   15131: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15132: encrypted; otherwise it will be null.
1.243     albertel 15133: 
1.191     harris41 15134: =item *
                   15135: 
1.243     albertel 15136: symbclean($symb) : removes versions numbers from a symb, returns the
                   15137: cleaned symb
1.191     harris41 15138: 
                   15139: =item *
                   15140: 
1.243     albertel 15141: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15142: course map, user must be in a course for it to work.
1.191     harris41 15143: 
                   15144: =item *
                   15145: 
1.243     albertel 15146: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15147: 
                   15148: =item *
                   15149: 
1.243     albertel 15150: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15151: a random seed, all arguments are optional, if they aren't sent it uses the
                   15152: environment to derive them. Note: if symb isn't sent and it can't get one
                   15153: from &symbread it will use the current time as its return value
1.191     harris41 15154: 
                   15155: =item *
                   15156: 
1.243     albertel 15157: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15158: unfakeable, receipt
1.191     harris41 15159: 
                   15160: =item *
                   15161: 
1.620     albertel 15162: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.243     albertel 15166: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15167: 
                   15168: =item *
                   15169: 
1.243     albertel 15170: 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 15171: 
                   15172: =item *
                   15173: 
1.243     albertel 15174: 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 15175: 
                   15176: =item *
                   15177: 
1.243     albertel 15178: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15179: 
                   15180: =item *
                   15181: 
1.243     albertel 15182: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15183: forcing spreadsheet to reevaluate the resource scores next time.
                   15184: 
1.1172.2.13  raeburn  15185: =item *
                   15186: 
                   15187: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15188: when viewing in course context.
                   15189: 
                   15190:  input: six args -- filename (decluttered), course number, course domain,
                   15191:                     url, symb (if registered) and group (if this is a
                   15192:                     group item -- e.g., bulletin board, group page etc.).
                   15193: 
                   15194:  output: array of five scalars --
                   15195:          $cfile -- url for file editing if editable on current server
                   15196:          $home -- homeserver of resource (i.e., for author if published,
                   15197:                                           or course if uploaded.).
                   15198:          $switchserver --  1 if server switch will be needed.
                   15199:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15200:          $forceview -- 1 if icon/link should be to go to view mode
                   15201: 
                   15202: =item *
                   15203: 
                   15204: is_course_upload($file,$cnum,$cdom)
                   15205: 
                   15206: Used in course context to determine if current file was uploaded to
                   15207: the course (i.e., would be found in /userfiles/docs on the course's
                   15208: homeserver.
                   15209: 
                   15210:   input: 3 args -- filename (decluttered), course number and course domain.
                   15211:   output: boolean -- 1 if file was uploaded.
                   15212: 
1.243     albertel 15213: =back
                   15214: 
                   15215: =head2 Storing/Retreiving Data
                   15216: 
                   15217: =over 4
1.191     harris41 15218: 
                   15219: =item *
                   15220: 
1.1172.2.64  raeburn  15221: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15222: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15223: the remaining args aren't required and if they aren't passed or are '' they will
                   15224: be derived from the env (with the exception of $laststore, which is an
                   15225: optional arg used when a user's submission is stored in grading).
                   15226: $laststore is $version=$timestamp, where $version is the most recent version
                   15227: number retrieved for the corresponding $symb in the $namespace db file, and
                   15228: $timestamp is the timestamp for that transaction (UNIX time).
                   15229: $laststore is currently only passed when cstore() is called by
                   15230: structuretags::finalize_storage().
1.191     harris41 15231: 
                   15232: =item *
                   15233: 
1.1172.2.64  raeburn  15234: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15235: but uses critical subroutine
1.191     harris41 15236: 
                   15237: =item *
                   15238: 
1.243     albertel 15239: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15240: all args are optional
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.717     albertel 15244: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15245: dumps the complete (or key matching regexp) namespace into a hash
                   15246: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15247: normally &store()ed into
                   15248: 
                   15249: $range should be either an integer '100' (give me the first 100
                   15250:                                            matching records)
                   15251:               or be  two integers sperated by a - with no spaces
                   15252:                  '30-50' (give me the 30th through the 50th matching
                   15253:                           records)
                   15254: 
                   15255: 
                   15256: =item *
                   15257: 
1.1172.2.59  raeburn  15258: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15259: replaces a &store() version of data with a replacement set of data
                   15260: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15261: reference. If $tolog is true, the transaction is logged in the courselog
                   15262: with an action=PUTSTORE.
1.717     albertel 15263: 
                   15264: =item *
                   15265: 
1.243     albertel 15266: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15267: works very similar to store/cstore, but all data is stored in a
                   15268: temporary location and can be reset using tmpreset, $storehash should
                   15269: be a hash reference, returns nothing on success
1.191     harris41 15270: 
                   15271: =item *
                   15272: 
1.243     albertel 15273: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15274: similar to restore, but all data is stored in a temporary location and
                   15275: can be reset using tmpreset. Returns a hash of values on success,
                   15276: error string otherwise.
1.191     harris41 15277: 
                   15278: =item *
                   15279: 
1.243     albertel 15280: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15281: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15282: 
                   15283: =item *
                   15284: 
1.243     albertel 15285: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15286: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15287: 
                   15288: =item *
                   15289: 
1.243     albertel 15290: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15291: namesp ($udom and $uname are optional)
1.191     harris41 15292: 
                   15293: =item *
                   15294: 
1.702     albertel 15295: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15296: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15297: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15298: 
1.702     albertel 15299: $range should be either an integer '100' (give me the first 100
                   15300:                                            matching records)
                   15301:               or be  two integers sperated by a - with no spaces
                   15302:                  '30-50' (give me the 30th through the 50th matching
                   15303:                           records)
1.449     matthew  15304: =item *
                   15305: 
                   15306: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15307: $store can be a scalar, an array reference, or if the amount to be 
                   15308: incremented is > 1, a hash reference.
                   15309: 
                   15310: ($udom and $uname are optional)
1.191     harris41 15311: 
                   15312: =item *
                   15313: 
1.243     albertel 15314: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15315: ($udom and $uname are optional)
1.191     harris41 15316: 
                   15317: =item *
                   15318: 
1.243     albertel 15319: cput($namespace,$storehash,$udom,$uname) : critical put
                   15320: ($udom and $uname are optional)
1.191     harris41 15321: 
                   15322: =item *
                   15323: 
1.748     albertel 15324: newput($namespace,$storehash,$udom,$uname) :
                   15325: 
                   15326: Attempts to store the items in the $storehash, but only if they don't
                   15327: currently exist, if this succeeds you can be certain that you have 
                   15328: successfully created a new key value pair in the $namespace db.
                   15329: 
                   15330: 
                   15331: Args:
                   15332:  $namespace: name of database to store values to
                   15333:  $storehash: hashref to store to the db
                   15334:  $udom: (optional) domain of user containing the db
                   15335:  $uname: (optional) name of user caontaining the db
                   15336: 
                   15337: Returns:
                   15338:  'ok' -> succeeded in storing all keys of $storehash
                   15339:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15340:                         least <key> already existed in the db (other
                   15341:                         requested keys may also already exist)
1.967     bisitz   15342:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15343:  'con_lost' -> unable to contact request server
                   15344:  'refused' -> action was not allowed by remote machine
                   15345: 
                   15346: 
                   15347: =item *
                   15348: 
1.243     albertel 15349: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15350: reference filled in from namesp (encrypts the return communication)
                   15351: ($udom and $uname are optional)
1.191     harris41 15352: 
                   15353: =item *
                   15354: 
1.243     albertel 15355: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15356: critical subroutine
                   15357: 
1.806     raeburn  15358: =item *
                   15359: 
1.860     raeburn  15360: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15361: array reference filled in from namespace found in domain level on either
                   15362: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15363: 
                   15364: =item *
                   15365: 
1.860     raeburn  15366: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15367: domain level either on specified domain server ($uhome) or primary domain 
                   15368: server ($udom and $uhome are optional)
1.806     raeburn  15369: 
1.943     raeburn  15370: =item * 
                   15371: 
1.1172.2.35  raeburn  15372: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15373: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15374: the target domain.
                   15375: 
                   15376: May also include additional key => value pairs for the following groups:
                   15377: 
                   15378: =over
                   15379: 
                   15380: =item
                   15381: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15382: 
                   15383: =over
                   15384: 
                   15385: =item defaultquota, authorquota
                   15386: 
                   15387: =back
                   15388: 
                   15389: =item
                   15390: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15391: portfolio for users).
                   15392: 
                   15393: =over
                   15394: 
                   15395: =item
                   15396: aboutme, blog, webdav, portfolio
                   15397: 
                   15398: =back
                   15399: 
                   15400: =item
                   15401: requestcourses: ability to request courses, and how requests are processed.
                   15402: 
                   15403: =over
                   15404: 
                   15405: =item
1.1172.2.37  raeburn  15406: official, unofficial, community, textbook
1.1172.2.35  raeburn  15407: 
                   15408: =back
                   15409: 
                   15410: =item
                   15411: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15412: 
                   15413: =over
                   15414: 
                   15415: =item
1.1172.2.44  raeburn  15416: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15417: 
                   15418: =back
                   15419: 
                   15420: =item
                   15421: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15422: for course's uploaded content.
                   15423: 
                   15424: =over
                   15425: 
                   15426: =item
1.1172.2.68  raeburn  15427: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15428: communityquota, textbookquota
1.1172.2.35  raeburn  15429: 
                   15430: =back
                   15431: 
                   15432: =item
                   15433: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15434: on your servers.
                   15435: 
                   15436: =over
                   15437: 
                   15438: =item
                   15439: remotesessions, hostedsessions
                   15440: 
                   15441: =back
                   15442: 
                   15443: =back
                   15444: 
                   15445: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15446: utility to create a configuration.db file on a domain's primary library server
                   15447: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15448: -- corresponding values are authentication type (internal, krb4, krb5,
                   15449: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15450: will be available. Values are retrieved from cache (if current), unless the
                   15451: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15452: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15453: 
                   15454: Typical usage:
1.943     raeburn  15455: 
1.1172.2.35  raeburn  15456: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15457: 
1.243     albertel 15458: =back
                   15459: 
                   15460: =head2 Network Status Functions
                   15461: 
                   15462: =over 4
1.191     harris41 15463: 
                   15464: =item *
                   15465: 
1.1137    raeburn  15466: dirlist() : return directory list based on URI (first arg).
                   15467: 
                   15468: Inputs: 1 required, 5 optional.
                   15469: 
                   15470: =over
                   15471: 
                   15472: =item 
                   15473: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15474: 
                   15475: =item
                   15476: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15477: 
                   15478: =item
                   15479: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15480: 
                   15481: =item
                   15482: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15483: 
                   15484: =item
                   15485: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15486: 
                   15487: =item 
                   15488: $alternateRoot - path to prepend in place of path from $uri.
                   15489: 
                   15490: =back
                   15491: 
                   15492: Returns: Array of up to two items.
                   15493: 
                   15494: =over
                   15495: 
                   15496: a reference to an array of files/subdirectories
                   15497: 
                   15498: =over
                   15499: 
                   15500: Each element in the array of files/subdirectories is a & separated list of
                   15501: item name and the result of running stat on the item.  If dirlist was requested
                   15502: for a file instead of a directory, the item name will be ''. For a directory 
                   15503: listing, if the item is a metadata file, the element will end &N&M 
                   15504: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15505: default copyright set (1).  
                   15506: 
                   15507: =back
                   15508: 
                   15509: a scalar containing error condition (if encountered).
                   15510: 
                   15511: =over
                   15512: 
                   15513: =item 
                   15514: no_host (no homeserver identified for $username:$domain).
                   15515: 
                   15516: =item 
                   15517: no_such_host (server contacted for listing not identified as valid host).
                   15518: 
                   15519: =item 
                   15520: con_lost (connection to remote server failed).
                   15521: 
                   15522: =item 
                   15523: refused (invalid $username:$domain received on lond side).
                   15524: 
                   15525: =item 
                   15526: no_such_dir (directory at specified path on lond side does not exist). 
                   15527: 
                   15528: =item 
                   15529: empty (directory at specified path on lond side is empty).
                   15530: 
                   15531: =over
                   15532: 
                   15533: This is currently not encountered because the &ls3, &ls2, 
                   15534: &ls (_handler) routines on the lond side do not filter out
                   15535: . and .. from a directory listing. 
                   15536: 
                   15537: =back
                   15538: 
                   15539: =back
                   15540: 
                   15541: =back
1.191     harris41 15542: 
                   15543: =item *
                   15544: 
1.243     albertel 15545: spareserver() : find server with least workload from spare.tab
                   15546: 
1.986     foxr     15547: 
                   15548: =item *
                   15549: 
                   15550: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15551: if there is no corresponding loncapa host.
                   15552: 
1.243     albertel 15553: =back
                   15554: 
1.986     foxr     15555: 
1.243     albertel 15556: =head2 Apache Request
                   15557: 
                   15558: =over 4
1.191     harris41 15559: 
                   15560: =item *
                   15561: 
1.243     albertel 15562: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15563: localhost, posts hash
                   15564: 
                   15565: =back
                   15566: 
                   15567: =head2 Data to String to Data
                   15568: 
                   15569: =over 4
1.191     harris41 15570: 
                   15571: =item *
                   15572: 
1.243     albertel 15573: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15574: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15575: 
                   15576: =item *
                   15577: 
1.243     albertel 15578: hashref2str($hashref) : convert a hashref into a string complete with
                   15579: escaping and '=' and '&' separators, supports elements that are
                   15580: arrayrefs and hashrefs
1.191     harris41 15581: 
                   15582: =item *
                   15583: 
1.243     albertel 15584: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15585: with escaping and '&' separators, supports elements that are arrayrefs
                   15586: and hashrefs
1.191     harris41 15587: 
                   15588: =item *
                   15589: 
1.243     albertel 15590: str2hash($string) : convert string to hash using unescaping and
                   15591: splitting on '=' and '&', supports elements that are arrayrefs and
                   15592: hashrefs
1.191     harris41 15593: 
                   15594: =item *
                   15595: 
1.243     albertel 15596: str2array($string) : convert string to hash using unescaping and
                   15597: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15598: 
                   15599: =back
                   15600: 
                   15601: =head2 Logging Routines
                   15602: 
                   15603: 
                   15604: These routines allow one to make log messages in the lonnet.log and
                   15605: lonnet.perm logfiles.
1.191     harris41 15606: 
1.1119    foxr     15607: =over 4
                   15608: 
1.191     harris41 15609: =item *
                   15610: 
1.243     albertel 15611: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15612: 
                   15613: =item *
                   15614: 
1.243     albertel 15615: logthis() : append message to the normal lonnet.log file, it gets
                   15616: preiodically rolled over and deleted.
1.191     harris41 15617: 
                   15618: =item *
                   15619: 
1.243     albertel 15620: logperm() : append a permanent message to lonnet.perm.log, this log
                   15621: file never gets deleted by any automated portion of the system, only
                   15622: messages of critical importance should go in here.
                   15623: 
1.1119    foxr     15624: 
1.243     albertel 15625: =back
                   15626: 
                   15627: =head2 General File Helper Routines
                   15628: 
                   15629: =over 4
1.191     harris41 15630: 
                   15631: =item *
                   15632: 
1.481     raeburn  15633: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15634: (a) files in /uploaded
                   15635:   (i) If a local copy of the file exists - 
                   15636:       compares modification date of local copy with last-modified date for 
                   15637:       definitive version stored on home server for course. If local copy is 
                   15638:       stale, requests a new version from the home server and stores it. 
                   15639:       If the original has been removed from the home server, then local copy 
                   15640:       is unlinked.
                   15641:   (ii) If local copy does not exist -
                   15642:       requests the file from the home server and stores it. 
                   15643:   
                   15644:   If $caller is 'uploadrep':  
                   15645:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15646:     for request for files originally uploaded via DOCS. 
                   15647:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15648:   
                   15649:   Otherwise:
                   15650:      This indicates a call from the content generation phase of the request.
                   15651:      -  returns the entire contents of the file or -1.
                   15652:      
                   15653: (b) files in /res
                   15654:    - returns the entire contents of a file or -1; 
                   15655:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15656: 
1.712     albertel 15657: 
                   15658: =item *
                   15659: 
                   15660: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15661:                   reference
                   15662: 
                   15663: returns either a stat() list of data about the file or an empty list
                   15664: if the file doesn't exist or couldn't find out about it (connection
                   15665: problems or user unknown)
                   15666: 
1.191     harris41 15667: =item *
                   15668: 
1.243     albertel 15669: filelocation($dir,$file) : returns file system location of a file
                   15670: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15671: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15672: and a file of ../bob will become /a/bob)
1.191     harris41 15673: 
                   15674: =item *
                   15675: 
                   15676: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15677: filelocation except for hrefs
                   15678: 
                   15679: =item *
                   15680: 
1.1172.2.49  raeburn  15681: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15682: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15683: 
1.243     albertel 15684: =back
                   15685: 
1.608     albertel 15686: =head2 Usererfile file routines (/uploaded*)
                   15687: 
                   15688: =over 4
                   15689: 
                   15690: =item *
                   15691: 
                   15692: userfileupload(): main rotine for putting a file in a user or course's
                   15693:                   filespace, arguments are,
                   15694: 
1.620     albertel 15695:  formname - required - this is the name of the element in $env where the
1.608     albertel 15696:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15697:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15698:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15699:  context - if coursedoc, store the file in the course of the active role
                   15700:              of the current user; 
                   15701:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15702:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15703:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15704:          if undefined, it will be placed in "unknown"
                   15705: 
                   15706:  (This routine calls clean_filename() to remove any dangerous
                   15707:  characters from the filename, and then calls finuserfileupload() to
                   15708:  complete the transaction)
                   15709: 
                   15710:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15711:  and /adm/notfound.html if unsuccessful
                   15712: 
                   15713: =item *
                   15714: 
                   15715: clean_filename(): routine for cleaing a filename up for storage in
                   15716:                  userfile space, argument is:
                   15717: 
                   15718:  filename - proposed filename
                   15719: 
                   15720: returns: the new clean filename
                   15721: 
                   15722: =item *
                   15723: 
1.1090    raeburn  15724: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15725: userspace, probably shouldn't be called directly
                   15726: 
                   15727:   docuname: username or courseid of destination for the file
                   15728:   docudom: domain of user/course of destination for the file
                   15729:   formname: same as for userfileupload()
1.1090    raeburn  15730:   fname: filename (including subdirectories) for the file
                   15731:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15732:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15733:   allfiles: reference to hash used to store objects found by parser
                   15734:   codebase: reference to hash used for codebases of java objects found by parser
                   15735:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15736:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15737:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15738:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15739:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15740:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15741:   mimetype: reference to scalar to accommodate mime type determined
                   15742:             from File::MMagic if $parser = parse.
1.608     albertel 15743: 
                   15744:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15745:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15746:  was 'overwrite').
                   15747:  
1.608     albertel 15748: 
                   15749: =item *
                   15750: 
                   15751: renameuserfile(): renames an existing userfile to a new name
                   15752: 
                   15753:   Args:
                   15754:    docuname: username or courseid of destination for the file
                   15755:    docudom: domain of user/course of destination for the file
                   15756:    old: current file name (including any subdirs under userfiles)
                   15757:    new: desired file name (including any subdirs under userfiles)
                   15758: 
                   15759: =item *
                   15760: 
                   15761: mkdiruserfile(): creates a directory is a userfiles dir
                   15762: 
                   15763:   Args:
                   15764:    docuname: username or courseid of destination for the file
                   15765:    docudom: domain of user/course of destination for the file
                   15766:    dir: dir to create (including any subdirs under userfiles)
                   15767: 
                   15768: =item *
                   15769: 
                   15770: removeuserfile(): removes a file that exists in userfiles
                   15771: 
                   15772:   Args:
                   15773:    docuname: username or courseid of destination for the file
                   15774:    docudom: domain of user/course of destination for the file
                   15775:    fname: filname to delete (including any subdirs under userfiles)
                   15776: 
                   15777: =item *
                   15778: 
                   15779: removeuploadedurl(): convience function for removeuserfile()
                   15780: 
                   15781:   Args:
                   15782:    url:  a full /uploaded/... url to delete
                   15783: 
1.747     albertel 15784: =item * 
                   15785: 
                   15786: get_portfile_permissions():
                   15787:   Args:
                   15788:     domain: domain of user or course contain the portfolio files
                   15789:     user: name of user or num of course contain the portfolio files
                   15790:   Returns:
                   15791:     hashref of a dump of the proper file_permissions.db
                   15792:    
                   15793: 
                   15794: =item * 
                   15795: 
                   15796: get_access_controls():
                   15797: 
                   15798: Args:
                   15799:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15800:   group: (optional) the group you want the files associated with
                   15801:   file: (optional) the file you want access info on
                   15802: 
                   15803: Returns:
1.749     raeburn  15804:     a hash (keys are file names) of hashes containing
                   15805:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15806:         values are XML containing access control settings (see below) 
1.747     albertel 15807: 
                   15808: Internal notes:
                   15809: 
1.749     raeburn  15810:  access controls are stored in file_permissions.db as key=value pairs.
                   15811:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15812:         where scope -> public,guest,course,group,domains or users.
                   15813:               end -> UNIX time for end of access (0 -> no end date)
                   15814:               start -> UNIX time for start of access
                   15815: 
                   15816:     value -> XML description of access control
                   15817:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15818:             <start></start>
                   15819:             <end></end>
                   15820: 
                   15821:             <password></password>  for scope type = guest
                   15822: 
                   15823:             <domain></domain>     for scope type = course or group
                   15824:             <number></number>
                   15825:             <roles id="">
                   15826:              <role></role>
                   15827:              <access></access>
                   15828:              <section></section>
                   15829:              <group></group>
                   15830:             </roles>
                   15831: 
                   15832:             <dom></dom>         for scope type = domains
                   15833: 
                   15834:             <users>             for scope type = users
                   15835:              <user>
                   15836:               <uname></uname>
                   15837:               <udom></udom>
                   15838:              </user>
                   15839:             </users>
                   15840:            </scope> 
                   15841:               
                   15842:  Access data is also aggregated for each file in an additional key=value pair:
                   15843:  key -> path to file/file_name\0accesscontrol 
                   15844:  value -> reference to hash
                   15845:           hash contains key = value pairs
                   15846:           where key = uniqueID:scope_end_start
                   15847:                 value = UNIX time record was last updated
                   15848: 
                   15849:           Used to improve speed of look-ups of access controls for each file.  
                   15850:  
                   15851:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15852: 
1.1172.2.13  raeburn  15853: =item *
                   15854: 
1.749     raeburn  15855: modify_access_controls():
                   15856: 
                   15857: Modifies access controls for a portfolio file
                   15858: Args
                   15859: 1. file name
                   15860: 2. reference to hash of required changes,
                   15861: 3. domain
                   15862: 4. username
                   15863:   where domain,username are the domain of the portfolio owner 
                   15864:   (either a user or a course) 
                   15865: 
                   15866: Returns:
                   15867: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15868: 2. result of deletions ('ok' or 'error', with error message).
                   15869: 3. reference to hash of any new or updated access controls.
                   15870: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15871:    key = integer (inbound ID)
1.1172.2.13  raeburn  15872:    value = uniqueID
                   15873: 
                   15874: =item *
                   15875: 
                   15876: get_timebased_id():
                   15877: 
                   15878: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15879: course via the Course Editor (e.g., folders, composite pages,
                   15880: group bulletin boards).
                   15881: 
                   15882: Args: (first three required; six others optional)
                   15883: 
                   15884: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15885:    docssequence, or name of group
                   15886: 
                   15887: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15888:    e.g., num, boardids
                   15889: 
                   15890: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15891:    file will be named nohist_namespace.db
                   15892: 
                   15893: 4. cdom: domain of course; default is current course domain from %env
                   15894: 
                   15895: 5. cnum: course number; default is current course number from %env
                   15896: 
                   15897: 6. idtype: set to concat if an additional digit is to be appended to the
                   15898:    unix timestamp to form the suffix, if the plain timestamp is already
                   15899:    in use.  Default is to not do this, but simply increment the unix
                   15900:    timestamp by 1 until a unique key is obtained.
                   15901: 
                   15902: 7. who: holder of locking key; defaults to user:domain for user.
                   15903: 
                   15904: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15905:    retrying); default is 3.
                   15906: 
                   15907: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15908: 
                   15909: Returns:
                   15910: 
                   15911: 1. suffix obtained (numeric)
                   15912: 
                   15913: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15914: 
                   15915: 3. error: contains (localized) error message if an error occurred.
                   15916: 
1.747     albertel 15917: 
1.608     albertel 15918: =back
                   15919: 
1.243     albertel 15920: =head2 HTTP Helper Routines
                   15921: 
                   15922: =over 4
                   15923: 
1.191     harris41 15924: =item *
                   15925: 
                   15926: escape() : unpack non-word characters into CGI-compatible hex codes
                   15927: 
                   15928: =item *
                   15929: 
                   15930: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15931: 
1.243     albertel 15932: =back
                   15933: 
                   15934: =head1 PRIVATE SUBROUTINES
                   15935: 
                   15936: =head2 Underlying communication routines (Shouldn't call)
                   15937: 
                   15938: =over 4
                   15939: 
                   15940: =item *
                   15941: 
                   15942: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15943: 
                   15944: =item *
                   15945: 
                   15946: reply() : uses subreply to send a message to remote machine, logs all failures
                   15947: 
                   15948: =item *
                   15949: 
                   15950: critical() : passes a critical message to another server; if cannot
                   15951: get through then place message in connection buffer directory and
                   15952: returns con_delayed, if incapable of saving message, returns
                   15953: con_failed
                   15954: 
                   15955: =item *
                   15956: 
                   15957: reconlonc() : tries to reconnect lonc client processes.
                   15958: 
                   15959: =back
                   15960: 
                   15961: =head2 Resource Access Logging
                   15962: 
                   15963: =over 4
                   15964: 
                   15965: =item *
                   15966: 
                   15967: flushcourselogs() : flush (save) buffer logs and access logs
                   15968: 
                   15969: =item *
                   15970: 
                   15971: courselog($what) : save message for course in hash
                   15972: 
                   15973: =item *
                   15974: 
                   15975: courseacclog($what) : save message for course using &courselog().  Perform
                   15976: special processing for specific resource types (problems, exams, quizzes, etc).
                   15977: 
1.191     harris41 15978: =item *
                   15979: 
                   15980: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15981: as a PerlChildExitHandler
1.243     albertel 15982: 
                   15983: =back
                   15984: 
                   15985: =head2 Other
                   15986: 
                   15987: =over 4
                   15988: 
                   15989: =item *
                   15990: 
                   15991: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15992: 
                   15993: =back
                   15994: 
                   15995: =cut
1.877     foxr     15996: 

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