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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .21(raeb    4:-21): # $Id: lonnet.pm,v 1.1172.2.118.2.20 2021/06/20 18:54:07 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.1172.2.118.  .19(raeb 3788:-21): # Replace three or more adjacent underscores with one for consistency
                   3789:-21): # with loncfile::filename_check() so complete url can be extracted by
                   3790:-21): # lonnet::decode_symb()
                   3791:-21):     $fname=~s/_{3,}/_/g;
1.531     albertel 3792:     return $fname;
                   3793: }
1.1172.2.110  raeburn  3794: 
1.1051    raeburn  3795: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3796: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3797: # image with the same aspect ratio as the original, but with dimensions which do 
                   3798: # not exceed $resizewidth and $resizeheight.
                   3799:  
1.984     neumanie 3800: sub resizeImage {
1.1051    raeburn  3801:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3802:     my $ima = Image::Magick->new;
                   3803:     my $resized;
                   3804:     if (-e $img_path) {
                   3805:         $ima->Read($img_path);
                   3806:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3807:             my $width = $ima->Get('width');
                   3808:             my $height = $ima->Get('height');
                   3809:             if ($width > $resizewidth) {
                   3810: 	        my $factor = $width/$resizewidth;
                   3811:                 my $newheight = $height/$factor;
                   3812:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3813:                 $resized = 1;
                   3814:             }
                   3815:         }
                   3816:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3817:             my $width = $ima->Get('width');
                   3818:             my $height = $ima->Get('height');
                   3819:             if ($height > $resizeheight) {
                   3820:                 my $factor = $height/$resizeheight;
                   3821:                 my $newwidth = $width/$factor;
                   3822:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3823:                 $resized = 1;
                   3824:             }
                   3825:         }
                   3826:         if ($resized) {
                   3827:             $ima->Write($img_path);
                   3828:         }
                   3829:     }
                   3830:     return;
1.977     amueller 3831: }
                   3832: 
1.608     albertel 3833: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3834: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3835: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3836: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3837: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3838: #                   if 'coursedoc': upload to the current course
                   3839: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3840: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3841: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3842: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3843: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3844: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3845: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3846: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3847: #        $allfiles - reference to hash for embedded objects
                   3848: #        $codebase - reference to hash for codebase of java objects
                   3849: #        $desuname - username for permanent storage of uploaded file
                   3850: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3851: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3852: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3853: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3854: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3855: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3856: #                    from File::MMagic.
1.858     raeburn  3857: # 
1.686     albertel 3858: # output: url of file in userspace, or error: <message> 
                   3859: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3860: 
1.531     albertel 3861: sub userfileupload {
1.1090    raeburn  3862:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3863:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3864:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3865:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3866:     $fname=&clean_filename($fname);
1.1090    raeburn  3867:     # See if there is anything left
1.257     www      3868:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3869:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3870:     if ($fname =~ /^\./) {
                   3871:         my ($s,$usec) = &gettimeofday();
                   3872:         while (length($usec) < 6) {
                   3873:             $usec = '0'.$usec;
                   3874:         }
                   3875:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3876:     }
1.1090    raeburn  3877:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3878:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3879:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3880:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3881:         my $now = time;
1.1090    raeburn  3882:         my $filepath;
1.1095    raeburn  3883:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3884:              $filepath = 'tmp/helprequests/'.$now;
                   3885:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3886:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3887:                          '_'.$env{'user.domain'}.'/pending';
                   3888:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3889:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3890:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3891:                 $docudom = $destudom;
                   3892:             } else {
                   3893:                 $docudom = $env{'user.domain'};
                   3894:             }
1.1172.2.96  raeburn  3895:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3896:                 $docuname = $destuname;
                   3897:             } else {
                   3898:                 $docuname = $env{'user.name'};
                   3899:             }
                   3900:             if (exists($env{'form.group'})) {
                   3901:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3902:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3903:             }
                   3904:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3905:             if ($context eq 'canceloverwrite') {
                   3906:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3907:                 if (-e  $tempfile) {
                   3908:                     my @info = stat($tempfile);
                   3909:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3910:                         unlink($tempfile);
                   3911:                     }
                   3912:                 }
                   3913:                 return;
1.523     raeburn  3914:             }
                   3915:         }
1.1090    raeburn  3916:         # Create the directory if not present
1.741     raeburn  3917:         my @parts=split(/\//,$filepath);
                   3918:         my $fullpath = $perlvar{'lonDaemons'};
                   3919:         for (my $i=0;$i<@parts;$i++) {
                   3920:             $fullpath .= '/'.$parts[$i];
                   3921:             if ((-e $fullpath)!=1) {
                   3922:                 mkdir($fullpath,0777);
                   3923:             }
                   3924:         }
1.1172.2.96  raeburn  3925:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3926:         print $fh $env{'form.'.$formname};
                   3927:         close($fh);
1.1090    raeburn  3928:         if ($context eq 'existingfile') {
                   3929:             my @info = stat($fullpath.'/'.$fname);
                   3930:             return ($fullpath.'/'.$fname,$info[9]);
                   3931:         } else {
                   3932:             return $fullpath.'/'.$fname;
                   3933:         }
1.523     raeburn  3934:     }
1.995     raeburn  3935:     if ($subdir eq 'scantron') {
                   3936:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3937:     } else {
1.995     raeburn  3938:         $fname="$subdir/$fname";
                   3939:     }
1.1090    raeburn  3940:     if ($context eq 'coursedoc') {
1.638     albertel 3941: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3942: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3943:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3944:             return &finishuserfileupload($docuname,$docudom,
                   3945: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3946: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3947:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3948:         } else {
1.1172.2.21  raeburn  3949:             if ($env{'form.folder'}) {
                   3950:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3951:             }
1.638     albertel 3952:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3953: 				       $fname,$formname,$parser,
1.1095    raeburn  3954: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3955:         }
1.719     banghart 3956:     } elsif (defined($destuname)) {
                   3957:         my $docuname=$destuname;
                   3958:         my $docudom=$destudom;
1.860     raeburn  3959: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3960: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3961:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3962:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3963:     } else {
1.638     albertel 3964:         my $docuname=$env{'user.name'};
                   3965:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3966:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3967:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3968:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3969:         }
1.860     raeburn  3970: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3971: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3972:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3973:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3974:     }
1.271     www      3975: }
                   3976: 
                   3977: sub finishuserfileupload {
1.860     raeburn  3978:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3979:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3980:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3981:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3982:   
1.860     raeburn  3983:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3984:     $file=$fname;
                   3985:     if ($fname=~m|/|) {
                   3986:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3987: 	$path.=$fnamepath.'/';
                   3988:     }
1.259     www      3989:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3990:     my $count;
                   3991:     for ($count=4;$count<=$#parts;$count++) {
                   3992:         $filepath.="/$parts[$count]";
                   3993:         if ((-e $filepath)!=1) {
                   3994: 	    mkdir($filepath,0777);
                   3995:         }
                   3996:     }
1.984     neumanie 3997: 
1.258     www      3998: # Save the file
                   3999:     {
1.1172.2.96  raeburn  4000: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4001: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4002: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4003: 	    return '/adm/notfound.html';
                   4004: 	}
1.1090    raeburn  4005:         if ($context eq 'overwrite') {
1.1117    foxr     4006:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4007:             my $target = $filepath.'/'.$file;
                   4008:             if (-e $source) {
                   4009:                 my @info = stat($source);
                   4010:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4011:                     unless (&File::Copy::move($source,$target)) {
                   4012:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4013:                         return "Moving from $source failed";
                   4014:                     }
                   4015:                 } else {
                   4016:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4017:                 }
                   4018:             } else {
                   4019:                 return "Temporary file: $source missing";
                   4020:             }
                   4021:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4022: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4023: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4024: 	    return '/adm/notfound.html';
                   4025: 	}
1.570     albertel 4026: 	close(FH);
1.1051    raeburn  4027:         if ($resizewidth && $resizeheight) {
                   4028:             my $mm = new File::MMagic;
                   4029:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4030:             if ($mime_type =~ m{^image/}) {
                   4031: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4032:             }  
1.977     amueller 4033: 	}
1.258     www      4034:     }
1.1152    raeburn  4035:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4036:         if (ref($mimetype)) {
                   4037:             if ($$mimetype eq '') {
                   4038:                 my $mm = new File::MMagic;
                   4039:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4040:                 $$mimetype = $type;
                   4041:             }
                   4042:         }
                   4043:     }
1.1172.2.109  raeburn  4044:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4045:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4046:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4047:                                                        $allfiles,$codebase);
                   4048:             unless ($parse_result eq 'ok') {
                   4049:                 &logthis('Failed to parse '.$filepath.$file.
                   4050: 	   	         ' for embedded media: '.$parse_result); 
                   4051:             }
1.637     raeburn  4052:         }
1.1172.2.109  raeburn  4053:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4054:         my $format = $env{'form.scantron_format'};
                   4055:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4056:     }
1.860     raeburn  4057:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4058:         my $input = $filepath.'/'.$file;
                   4059:         my $output = $filepath.'/'.'tn-'.$file;
                   4060:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4061:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4062:         system({$args[0]} @args);
1.860     raeburn  4063:         if (-e $filepath.'/'.'tn-'.$file) {
                   4064:             $fetchthumb  = 1; 
                   4065:         }
                   4066:     }
1.858     raeburn  4067:  
1.259     www      4068: # Notify homeserver to grep it
                   4069: #
1.984     neumanie 4070:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4071:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4072:     if ($fetchresult eq 'ok') {
1.860     raeburn  4073:         if ($fetchthumb) {
                   4074:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4075:             if ($thumbresult ne 'ok') {
                   4076:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4077:                          $docuhome.': '.$thumbresult);
                   4078:             }
                   4079:         }
1.259     www      4080: #
1.258     www      4081: # Return the URL to it
1.494     albertel 4082:         return '/uploaded/'.$path.$file;
1.263     www      4083:     } else {
1.494     albertel 4084:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4085: 		 ': '.$fetchresult);
1.263     www      4086:         return '/adm/notfound.html';
1.858     raeburn  4087:     }
1.493     albertel 4088: }
                   4089: 
1.637     raeburn  4090: sub extract_embedded_items {
1.961     raeburn  4091:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4092:     my @state = ();
1.1164    raeburn  4093:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4094:     my %javafiles = (
                   4095:                       codebase => '',
                   4096:                       code => '',
                   4097:                       archive => ''
                   4098:                     );
                   4099:     my %mediafiles = (
                   4100:                       src => '',
                   4101:                       movie => '',
                   4102:                      );
1.648     raeburn  4103:     my $p;
                   4104:     if ($content) {
                   4105:         $p = HTML::LCParser->new($content);
                   4106:     } else {
1.961     raeburn  4107:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4108:     }
1.641     albertel 4109:     while (my $t=$p->get_token()) {
1.640     albertel 4110: 	if ($t->[0] eq 'S') {
                   4111: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4112: 	    push(@state, $tagname);
1.648     raeburn  4113:             if (lc($tagname) eq 'allow') {
                   4114:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4115:             }
1.640     albertel 4116: 	    if (lc($tagname) eq 'img') {
                   4117: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4118: 	    }
1.886     albertel 4119: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4120:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4121: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4122:                 }
1.886     albertel 4123: 	    }
1.645     raeburn  4124:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4125:                 my $src;
1.645     raeburn  4126:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4127:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4128:                 } else {
1.1164    raeburn  4129:                     if ($attr->{'src'} ne '') {
                   4130:                         $src = $attr->{'src'};
                   4131:                         &add_filetype($allfiles,$src,'src');
                   4132:                     }
                   4133:                 }
                   4134:                 my $text = $p->get_trimmed_text();
                   4135:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4136:                     my @swfargs = split(/,/,$1);
                   4137:                     foreach my $item (@swfargs) {
                   4138:                         $item =~ s/["']//g;
                   4139:                         $item =~ s/^\s+//;
                   4140:                         $item =~ s/\s+$//;
                   4141:                     }
                   4142:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4143:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4144:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4145:                         } else {
                   4146:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4147:                         }
                   4148:                     }
1.645     raeburn  4149:                 }
                   4150:             }
                   4151:             if (lc($tagname) eq 'link') {
                   4152:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4153:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4154:                 }
                   4155:             }
1.640     albertel 4156: 	    if (lc($tagname) eq 'object' ||
                   4157: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4158: 		foreach my $item (keys(%javafiles)) {
                   4159: 		    $javafiles{$item} = '';
                   4160: 		}
1.1164    raeburn  4161:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4162:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4163:                 }
1.640     albertel 4164: 	    }
                   4165: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4166: 		my $name = lc($attr->{'name'});
                   4167: 		foreach my $item (keys(%javafiles)) {
                   4168: 		    if ($name eq $item) {
                   4169: 			$javafiles{$item} = $attr->{'value'};
                   4170: 			last;
                   4171: 		    }
                   4172: 		}
1.1164    raeburn  4173:                 my $pathfrom;
1.640     albertel 4174: 		foreach my $item (keys(%mediafiles)) {
                   4175: 		    if ($name eq $item) {
1.1164    raeburn  4176:                         $pathfrom = $attr->{'value'};
                   4177:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4178: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4179: 			last;
                   4180: 		    }
                   4181: 		}
1.1164    raeburn  4182:                 if ($name eq 'flashvars') {
                   4183:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4184:                 }
                   4185:                 if ($pathfrom ne '') {
                   4186:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4187:                                          $pathfrom);
                   4188:                 }
1.640     albertel 4189: 	    }
                   4190: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4191: 		foreach my $item (keys(%javafiles)) {
                   4192: 		    if ($attr->{$item}) {
                   4193: 			$javafiles{$item} = $attr->{$item};
                   4194: 			last;
                   4195: 		    }
                   4196: 		}
                   4197: 		foreach my $item (keys(%mediafiles)) {
                   4198: 		    if ($attr->{$item}) {
                   4199: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4200: 			last;
                   4201: 		    }
                   4202: 		}
1.1164    raeburn  4203:                 if (lc($tagname) eq 'embed') {
                   4204:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4205:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4206:                                              $attr->{'src'});
                   4207:                     }
                   4208:                 }
1.640     albertel 4209: 	    }
1.1172.2.35  raeburn  4210:             if (lc($tagname) eq 'iframe') {
                   4211:                 my $src = $attr->{'src'} ;
                   4212:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4213:                     &add_filetype($allfiles,$src,'src');
                   4214:                 } elsif ($src =~ m{^/}) {
                   4215:                     if ($env{'request.course.id'}) {
                   4216:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4217:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4218:                         my $url = &hreflocation('',$fullpath);
                   4219:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4220:                             my $relpath = $1;
                   4221:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4222:                                 &add_filetype($allfiles,$1,'src');
                   4223:                             }
                   4224:                         }
                   4225:                     }
                   4226:                 }
                   4227:             }
1.1164    raeburn  4228:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4229:                 pop(@state);
1.1164    raeburn  4230:             }
1.640     albertel 4231: 	} elsif ($t->[0] eq 'E') {
                   4232: 	    my ($tagname) = ($t->[1]);
                   4233: 	    if ($javafiles{'codebase'} ne '') {
                   4234: 		$javafiles{'codebase'} .= '/';
                   4235: 	    }  
                   4236: 	    if (lc($tagname) eq 'applet' ||
                   4237: 		lc($tagname) eq 'object' ||
                   4238: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4239: 		) {
                   4240: 		foreach my $item (keys(%javafiles)) {
                   4241: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4242: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4243: 			&add_filetype($allfiles,$file,$item);
                   4244: 		    }
                   4245: 		}
                   4246: 	    } 
                   4247: 	    pop @state;
                   4248: 	}
                   4249:     }
1.1164    raeburn  4250:     foreach my $id (sort(keys(%flashvars))) {
                   4251:         if ($shockwave{$id} ne '') {
                   4252:             my @pairs = split(/\&/,$flashvars{$id});
                   4253:             foreach my $pair (@pairs) {
                   4254:                 my ($key,$value) = split(/\=/,$pair);
                   4255:                 if ($key eq 'thumb') {
                   4256:                     &add_filetype($allfiles,$value,$key);
                   4257:                 } elsif ($key eq 'content') {
                   4258:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4259:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4260:                     if ($ext ne '') {
                   4261:                         &add_filetype($allfiles,$path.$value,$ext);
                   4262:                     }
                   4263:                 }
                   4264:             }
                   4265:         }
                   4266:     }
1.637     raeburn  4267:     return 'ok';
                   4268: }
                   4269: 
1.639     albertel 4270: sub add_filetype {
                   4271:     my ($allfiles,$file,$type)=@_;
                   4272:     if (exists($allfiles->{$file})) {
                   4273: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4274: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4275: 	}
                   4276:     } else {
                   4277: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4278:     }
                   4279: }
                   4280: 
1.1164    raeburn  4281: sub embedded_dependency {
                   4282:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4283:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4284:         if (($identifier ne '') &&
                   4285:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4286:             ($pathfrom ne '')) {
                   4287:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4288:             foreach my $dep (@{$related->{$identifier}}) {
                   4289:                 &add_filetype($allfiles,$path.$dep,'object');
                   4290:             }
                   4291:         }
                   4292:     }
                   4293:     return;
                   4294: }
                   4295: 
1.1172.2.109  raeburn  4296: sub bubblesheet_converter {
                   4297:     my ($cdom,$fullpath,$config,$format) = @_;
                   4298:     if ((&domain($cdom) ne '') &&
                   4299:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4300:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4301:         my (%csvcols,%csvoptions);
                   4302:         if (ref($config->{'fields'}) eq 'HASH') {
                   4303:             %csvcols = %{$config->{'fields'}};
                   4304:         }
                   4305:         if (ref($config->{'options'}) eq 'HASH') {
                   4306:             %csvoptions = %{$config->{'options'}};
                   4307:         }
                   4308:         my %csvbynum = reverse(%csvcols);
                   4309:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4310:         if (keys(%scantronconf)) {
                   4311:             my %bynum = (
                   4312:                           $scantronconf{CODEstart} => 'CODEstart',
                   4313:                           $scantronconf{IDstart}   => 'IDstart',
                   4314:                           $scantronconf{PaperID}   => 'PaperID',
                   4315:                           $scantronconf{FirstName} => 'FirstName',
                   4316:                           $scantronconf{LastName}  => 'LastName',
                   4317:                           $scantronconf{Qstart}    => 'Qstart',
                   4318:                         );
                   4319:             my @ordered;
                   4320:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4321:                 push(@ordered,$bynum{$item});
                   4322:             }
                   4323:             my %mapstart = (
                   4324:                               CODEstart => 'CODE',
                   4325:                               IDstart   => 'ID',
                   4326:                               PaperID   => 'PaperID',
                   4327:                               FirstName => 'FirstName',
                   4328:                               LastName  => 'LastName',
                   4329:                               Qstart    => 'FirstQuestion',
                   4330:                            );
                   4331:             my %maplength = (
                   4332:                               CODEstart => 'CODElength',
                   4333:                               IDstart   => 'IDlength',
                   4334:                               PaperID   => 'PaperIDlength',
                   4335:                               FirstName => 'FirstNamelength',
                   4336:                               LastName  => 'LastNamelength',
                   4337:             );
                   4338:             if (open(my $fh,'<',$fullpath)) {
                   4339:                 my $output;
                   4340:                 my %lettdig = &letter_to_digits();
                   4341:                 my %diglett = reverse(%lettdig);
                   4342:                 my $numletts = scalar(keys(%lettdig));
                   4343:                 my $num = 0;
                   4344:                 while (my $line=<$fh>) {
                   4345:                     $num ++;
                   4346:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4347:                     $line =~ s{[\r\n]+$}{};
                   4348:                     my %found;
                   4349:                     my @values = split(/,/,$line);
                   4350:                     my ($qstart,$record);
                   4351:                     for (my $i=0; $i<@values; $i++) {
                   4352:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4353:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4354:                             if ($values[$i] eq '') {
                   4355:                                 $values[$i] = $scantronconf{'Qoff'};
                   4356:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4357:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4358:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4359:                                 }
                   4360:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4361:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4362:                                     $values[$i] = $diglett{$values[$i]};
                   4363:                                 }
                   4364:                             } else {
                   4365:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4366:                                     my $digit;
                   4367:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4368:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4369:                                         if ($values[$i] eq 'J') {
                   4370:                                             $digit += $numletts;
                   4371:                                         }
                   4372:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4373:                                         $digit = $values[$i]-1;
                   4374:                                         if ($values[$i] eq '0') {
                   4375:                                             $digit += $numletts;
                   4376:                                         }
                   4377:                                     }
                   4378:                                     my $qval='';
                   4379:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4380:                                         if ($j == $digit) {
                   4381:                                             $qval .= $scantronconf{'Qon'};
                   4382:                                         } else {
                   4383:                                             $qval .= $scantronconf{'Qoff'};
                   4384:                                         }
                   4385:                                     }
                   4386:                                     $values[$i] = $qval;
                   4387:                                 }
                   4388:                             }
                   4389:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4390:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4391:                             }
                   4392:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4393:                             if ($numblank > 0) {
                   4394:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4395:                             }
                   4396:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4397:                                 $qstart = $i;
                   4398:                                 $found{$csvbynum{$i}} = $values[$i];
                   4399:                             } else {
                   4400:                                 $found{'FirstQuestion'} .= $values[$i];
                   4401:                             }
                   4402:                         } elsif (exists($csvbynum{$i})) {
                   4403:                             if ($csvoptions{'rem'}) {
                   4404:                                 $values[$i] =~ s/^\s+//;
                   4405:                             }
                   4406:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4407:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4408:                                     $values[$i] = '0'.$values[$i];
                   4409:                                 }
                   4410:                             }
                   4411:                             $found{$csvbynum{$i}} = $values[$i];
                   4412:                         }
                   4413:                     }
                   4414:                     foreach my $item (@ordered) {
                   4415:                         my $currlength = 1+length($record);
                   4416:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4417:                         if ($numspaces > 0) {
                   4418:                             $record .= (' ' x $numspaces);
                   4419:                         }
                   4420:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4421:                             unless ($item eq 'Qstart') {
                   4422:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4423:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4424:                                 }
                   4425:                             }
                   4426:                             $record .= $found{$mapstart{$item}};
                   4427:                         }
                   4428:                     }
                   4429:                     $output .= "$record\n";
                   4430:                 }
                   4431:                 close($fh);
                   4432:                 if ($output) {
                   4433:                     if (open(my $fh,'>',$fullpath)) {
                   4434:                         print $fh $output;
                   4435:                         close($fh);
                   4436:                     }
                   4437:                 }
                   4438:             }
                   4439:         }
                   4440:         return;
                   4441:     }
                   4442: }
                   4443: 
                   4444: sub letter_to_digits {
                   4445:     my %lettdig = (
                   4446:                     A => 1,
                   4447:                     B => 2,
                   4448:                     C => 3,
                   4449:                     D => 4,
                   4450:                     E => 5,
                   4451:                     F => 6,
                   4452:                     G => 7,
                   4453:                     H => 8,
                   4454:                     I => 9,
                   4455:                     J => 0,
                   4456:                   );
                   4457:     return %lettdig;
                   4458: }
                   4459: 
                   4460: sub get_scantron_config {
                   4461:     my ($which,$cdom) = @_;
                   4462:     my @lines = &get_scantronformat_file($cdom);
                   4463:     my %config;
                   4464:     #FIXME probably should move to XML it has already gotten a bit much now
                   4465:     foreach my $line (@lines) {
                   4466:         my ($name,$descrip)=split(/:/,$line);
                   4467:         if ($name ne $which ) { next; }
                   4468:         chomp($line);
                   4469:         my @config=split(/:/,$line);
                   4470:         $config{'name'}=$config[0];
                   4471:         $config{'description'}=$config[1];
                   4472:         $config{'CODElocation'}=$config[2];
                   4473:         $config{'CODEstart'}=$config[3];
                   4474:         $config{'CODElength'}=$config[4];
                   4475:         $config{'IDstart'}=$config[5];
                   4476:         $config{'IDlength'}=$config[6];
                   4477:         $config{'Qstart'}=$config[7];
                   4478:         $config{'Qlength'}=$config[8];
                   4479:         $config{'Qoff'}=$config[9];
                   4480:         $config{'Qon'}=$config[10];
                   4481:         $config{'PaperID'}=$config[11];
                   4482:         $config{'PaperIDlength'}=$config[12];
                   4483:         $config{'FirstName'}=$config[13];
                   4484:         $config{'FirstNamelength'}=$config[14];
                   4485:         $config{'LastName'}=$config[15];
                   4486:         $config{'LastNamelength'}=$config[16];
                   4487:         $config{'BubblesPerRow'}=$config[17];
                   4488:         last;
                   4489:     }
                   4490:     return %config;
                   4491: }
                   4492: 
                   4493: sub get_scantronformat_file {
                   4494:     my ($cdom) = @_;
                   4495:     if ($cdom eq '') {
                   4496:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4497:     }
                   4498:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4499:     my $gottab = 0;
                   4500:     my @lines;
                   4501:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4502:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4503:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4504:             if ($formatfile ne '-1') {
                   4505:                 @lines = split("\n",$formatfile,-1);
                   4506:                 $gottab = 1;
                   4507:             }
                   4508:         }
                   4509:     }
                   4510:     if (!$gottab) {
                   4511:         my $confname = $cdom.'-domainconfig';
                   4512:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4513:         my $formatfile = &getfile($default);
                   4514:         if ($formatfile ne '-1') {
                   4515:             @lines = split("\n",$formatfile,-1);
                   4516:             $gottab = 1;
                   4517:         }
                   4518:     }
                   4519:     if (!$gottab) {
                   4520:         my @domains = &current_machine_domains();
                   4521:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4522:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4523:                 @lines = <$fh>;
                   4524:                 close($fh);
                   4525:             }
                   4526:         } else {
                   4527:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4528:                 @lines = <$fh>;
                   4529:                 close($fh);
                   4530:             }
                   4531:         }
                   4532:     }
                   4533:     return @lines;
                   4534: }
                   4535: 
1.493     albertel 4536: sub removeuploadedurl {
1.984     neumanie 4537:     my ($url)=@_;	
                   4538:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4539:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4540: }
                   4541: 
                   4542: sub removeuserfile {
                   4543:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4544:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4545:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4546:     if ($result eq 'ok') {	
1.798     raeburn  4547:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4548:             my $metafile = $fname.'.meta';
                   4549:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4550: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4551:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4552:             my $sqlresult = 
1.823     albertel 4553:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4554:                                         'portfolio_metadata',$group,
                   4555:                                         'delete');
1.798     raeburn  4556:         }
                   4557:     }
                   4558:     return $result;
1.257     www      4559: }
1.15      www      4560: 
1.530     albertel 4561: sub mkdiruserfile {
                   4562:     my ($docuname,$docudom,$dir)=@_;
                   4563:     my $home=&homeserver($docuname,$docudom);
                   4564:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4565: }
                   4566: 
1.531     albertel 4567: sub renameuserfile {
                   4568:     my ($docuname,$docudom,$old,$new)=@_;
                   4569:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4570:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4571:                         &escape("$old").':'.&escape("$new"),$home);
                   4572:     if ($result eq 'ok') {
                   4573:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4574:             my $oldmeta = $old.'.meta';
                   4575:             my $newmeta = $new.'.meta';
                   4576:             my $metaresult = 
                   4577:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4578: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4579:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4580:             my $sqlresult = 
1.823     albertel 4581:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4582:                                         'portfolio_metadata',$group,
                   4583:                                         'delete');
1.798     raeburn  4584:         }
                   4585:     }
                   4586:     return $result;
1.531     albertel 4587: }
                   4588: 
1.14      www      4589: # ------------------------------------------------------------------------- Log
                   4590: 
                   4591: sub log {
                   4592:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4593:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4594: }
                   4595: 
                   4596: # ------------------------------------------------------------------ Course Log
1.352     www      4597: #
                   4598: # This routine flushes several buffers of non-mission-critical nature
                   4599: #
1.157     www      4600: 
                   4601: sub flushcourselogs {
1.352     www      4602:     &logthis('Flushing log buffers');
                   4603: #
                   4604: # course logs
                   4605: # This is a log of all transactions in a course, which can be used
                   4606: # for data mining purposes
                   4607: #
                   4608: # It also collects the courseid database, which lists last transaction
                   4609: # times and course titles for all courseids
                   4610: #
                   4611:     my %courseidbuffer=();
1.921     raeburn  4612:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4613:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4614: 		          &escape($courselogs{$crsid}),
                   4615: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4616: 	    delete $courselogs{$crsid};
                   4617:         } else {
                   4618:             &logthis('Failed to flush log buffer for '.$crsid);
                   4619:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4620:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4621:                         " exceeded maximum size, deleting.</font>");
                   4622:                delete $courselogs{$crsid};
                   4623:             }
1.352     www      4624:         }
1.920     raeburn  4625:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4626:             'description' => $coursedescrbuf{$crsid},
                   4627:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4628:             'type'        => $coursetypebuf{$crsid},
                   4629:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4630:         };
1.191     harris41 4631:     }
1.352     www      4632: #
                   4633: # Write course id database (reverse lookup) to homeserver of courses 
                   4634: # Is used in pickcourse
                   4635: #
1.840     albertel 4636:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4637:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4638:                                     $courseidbuffer{$crs_home},
                   4639:                                     $crs_home,'timeonly');
1.352     www      4640:     }
                   4641: #
                   4642: # File accesses
                   4643: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4644: #
1.449     matthew  4645:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4646:         if ($entry =~ /___count$/) {
                   4647:             my ($dom,$name);
1.807     albertel 4648:             ($dom,$name,undef)=
1.811     albertel 4649: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4650:             if (! defined($dom) || $dom eq '' || 
                   4651:                 ! defined($name) || $name eq '') {
1.620     albertel 4652:                 my $cid = $env{'request.course.id'};
                   4653:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4654:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4655:             }
1.450     matthew  4656:             my $value = $accesshash{$entry};
                   4657:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4658:             my %temphash=($url => $value);
1.449     matthew  4659:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4660:             if ($result eq 'ok') {
                   4661:                 delete $accesshash{$entry};
                   4662:             }
                   4663:         } else {
1.811     albertel 4664:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4665:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4666:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4667:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4668:                 delete $accesshash{$entry};
                   4669:             }
1.185     www      4670:         }
1.191     harris41 4671:     }
1.352     www      4672: #
                   4673: # Roles
                   4674: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4675: #
1.800     albertel 4676:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4677:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4678: 	    split(/\:/,$entry);
                   4679:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4680:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4681:                 $rudom,$runame) eq 'ok') {
                   4682: 	    delete $userrolehash{$entry};
                   4683:         }
                   4684:     }
1.662     raeburn  4685: #
1.1172.2.90  raeburn  4686: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4687: #
                   4688:     my %domrolebuffer = ();
1.1000    raeburn  4689:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4690:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4691:         if ($domrolebuffer{$rudom}) {
                   4692:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4693:                       '='.&escape($domainrolehash{$entry});
                   4694:         } else {
                   4695:             $domrolebuffer{$rudom}.=&escape($entry).
                   4696:                       '='.&escape($domainrolehash{$entry});
                   4697:         }
                   4698:         delete $domainrolehash{$entry};
                   4699:     }
                   4700:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4701:         my %servers;
                   4702:         if (defined(&domain($dom,'primary'))) {
                   4703:             my $primary=&domain($dom,'primary');
                   4704:             my $hostname=&hostname($primary);
                   4705:             $servers{$primary} = $hostname;
                   4706:         } else {
                   4707:             %servers = &get_servers($dom,'library');
                   4708:         }
1.841     albertel 4709: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4710: 	    if (&reply('domroleput:'.$dom.':'.
                   4711: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4712: 	        last;
                   4713: 	    } else {
1.841     albertel 4714: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4715: 	    }
1.662     raeburn  4716:         }
                   4717:     }
1.186     www      4718:     $dumpcount++;
1.157     www      4719: }
                   4720: 
                   4721: sub courselog {
                   4722:     my $what=shift;
1.158     www      4723:     $what=time.':'.$what;
1.620     albertel 4724:     unless ($env{'request.course.id'}) { return ''; }
                   4725:     $coursedombuf{$env{'request.course.id'}}=
                   4726:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4727:     $coursenumbuf{$env{'request.course.id'}}=
                   4728:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4729:     $coursehombuf{$env{'request.course.id'}}=
                   4730:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4731:     $coursedescrbuf{$env{'request.course.id'}}=
                   4732:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4733:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4734:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4735:     $courseownerbuf{$env{'request.course.id'}}=
                   4736:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4737:     $coursetypebuf{$env{'request.course.id'}}=
                   4738:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4739:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4740: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4741:     } else {
1.620     albertel 4742: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4743:     }
1.620     albertel 4744:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4745: 	&flushcourselogs();
                   4746:     }
1.158     www      4747: }
                   4748: 
                   4749: sub courseacclog {
                   4750:     my $fnsymb=shift;
1.620     albertel 4751:     unless ($env{'request.course.id'}) { return ''; }
                   4752:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4753:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4754:         $what.=':POST';
1.583     matthew  4755:         # FIXME: Probably ought to escape things....
1.800     albertel 4756: 	foreach my $key (keys(%env)) {
                   4757:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4758:                 my $formitem = $1;
                   4759:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4760:                     $what.=':'.$formitem.'='.$env{$key};
                   4761:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.118.  .12(raeb 4762:-20):                     if ($formitem eq 'proctorpassword') {
                   4763:-20):                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
                   4764:-20):                     } else {
                   4765:-20):                         $what.=':'.$formitem.'='.$env{$key};
                   4766:-20):                     }
1.975     raeburn  4767:                 }
1.158     www      4768:             }
1.191     harris41 4769:         }
1.583     matthew  4770:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4771:         # FIXME: We should not be depending on a form parameter that someone
                   4772:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4773:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4774:             $what.= ':POST';
                   4775:             # FIXME: Probably ought to escape things....
                   4776:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4777:                                  'crsdiscuss') {
1.620     albertel 4778:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4779:             }
                   4780:         }
1.158     www      4781:     }
                   4782:     &courselog($what);
1.149     www      4783: }
                   4784: 
1.185     www      4785: sub countacc {
                   4786:     my $url=&declutter(shift);
1.458     matthew  4787:     return if (! defined($url) || $url eq '');
1.620     albertel 4788:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4789: #
                   4790: # Mark that this url was used in this course
                   4791: #
1.620     albertel 4792:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4793: #
                   4794: # Increase the access count for this resource in this child process
                   4795: #
1.281     www      4796:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4797:     $accesshash{$key}++;
1.185     www      4798: }
1.349     www      4799: 
1.361     www      4800: sub linklog {
                   4801:     my ($from,$to)=@_;
                   4802:     $from=&declutter($from);
                   4803:     $to=&declutter($to);
                   4804:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4805:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4806: }
1.1160    www      4807: 
                   4808: sub statslog {
                   4809:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4810:     if ($users<2) { return; }
                   4811:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4812:             'course'       => $env{'request.course.id'},
                   4813:             'sections'     => '"all"',
                   4814:             'num_students' => $users,
                   4815:             'part'         => $part,
                   4816:             'symb'         => $symb,
                   4817:             'mean_tries'   => $av_attempts,
                   4818:             'deg_of_diff'  => $degdiff});
                   4819:     foreach my $key (keys(%dynstore)) {
                   4820:         $accesshash{$key}=$dynstore{$key};
                   4821:     }
                   4822: }
1.361     www      4823:   
1.349     www      4824: sub userrolelog {
                   4825:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4826:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4827:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4828:        $userrolehash
                   4829:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4830:                     =$tend.':'.$tstart;
1.662     raeburn  4831:     }
1.1169    droeschl 4832:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4833:        $userrolehash
                   4834:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4835:                     =$tend.':'.$tstart;
                   4836:     }
1.1172.2.90  raeburn  4837:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4838:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4839:        $domainrolehash
                   4840:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4841:                     = $tend.':'.$tstart;
                   4842:     }
1.351     www      4843: }
                   4844: 
1.957     raeburn  4845: sub courserolelog {
                   4846:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4847:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4848:         my $cdom = $1;
                   4849:         my $cnum = $2;
                   4850:         my $sec = $3;
                   4851:         my $namespace = 'rolelog';
                   4852:         my %storehash = (
                   4853:                            role    => $trole,
                   4854:                            start   => $tstart,
                   4855:                            end     => $tend,
                   4856:                            selfenroll => $selfenroll,
                   4857:                            context    => $context,
                   4858:                         );
                   4859:         if ($trole eq 'gr') {
                   4860:             $namespace = 'groupslog';
                   4861:             $storehash{'group'} = $sec;
                   4862:         } else {
                   4863:             $storehash{'section'} = $sec;
                   4864:         }
                   4865:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4866:                    $domain,$cnum,$cdom);
                   4867:         if (($trole ne 'st') || ($sec ne '')) {
                   4868:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4869:         }
                   4870:     }
                   4871:     return;
                   4872: }
                   4873: 
1.1172.2.9  raeburn  4874: sub domainrolelog {
                   4875:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4876:     if ($area =~ m{^/($match_domain)/$}) {
                   4877:         my $cdom = $1;
                   4878:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4879:         my $namespace = 'rolelog';
                   4880:         my %storehash = (
                   4881:                            role    => $trole,
                   4882:                            start   => $tstart,
                   4883:                            end     => $tend,
                   4884:                            context => $context,
                   4885:                         );
                   4886:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4887:                    $domain,$domconfiguser,$cdom);
                   4888:     }
                   4889:     return;
                   4890: 
                   4891: }
                   4892: 
                   4893: sub coauthorrolelog {
                   4894:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4895:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4896:         my $audom = $1;
                   4897:         my $auname = $2;
                   4898:         my $namespace = 'rolelog';
                   4899:         my %storehash = (
                   4900:                            role    => $trole,
                   4901:                            start   => $tstart,
                   4902:                            end     => $tend,
                   4903:                            context => $context,
                   4904:                         );
                   4905:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4906:                    $domain,$auname,$audom);
                   4907:     }
                   4908:     return;
                   4909: }
                   4910: 
1.351     www      4911: sub get_course_adv_roles {
1.948     raeburn  4912:     my ($cid,$codes) = @_;
1.620     albertel 4913:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4914:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4915:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4916:     my %nothide=();
1.800     albertel 4917:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4918:         if ($user !~ /:/) {
                   4919: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4920:         } else {
                   4921:             $nothide{$user}=1;
                   4922:         }
1.470     www      4923:     }
1.1172.2.23  raeburn  4924:     my @possdoms = ($coursehash{'domain'});
                   4925:     if ($coursehash{'checkforpriv'}) {
                   4926:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4927:     }
1.351     www      4928:     my %returnhash=();
                   4929:     my %dumphash=
                   4930:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4931:     my $now=time;
1.997     raeburn  4932:     my %privileged;
1.1000    raeburn  4933:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4934: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4935:         if (($tstart) && ($tstart<0)) { next; }
                   4936:         if (($tend) && ($tend<$now)) { next; }
                   4937:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4938:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4939: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4940:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4941:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4942: 	if ($role eq 'cr') { next; }
1.948     raeburn  4943:         if ($codes) {
                   4944:             if ($section) { $role .= ':'.$section; }
                   4945:             if ($returnhash{$role}) {
                   4946:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4947:             } else {
                   4948:                 $returnhash{$role}=$username.':'.$domain;
                   4949:             }
1.351     www      4950:         } else {
1.988     raeburn  4951:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4952:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4953:             if ($returnhash{$key}) {
                   4954: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4955:             } else {
                   4956:                 $returnhash{$key}=$username.':'.$domain;
                   4957:             }
1.351     www      4958:         }
1.948     raeburn  4959:     }
1.400     www      4960:     return %returnhash;
                   4961: }
                   4962: 
                   4963: sub get_my_roles {
1.937     raeburn  4964:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4965:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4966:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4967:     my (%dumphash,%nothide);
1.1086    raeburn  4968:     if ($context eq 'userroles') {
1.1166    raeburn  4969:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4970:     } else {
1.1172.2.23  raeburn  4971:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4972:         if ($hidepriv) {
                   4973:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4974:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4975:                 if ($user !~ /:/) {
                   4976:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4977:                 } else {
                   4978:                     $nothide{$user} = 1;
                   4979:                 }
                   4980:             }
                   4981:         }
1.858     raeburn  4982:     }
1.400     www      4983:     my %returnhash=();
                   4984:     my $now=time;
1.999     raeburn  4985:     my %privileged;
1.800     albertel 4986:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4987:         my ($role,$tend,$tstart);
                   4988:         if ($context eq 'userroles') {
1.1149    raeburn  4989:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4990: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4991:         } else {
                   4992:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4993:         }
1.400     www      4994:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4995:         my $status = 'active';
1.939     raeburn  4996:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4997:             $status = 'previous';
                   4998:         } 
                   4999:         if (($tstart) && ($now<$tstart)) {
                   5000:             $status = 'future';
                   5001:         }
                   5002:         if (ref($types) eq 'ARRAY') {
                   5003:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5004:                 next;
                   5005:             } 
                   5006:         } else {
                   5007:             if ($status ne 'active') {
                   5008:                 next;
                   5009:             }
                   5010:         }
1.867     raeburn  5011:         my ($rolecode,$username,$domain,$section,$area);
                   5012:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5013:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5014:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5015:         } else {
                   5016:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5017:         }
1.832     raeburn  5018:         if (ref($roledoms) eq 'ARRAY') {
                   5019:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5020:                 next;
                   5021:             }
                   5022:         }
                   5023:         if (ref($roles) eq 'ARRAY') {
                   5024:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5025:                 if ($role =~ /^cr\//) {
                   5026:                     if (!grep(/^cr$/,@{$roles})) {
                   5027:                         next;
                   5028:                     }
1.1104    raeburn  5029:                 } elsif ($role =~ /^gr\//) {
                   5030:                     if (!grep(/^gr$/,@{$roles})) {
                   5031:                         next;
                   5032:                     }
1.922     raeburn  5033:                 } else {
                   5034:                     next;
                   5035:                 }
1.832     raeburn  5036:             }
1.867     raeburn  5037:         }
1.937     raeburn  5038:         if ($hidepriv) {
1.1172.2.23  raeburn  5039:             my @privroles = ('dc','su');
1.999     raeburn  5040:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5041:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5042:             } else {
1.1172.2.23  raeburn  5043:                 my $possdoms = [$domain];
                   5044:                 if (ref($roledoms) eq 'ARRAY') {
                   5045:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5046:                 }
1.1172.2.23  raeburn  5047:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5048:                     if (!$nothide{$username.':'.$domain}) {
                   5049:                         next;
                   5050:                     }
                   5051:                 }
1.937     raeburn  5052:             }
                   5053:         }
1.933     raeburn  5054:         if ($withsec) {
                   5055:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5056:                 $tstart.':'.$tend;
                   5057:         } else {
                   5058:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5059:         }
1.832     raeburn  5060:     }
1.373     www      5061:     return %returnhash;
1.399     www      5062: }
                   5063: 
1.1172.2.89  raeburn  5064: sub get_all_adhocroles {
                   5065:     my ($dom) = @_;
                   5066:     my @roles_by_num = ();
                   5067:     my %domdefaults = &get_domain_defaults($dom);
                   5068:     my (%description,%access_in_dom,%access_info);
                   5069:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5070:         my $count = 0;
                   5071:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5072:         my %ordered;
                   5073:         foreach my $role (sort(keys(%domcurrent))) {
                   5074:             my ($order,$desc,$access_in_dom);
                   5075:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5076:                 $order = $domcurrent{$role}{'order'};
                   5077:                 $desc = $domcurrent{$role}{'desc'};
                   5078:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5079:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5080:             }
                   5081:             if ($order eq '') {
                   5082:                 $order = $count;
                   5083:             }
                   5084:             $ordered{$order} = $role;
                   5085:             if ($desc ne '') {
                   5086:                 $description{$role} = $desc;
                   5087:             } else {
                   5088:                 $description{$role}= $role;
                   5089:             }
                   5090:             $count++;
                   5091:         }
                   5092:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5093:             push(@roles_by_num,$ordered{$item});
                   5094:         }
                   5095:     }
                   5096:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5097: }
                   5098: 
                   5099: sub get_my_adhocroles {
                   5100:     my ($cid,$checkreg) = @_;
                   5101:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5102:     if ($env{'request.course.id'} eq $cid) {
                   5103:         $cdom = $env{'course.'.$cid.'.domain'};
                   5104:         $cnum = $env{'course.'.$cid.'.num'};
                   5105:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5106:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5107:         $cdom = $1;
                   5108:         $cnum = $2;
                   5109:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5110:                                      $cdom,$cnum);
                   5111:     }
                   5112:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5113:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5114:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5115:         if ($rosterhash{$user} ne '') {
                   5116:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5117:             return ([],{}) if ($type eq 'auto');
                   5118:         }
                   5119:     }
                   5120:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5121:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5122:             my $then=$env{'user.login.time'};
                   5123:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5124:             if (!$update) {
                   5125:                 $update = $then;
                   5126:             }
                   5127:             my @liveroles;
                   5128:             foreach my $role ('dh','da') {
                   5129:                 if ($env{"user.role.$role./$cdom/"}) {
                   5130:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5131:                     my $limit = $update;
                   5132:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5133:                         $limit = $then;
                   5134:                     }
                   5135:                     my $activerole = 1;
                   5136:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5137:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5138:                     if ($activerole) {
                   5139:                         push(@liveroles,$role);
                   5140:                     }
                   5141:                 }
                   5142:             }
                   5143:             if (@liveroles) {
1.1172.2.89  raeburn  5144:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5145:                     my ($accessref,$accessinfo,%access_in_dom);
                   5146:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5147:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5148:                         if (@{$roles_by_num}) {
                   5149:                             my %settings;
                   5150:                             if ($env{'request.course.id'} eq $cid) {
                   5151:                                 foreach my $envkey (keys(%env)) {
                   5152:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5153:                                         $settings{$1} = $env{$envkey};
                   5154:                                     }
                   5155:                                 }
                   5156:                             } else {
                   5157:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5158:                             }
                   5159:                             my %setincrs;
                   5160:                             if ($settings{'internal.adhocaccess'}) {
                   5161:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5162:                             }
                   5163:                             my @statuses;
                   5164:                             if ($env{'environment.inststatus'}) {
                   5165:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5166:                             }
                   5167:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5168:                             if (ref($accessref) eq 'HASH') {
                   5169:                                 %access_in_dom = %{$accessref};
                   5170:                             }
                   5171:                             foreach my $role (@{$roles_by_num}) {
                   5172:                                 my ($curraccess,@okstatus,@personnel);
                   5173:                                 if ($setincrs{$role}) {
                   5174:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5175:                                     if ($curraccess eq 'status') {
                   5176:                                         @okstatus = split(/\&/,$rest);
                   5177:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5178:                                         @personnel = split(/\&/,$rest);
                   5179:                                     }
                   5180:                                 } else {
                   5181:                                     $curraccess = $access_in_dom{$role};
                   5182:                                     if (ref($accessinfo) eq 'HASH') {
                   5183:                                         if ($curraccess eq 'status') {
                   5184:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5185:                                                 @okstatus = @{$accessinfo->{$role}};
                   5186:                                             }
                   5187:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5188:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5189:                                                 @personnel = @{$accessinfo->{$role}};
                   5190:                                             }
                   5191:                                         }
                   5192:                                     }
                   5193:                                 }
                   5194:                                 if ($curraccess eq 'none') {
                   5195:                                     next;
                   5196:                                 } elsif ($curraccess eq 'all') {
                   5197:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5198:                                 } elsif ($curraccess eq 'dh') {
                   5199:                                     if (grep(/^dh$/,@liveroles)) {
                   5200:                                         push(@possroles,$role);
                   5201:                                     } else {
                   5202:                                         next;
                   5203:                                     }
                   5204:                                 } elsif ($curraccess eq 'da') {
                   5205:                                     if (grep(/^da$/,@liveroles)) {
                   5206:                                         push(@possroles,$role);
                   5207:                                     } else {
                   5208:                                         next;
                   5209:                                     }
1.1172.2.89  raeburn  5210:                                 } elsif ($curraccess eq 'status') {
                   5211:                                     if (@okstatus) {
                   5212:                                         if (!@statuses) {
                   5213:                                             if (grep(/^default$/,@okstatus)) {
                   5214:                                                 push(@possroles,$role);
                   5215:                                             }
                   5216:                                         } else {
                   5217:                                             foreach my $status (@okstatus) {
                   5218:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5219:                                                     push(@possroles,$role);
                   5220:                                                     last;
                   5221:                                                 }
                   5222:                                             }
                   5223:                                         }
                   5224:                                     }
                   5225:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5226:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5227:                                         if ($curraccess eq 'exc') {
                   5228:                                             push(@possroles,$role);
                   5229:                                         }
                   5230:                                     } elsif ($curraccess eq 'inc') {
                   5231:                                         push(@possroles,$role);
                   5232:                                     }
                   5233:                                 }
                   5234:                             }
                   5235:                         }
                   5236:                     }
                   5237:                 }
                   5238:             }
                   5239:         }
                   5240:     }
                   5241:     unless (ref($description) eq 'HASH') {
                   5242:         if (ref($roles_by_num) eq 'ARRAY') {
                   5243:             my %desc;
                   5244:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5245:             $description = \%desc;
                   5246:         } else {
                   5247:             $description = {};
                   5248:         }
                   5249:     }
                   5250:     return (\@possroles,$description);
                   5251: }
                   5252: 
1.399     www      5253: # ----------------------------------------------------- Frontpage Announcements
                   5254: #
                   5255: #
                   5256: 
                   5257: sub postannounce {
                   5258:     my ($server,$text)=@_;
1.844     albertel 5259:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5260:     unless ($text=~/\w/) { $text=''; }
                   5261:     return &reply('setannounce:'.&escape($text),$server);
                   5262: }
                   5263: 
                   5264: sub getannounce {
1.448     albertel 5265: 
1.1172.2.96  raeburn  5266:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5267: 	my $announcement='';
1.800     albertel 5268: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5269: 	close($fh);
1.399     www      5270: 	if ($announcement=~/\w/) { 
                   5271: 	    return 
                   5272:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5273:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5274: 	} else {
                   5275: 	    return '';
                   5276: 	}
                   5277:     } else {
                   5278: 	return '';
                   5279:     }
1.351     www      5280: }
1.353     www      5281: 
                   5282: # ---------------------------------------------------------- Course ID routines
                   5283: # Deal with domain's nohist_courseid.db files
                   5284: #
                   5285: 
                   5286: sub courseidput {
1.921     raeburn  5287:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5288:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5289:     my $outcome;
                   5290:     if ($caller eq 'timeonly') {
                   5291:         my $cids = '';
                   5292:         foreach my $item (keys(%$storehash)) {
                   5293:             $cids.=&escape($item).'&';
                   5294:         }
                   5295:         $cids=~s/\&$//;
                   5296:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5297:                           $coursehome);       
                   5298:     } else {
                   5299:         my $items = '';
                   5300:         foreach my $item (keys(%$storehash)) {
                   5301:             $items.= &escape($item).'='.
                   5302:                      &freeze_escape($$storehash{$item}).'&';
                   5303:         }
                   5304:         $items=~s/\&$//;
                   5305:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5306:                           $coursehome);
1.918     raeburn  5307:     }
                   5308:     if ($outcome eq 'unknown_cmd') {
                   5309:         my $what;
                   5310:         foreach my $cid (keys(%$storehash)) {
                   5311:             $what .= &escape($cid).'=';
1.921     raeburn  5312:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5313:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5314:             }
                   5315:             $what =~ s/\:$/&/;
                   5316:         }
                   5317:         $what =~ s/\&$//;  
                   5318:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5319:     } else {
                   5320:         return $outcome;
                   5321:     }
1.353     www      5322: }
                   5323: 
                   5324: sub courseiddump {
1.921     raeburn  5325:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5326:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5327:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5328:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5329:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5330:     my $as_hash = 1;
                   5331:     my %returnhash;
                   5332:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5333:     my %libserv = &all_library();
                   5334:     foreach my $tryserver (keys(%libserv)) {
                   5335:         if ( (  $hostidflag == 1 
                   5336: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5337: 	     || (!defined($hostidflag)) ) {
                   5338: 
1.918     raeburn  5339: 	    if (($domfilter eq '') ||
                   5340: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5341:                 my $rep;
                   5342:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5343:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5344:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5345:                                 &escape($descfilter), &escape($instcodefilter),
                   5346:                                 &escape($ownerfilter), &escape($coursefilter),
                   5347:                                 &escape($typefilter), &escape($regexp_ok),
                   5348:                                 $as_hash, &escape($selfenrollonly),
                   5349:                                 &escape($catfilter), $showhidden, $caller,
                   5350:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5351:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5352:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5353:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5354:                 } else {
                   5355:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5356:                              $sincefilter.':'.&escape($descfilter).':'.
                   5357:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5358:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5359:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5360:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5361:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5362:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5363:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5364:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5365:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5366:                 }
                   5367: 
1.918     raeburn  5368:                 my @pairs=split(/\&/,$rep);
                   5369:                 foreach my $item (@pairs) {
                   5370:                     my ($key,$value)=split(/\=/,$item,2);
                   5371:                     $key = &unescape($key);
                   5372:                     next if ($key =~ /^error: 2 /);
                   5373:                     my $result = &thaw_unescape($value);
                   5374:                     if (ref($result) eq 'HASH') {
                   5375:                         $returnhash{$key}=$result;
                   5376:                     } else {
1.921     raeburn  5377:                         my @responses = split(/:/,$value);
                   5378:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5379:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5380:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5381:                         }
1.1008    raeburn  5382:                     }
1.353     www      5383:                 }
                   5384:             }
                   5385:         }
                   5386:     }
                   5387:     return %returnhash;
                   5388: }
                   5389: 
1.1055    raeburn  5390: sub courselastaccess {
                   5391:     my ($cdom,$cnum,$hostidref) = @_;
                   5392:     my %returnhash;
                   5393:     if ($cdom && $cnum) {
                   5394:         my $chome = &homeserver($cnum,$cdom);
                   5395:         if ($chome ne 'no_host') {
                   5396:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5397:             &extract_lastaccess(\%returnhash,$rep);
                   5398:         }
                   5399:     } else {
                   5400:         if (!$cdom) { $cdom=''; }
                   5401:         my %libserv = &all_library();
                   5402:         foreach my $tryserver (keys(%libserv)) {
                   5403:             if (ref($hostidref) eq 'ARRAY') {
                   5404:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5405:             } 
                   5406:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5407:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5408:                 &extract_lastaccess(\%returnhash,$rep);
                   5409:             }
                   5410:         }
                   5411:     }
                   5412:     return %returnhash;
                   5413: }
                   5414: 
                   5415: sub extract_lastaccess {
                   5416:     my ($returnhash,$rep) = @_;
                   5417:     if (ref($returnhash) eq 'HASH') {
                   5418:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5419:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5420:                  $rep eq '') {
                   5421:             my @pairs=split(/\&/,$rep);
                   5422:             foreach my $item (@pairs) {
                   5423:                 my ($key,$value)=split(/\=/,$item,2);
                   5424:                 $key = &unescape($key);
                   5425:                 next if ($key =~ /^error: 2 /);
                   5426:                 $returnhash->{$key} = &thaw_unescape($value);
                   5427:             }
                   5428:         }
                   5429:     }
                   5430:     return;
                   5431: }
                   5432: 
1.658     raeburn  5433: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5434: 
                   5435: sub dcmailput {
1.685     raeburn  5436:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5437:     my $status = &Apache::lonnet::critical(
1.740     www      5438:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5439:        &escape($message),$server);
1.662     raeburn  5440:     return $status;
                   5441: }
                   5442: 
1.658     raeburn  5443: sub dcmaildump {
                   5444:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5445:     my %returnhash=();
1.846     albertel 5446: 
                   5447:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5448:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5449:                                                          &escape($enddate).':';
                   5450: 	my @esc_senders=map { &escape($_)} @$senders;
                   5451: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5452: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5453:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5454:             if (($key) && ($value)) {
                   5455:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5456:             }
                   5457:         }
                   5458:     }
                   5459:     return %returnhash;
                   5460: }
1.662     raeburn  5461: # ---------------------------------------------------------- Domain roles
                   5462: 
                   5463: sub get_domain_roles {
                   5464:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5465:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5466:         $startdate = '.';
                   5467:     }
1.1018    raeburn  5468:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5469:         $enddate = '.';
                   5470:     }
1.922     raeburn  5471:     my $rolelist;
                   5472:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5473:         $rolelist = join('&',@{$roles});
1.922     raeburn  5474:     }
1.662     raeburn  5475:     my %personnel = ();
1.841     albertel 5476: 
                   5477:     my %servers = &get_servers($dom,'library');
                   5478:     foreach my $tryserver (keys(%servers)) {
                   5479: 	%{$personnel{$tryserver}}=();
                   5480: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5481: 					    &escape($startdate).':'.
                   5482: 					    &escape($enddate).':'.
                   5483: 					    &escape($rolelist), $tryserver))) {
                   5484: 	    my ($key,$value) = split(/\=/,$line,2);
                   5485: 	    if (($key) && ($value)) {
                   5486: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5487: 	    }
                   5488: 	}
1.662     raeburn  5489:     }
                   5490:     return %personnel;
                   5491: }
1.658     raeburn  5492: 
1.1172.2.89  raeburn  5493: sub get_active_domroles {
                   5494:     my ($dom,$roles) = @_;
                   5495:     return () unless (ref($roles) eq 'ARRAY');
                   5496:     my $now = time;
                   5497:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5498:     my %domroles;
                   5499:     foreach my $server (keys(%dompersonnel)) {
                   5500:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5501:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5502:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5503:         }
                   5504:     }
                   5505:     return %domroles;
                   5506: }
                   5507: 
1.1057    www      5508: # ----------------------------------------------------------- Interval timing 
1.149     www      5509: 
1.1153    www      5510: {
                   5511: # Caches needed for speedup of navmaps
                   5512: # We don't want to cache this for very long at all (5 seconds at most)
                   5513: # 
                   5514: # The user for whom we cache
                   5515: my $cachedkey='';
                   5516: # The cached times for this user
                   5517: my %cachedtimes=();
                   5518: # When this was last done
1.1172.2.66  raeburn  5519: my $cachedtime='';
1.1153    www      5520: 
                   5521: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5522:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5523:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5524:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5525:20):         (!$ignorecache)) {
1.1154    raeburn  5526:         return;
                   5527:     }
                   5528:     $cachedtime=time;
                   5529:     $cachedkey=$uname.':'.$udom;
                   5530:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5531: }
                   5532: 
1.504     albertel 5533: sub get_first_access {
1.1172.2.118.  .1(raebu 5534:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5535:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5536:     if ($argsymb) { $symb=$argsymb; }
                   5537:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5538:     if ($argmap) { $map = $argmap; }
1.926     albertel 5539:     if ($type eq 'course') {
                   5540: 	$res='course';
                   5541:     } elsif ($type eq 'map') {
1.588     albertel 5542: 	$res=&symbread($map);
                   5543:     } else {
                   5544: 	$res=$symb;
                   5545:     }
1.1172.2.118.  .1(raebu 5546:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5547:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5548: }
                   5549: 
                   5550: sub set_first_access {
1.1162    raeburn  5551:     my ($type,$interval)=@_;
1.790     albertel 5552:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5553:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5554:     if ($type eq 'course') {
                   5555: 	$res='course';
                   5556:     } elsif ($type eq 'map') {
1.588     albertel 5557: 	$res=&symbread($map);
                   5558:     } else {
                   5559: 	$res=$symb;
                   5560:     }
1.1153    www      5561:     $cachedkey='';
1.1162    raeburn  5562:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5563:     if ($firstaccess) {
                   5564:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5565:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5566:                  "in $courseid");
                   5567:         return 'already_set';
                   5568:     } else {
1.1162    raeburn  5569:         my $start = time;
                   5570: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5571:                           $udom,$uname);
                   5572:         if ($putres eq 'ok') {
                   5573:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5574:                  $udom,$uname); 
                   5575:             &appenv(
                   5576:                      {
                   5577:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5578:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5579:                      }
                   5580:                   );
1.1172.2.97  raeburn  5581:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5582:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5583:             }
1.1172.2.102  raeburn  5584:         } elsif ($putres ne 'refused') {
                   5585:             &logthis("Result: $putres when attempting to set first access time ".
                   5586:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5587:         }
                   5588:         return $putres;
1.505     albertel 5589:     }
                   5590:     return 'already_set';
1.504     albertel 5591: }
1.1153    www      5592: }
1.1172.2.32  raeburn  5593: 
                   5594: sub checkout {
                   5595:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5596:     my $now=time;
                   5597:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.118.  .14(raeb 5598:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5599:     my $infostr=&escape(
                   5600:                  'CHECKOUTTOKEN&'.
                   5601:                  $tuname.'&'.
                   5602:                  $tudom.'&'.
                   5603:                  $tcrsid.'&'.
                   5604:                  $symb.'&'.
1.1172.2.118.  .14(raeb 5605:-21):                  $now.'&'.$ip);
1.1172.2.32  raeburn  5606:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5607:     if ($token=~/^error\:/) {
                   5608:         &logthis("<font color=\"blue\">WARNING: ".
                   5609:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5610:                  "</font>");
                   5611:         return '';
                   5612:     }
                   5613: 
                   5614:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5615:     $token=~tr/a-z/A-Z/;
                   5616: 
                   5617:     my %infohash=('resource.0.outtoken' => $token,
                   5618:                   'resource.0.checkouttime' => $now,
1.1172.2.118.  .14(raeb 5619:-21):                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5620: 
                   5621:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5622:        return '';
                   5623:     } else {
                   5624:         &logthis("<font color=\"blue\">WARNING: ".
                   5625:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5626:                  "</font>");
                   5627:     }
                   5628: 
                   5629:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5630:                          &escape('Checkout '.$infostr.' - '.
                   5631:                                                  $token)) ne 'ok') {
                   5632:         return '';
                   5633:     } else {
                   5634:         &logthis("<font color=\"blue\">WARNING: ".
                   5635:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5636:                  "</font>");
                   5637:     }
                   5638:     return $token;
                   5639: }
                   5640: 
                   5641: # ------------------------------------------------------------ Check in an item
                   5642: 
                   5643: sub checkin {
                   5644:     my $token=shift;
                   5645:     my $now=time;
                   5646:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5647:     $lonhost=~tr/A-Z/a-z/;
                   5648:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5649:     $dtoken=~s/\W/\_/g;
1.1172.2.118.  .14(raeb 5650:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5651:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5652:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5653: 
                   5654:     unless (($tuname) && ($tudom)) {
                   5655:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5656:         return '';
                   5657:     }
                   5658: 
                   5659:     unless (&allowed('mgr',$tcrsid)) {
                   5660:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5661:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5662:         return '';
                   5663:     }
                   5664: 
                   5665:     my %infohash=('resource.0.intoken' => $token,
                   5666:                   'resource.0.checkintime' => $now,
1.1172.2.118.  .14(raeb 5667:-21):                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5668: 
                   5669:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5670:        return '';
                   5671:     }
                   5672: 
                   5673:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5674:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5675:         return '';
                   5676:     }
                   5677: 
                   5678:     return ($symb,$tuname,$tudom,$tcrsid);
                   5679: }
                   5680: 
1.110     www      5681: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5682: 
                   5683: sub expirespread {
                   5684:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5685:     my $cid=$env{'request.course.id'}; 
1.110     www      5686:     if ($cid) {
                   5687:        my $now=time;
                   5688:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5689:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5690:                             $env{'course.'.$cid.'.num'}.
1.110     www      5691: 	        	    ':nohist_expirationdates:'.
                   5692:                             &escape($key).'='.$now,
1.620     albertel 5693:                             $env{'course.'.$cid.'.home'})
1.110     www      5694:     }
                   5695:     return 'ok';
1.14      www      5696: }
                   5697: 
1.109     www      5698: # ----------------------------------------------------- Devalidate Spreadsheets
                   5699: 
                   5700: sub devalidate {
1.325     www      5701:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5702:     my $cid=$env{'request.course.id'}; 
1.109     www      5703:     if ($cid) {
1.391     matthew  5704:         # delete the stored spreadsheets for
                   5705:         # - the student level sheet of this user in course's homespace
                   5706:         # - the assessment level sheet for this resource 
                   5707:         #   for this user in user's homespace
1.553     albertel 5708: 	# - current conditional state info
1.325     www      5709: 	my $key=$uname.':'.$udom.':';
1.109     www      5710:         my $status=
1.299     matthew  5711: 	    &del('nohist_calculatedsheets',
1.391     matthew  5712: 		 [$key.'studentcalc:'],
1.620     albertel 5713: 		 $env{'course.'.$cid.'.domain'},
                   5714: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5715: 		.' '.
                   5716: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5717: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5718:         unless ($status eq 'ok ok') {
                   5719:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5720:                     $uname.' at '.$udom.' for '.
1.109     www      5721: 		    $symb.': '.$status);
1.133     albertel 5722:         }
1.553     albertel 5723: 	&delenv('user.state.'.$cid);
1.109     www      5724:     }
                   5725: }
                   5726: 
1.265     albertel 5727: sub get_scalar {
                   5728:     my ($string,$end) = @_;
                   5729:     my $value;
                   5730:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5731: 	$value = $1;
                   5732:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5733: 	$value = $1;
                   5734:     }
                   5735:     return &unescape($value);
                   5736: }
                   5737: 
                   5738: sub array2str {
                   5739:   my (@array) = @_;
                   5740:   my $result=&arrayref2str(\@array);
                   5741:   $result=~s/^__ARRAY_REF__//;
                   5742:   $result=~s/__END_ARRAY_REF__$//;
                   5743:   return $result;
                   5744: }
                   5745: 
1.204     albertel 5746: sub arrayref2str {
                   5747:   my ($arrayref) = @_;
1.265     albertel 5748:   my $result='__ARRAY_REF__';
1.204     albertel 5749:   foreach my $elem (@$arrayref) {
1.265     albertel 5750:     if(ref($elem) eq 'ARRAY') {
                   5751:       $result.=&arrayref2str($elem).'&';
                   5752:     } elsif(ref($elem) eq 'HASH') {
                   5753:       $result.=&hashref2str($elem).'&';
                   5754:     } elsif(ref($elem)) {
                   5755:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5756:     } else {
                   5757:       $result.=&escape($elem).'&';
                   5758:     }
                   5759:   }
                   5760:   $result=~s/\&$//;
1.265     albertel 5761:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5762:   return $result;
                   5763: }
                   5764: 
1.168     albertel 5765: sub hash2str {
1.204     albertel 5766:   my (%hash) = @_;
                   5767:   my $result=&hashref2str(\%hash);
1.265     albertel 5768:   $result=~s/^__HASH_REF__//;
                   5769:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5770:   return $result;
                   5771: }
                   5772: 
                   5773: sub hashref2str {
                   5774:   my ($hashref)=@_;
1.265     albertel 5775:   my $result='__HASH_REF__';
1.800     albertel 5776:   foreach my $key (sort(keys(%$hashref))) {
                   5777:     if (ref($key) eq 'ARRAY') {
                   5778:       $result.=&arrayref2str($key).'=';
                   5779:     } elsif (ref($key) eq 'HASH') {
                   5780:       $result.=&hashref2str($key).'=';
                   5781:     } elsif (ref($key)) {
1.265     albertel 5782:       $result.='=';
1.800     albertel 5783:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5784:     } else {
1.1132    raeburn  5785: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5786:     }
                   5787: 
1.800     albertel 5788:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5789:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5790:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5791:       $result.=&hashref2str($hashref->{$key}).'&';
                   5792:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5793:        $result.='&';
1.800     albertel 5794:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5795:     } else {
1.800     albertel 5796:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5797:     }
                   5798:   }
1.168     albertel 5799:   $result=~s/\&$//;
1.265     albertel 5800:   $result .= '__END_HASH_REF__';
1.168     albertel 5801:   return $result;
                   5802: }
                   5803: 
                   5804: sub str2hash {
1.265     albertel 5805:     my ($string)=@_;
                   5806:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5807:     return %$hash;
                   5808: }
                   5809: 
                   5810: sub str2hashref {
1.168     albertel 5811:   my ($string) = @_;
1.265     albertel 5812: 
                   5813:   my %hash;
                   5814: 
                   5815:   if($string !~ /^__HASH_REF__/) {
                   5816:       if (! ($string eq '' || !defined($string))) {
                   5817: 	  $hash{'error'}='Not hash reference';
                   5818:       }
                   5819:       return (\%hash, $string);
                   5820:   }
                   5821: 
                   5822:   $string =~ s/^__HASH_REF__//;
                   5823: 
                   5824:   while($string !~ /^__END_HASH_REF__/) {
                   5825:       #key
                   5826:       my $key='';
                   5827:       if($string =~ /^__HASH_REF__/) {
                   5828:           ($key, $string)=&str2hashref($string);
                   5829:           if(defined($key->{'error'})) {
                   5830:               $hash{'error'}='Bad data';
                   5831:               return (\%hash, $string);
                   5832:           }
                   5833:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5834:           ($key, $string)=&str2arrayref($string);
                   5835:           if($key->[0] eq 'Array reference error') {
                   5836:               $hash{'error'}='Bad data';
                   5837:               return (\%hash, $string);
                   5838:           }
                   5839:       } else {
                   5840:           $string =~ s/^(.*?)=//;
1.267     albertel 5841: 	  $key=&unescape($1);
1.265     albertel 5842:       }
                   5843:       $string =~ s/^=//;
                   5844: 
                   5845:       #value
                   5846:       my $value='';
                   5847:       if($string =~ /^__HASH_REF__/) {
                   5848:           ($value, $string)=&str2hashref($string);
                   5849:           if(defined($value->{'error'})) {
                   5850:               $hash{'error'}='Bad data';
                   5851:               return (\%hash, $string);
                   5852:           }
                   5853:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5854:           ($value, $string)=&str2arrayref($string);
                   5855:           if($value->[0] eq 'Array reference error') {
                   5856:               $hash{'error'}='Bad data';
                   5857:               return (\%hash, $string);
                   5858:           }
                   5859:       } else {
                   5860: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5861:       }
                   5862:       $string =~ s/^&//;
                   5863: 
                   5864:       $hash{$key}=$value;
1.204     albertel 5865:   }
1.265     albertel 5866: 
                   5867:   $string =~ s/^__END_HASH_REF__//;
                   5868: 
                   5869:   return (\%hash, $string);
1.204     albertel 5870: }
                   5871: 
                   5872: sub str2array {
1.265     albertel 5873:     my ($string)=@_;
                   5874:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5875:     return @$array;
                   5876: }
                   5877: 
                   5878: sub str2arrayref {
1.204     albertel 5879:   my ($string) = @_;
1.265     albertel 5880:   my @array;
                   5881: 
                   5882:   if($string !~ /^__ARRAY_REF__/) {
                   5883:       if (! ($string eq '' || !defined($string))) {
                   5884: 	  $array[0]='Array reference error';
                   5885:       }
                   5886:       return (\@array, $string);
                   5887:   }
                   5888: 
                   5889:   $string =~ s/^__ARRAY_REF__//;
                   5890: 
                   5891:   while($string !~ /^__END_ARRAY_REF__/) {
                   5892:       my $value='';
                   5893:       if($string =~ /^__HASH_REF__/) {
                   5894:           ($value, $string)=&str2hashref($string);
                   5895:           if(defined($value->{'error'})) {
                   5896:               $array[0] ='Array reference error';
                   5897:               return (\@array, $string);
                   5898:           }
                   5899:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5900:           ($value, $string)=&str2arrayref($string);
                   5901:           if($value->[0] eq 'Array reference error') {
                   5902:               $array[0] ='Array reference error';
                   5903:               return (\@array, $string);
                   5904:           }
                   5905:       } else {
                   5906: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5907:       }
                   5908:       $string =~ s/^&//;
                   5909: 
                   5910:       push(@array, $value);
1.191     harris41 5911:   }
1.265     albertel 5912: 
                   5913:   $string =~ s/^__END_ARRAY_REF__//;
                   5914: 
                   5915:   return (\@array, $string);
1.168     albertel 5916: }
                   5917: 
1.167     albertel 5918: # -------------------------------------------------------------------Temp Store
                   5919: 
1.168     albertel 5920: sub tmpreset {
                   5921:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5922:   if (!$symb) {
                   5923:     $symb=&symbread();
1.620     albertel 5924:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5925:   }
                   5926:   $symb=escape($symb);
                   5927: 
1.620     albertel 5928:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5929:   $namespace=~s/\//\_/g;
                   5930:   $namespace=~s/\W//g;
                   5931: 
1.620     albertel 5932:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5933:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5934:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118.  .17(raeb 5935:-21):       $stuname=&get_requestor_ip();
1.591     albertel 5936:   }
1.1117    foxr     5937:   my $path=LONCAPA::tempdir();
1.168     albertel 5938:   my %hash;
                   5939:   if (tie(%hash,'GDBM_File',
                   5940: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5941: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5942:     foreach my $key (keys(%hash)) {
1.180     albertel 5943:       if ($key=~ /:$symb/) {
1.168     albertel 5944: 	delete($hash{$key});
                   5945:       }
                   5946:     }
                   5947:   }
                   5948: }
                   5949: 
1.167     albertel 5950: sub tmpstore {
1.168     albertel 5951:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5952: 
                   5953:   if (!$symb) {
                   5954:     $symb=&symbread();
1.620     albertel 5955:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5956:   }
                   5957:   $symb=escape($symb);
                   5958: 
                   5959:   if (!$namespace) {
                   5960:     # I don't think we would ever want to store this for a course.
                   5961:     # it seems this will only be used if we don't have a course.
1.620     albertel 5962:     #$namespace=$env{'request.course.id'};
1.168     albertel 5963:     #if (!$namespace) {
1.620     albertel 5964:       $namespace=$env{'request.state'};
1.168     albertel 5965:     #}
                   5966:   }
                   5967:   $namespace=~s/\//\_/g;
                   5968:   $namespace=~s/\W//g;
1.620     albertel 5969:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5970:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5971:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118.  .17(raeb 5972:-21):       $stuname=&get_requestor_ip();
1.591     albertel 5973:   }
1.168     albertel 5974:   my $now=time;
                   5975:   my %hash;
1.1117    foxr     5976:   my $path=LONCAPA::tempdir();
1.168     albertel 5977:   if (tie(%hash,'GDBM_File',
                   5978: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5979: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5980:     $hash{"version:$symb"}++;
                   5981:     my $version=$hash{"version:$symb"};
                   5982:     my $allkeys=''; 
                   5983:     foreach my $key (keys(%$storehash)) {
                   5984:       $allkeys.=$key.':';
1.591     albertel 5985:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5986:     }
                   5987:     $hash{"$version:$symb:timestamp"}=$now;
                   5988:     $allkeys.='timestamp';
                   5989:     $hash{"$version:keys:$symb"}=$allkeys;
                   5990:     if (untie(%hash)) {
                   5991:       return 'ok';
                   5992:     } else {
                   5993:       return "error:$!";
                   5994:     }
                   5995:   } else {
                   5996:     return "error:$!";
                   5997:   }
                   5998: }
1.167     albertel 5999: 
1.168     albertel 6000: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6001: 
1.168     albertel 6002: sub tmprestore {
                   6003:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6004: 
1.168     albertel 6005:   if (!$symb) {
                   6006:     $symb=&symbread();
1.620     albertel 6007:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6008:   }
                   6009:   $symb=escape($symb);
                   6010: 
1.620     albertel 6011:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6012: 
1.620     albertel 6013:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6014:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6015:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.118.  .17(raeb 6016:-21):       $stuname=&get_requestor_ip();
1.591     albertel 6017:   }
1.168     albertel 6018:   my %returnhash;
                   6019:   $namespace=~s/\//\_/g;
                   6020:   $namespace=~s/\W//g;
                   6021:   my %hash;
1.1117    foxr     6022:   my $path=LONCAPA::tempdir();
1.168     albertel 6023:   if (tie(%hash,'GDBM_File',
                   6024: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6025: 	  &GDBM_READER(),0640)) {
1.168     albertel 6026:     my $version=$hash{"version:$symb"};
                   6027:     $returnhash{'version'}=$version;
                   6028:     my $scope;
                   6029:     for ($scope=1;$scope<=$version;$scope++) {
                   6030:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6031:       my @keys=split(/:/,$vkeys);
                   6032:       my $key;
                   6033:       $returnhash{"$scope:keys"}=$vkeys;
                   6034:       foreach $key (@keys) {
1.591     albertel 6035: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6036: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6037:       }
                   6038:     }
1.168     albertel 6039:     if (!(untie(%hash))) {
                   6040:       return "error:$!";
                   6041:     }
                   6042:   } else {
                   6043:     return "error:$!";
                   6044:   }
                   6045:   return %returnhash;
1.167     albertel 6046: }
                   6047: 
1.9       www      6048: # ----------------------------------------------------------------------- Store
                   6049: 
                   6050: sub store {
1.1172.2.64  raeburn  6051:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6052:     my $home='';
                   6053: 
1.168     albertel 6054:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6055: 
1.213     www      6056:     $symb=&symbclean($symb);
1.122     albertel 6057:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6058: 
1.620     albertel 6059:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6060:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6061: 
                   6062:     &devalidate($symb,$stuname,$domain);
1.109     www      6063: 
                   6064:     $symb=escape($symb);
1.187     www      6065:     if (!$namespace) { 
1.620     albertel 6066:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6067:           return ''; 
                   6068:        } 
                   6069:     }
1.620     albertel 6070:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6071: 
1.1172.2.118.  .17(raeb 6072:-21):     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6073:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6074: 
1.12      www      6075:     my $namevalue='';
1.800     albertel 6076:     foreach my $key (keys(%$storehash)) {
                   6077:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6078:     }
1.12      www      6079:     $namevalue=~s/\&$//;
1.187     www      6080:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6081:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6082: }
                   6083: 
1.47      www      6084: # -------------------------------------------------------------- Critical Store
                   6085: 
                   6086: sub cstore {
1.1172.2.64  raeburn  6087:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6088:     my $home='';
                   6089: 
1.168     albertel 6090:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6091: 
1.213     www      6092:     $symb=&symbclean($symb);
1.122     albertel 6093:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6094: 
1.620     albertel 6095:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6096:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6097: 
                   6098:     &devalidate($symb,$stuname,$domain);
1.109     www      6099: 
                   6100:     $symb=escape($symb);
1.187     www      6101:     if (!$namespace) { 
1.620     albertel 6102:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6103:           return ''; 
                   6104:        } 
                   6105:     }
1.620     albertel 6106:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6107: 
1.1172.2.118.  .17(raeb 6108:-21):     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6109:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6110: 
1.47      www      6111:     my $namevalue='';
1.800     albertel 6112:     foreach my $key (keys(%$storehash)) {
                   6113:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6114:     }
1.47      www      6115:     $namevalue=~s/\&$//;
1.187     www      6116:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6117:     return critical
1.1172.2.64  raeburn  6118:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6119: }
                   6120: 
1.9       www      6121: # --------------------------------------------------------------------- Restore
                   6122: 
                   6123: sub restore {
1.124     www      6124:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6125:     my $home='';
                   6126: 
1.168     albertel 6127:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6128: 
1.122     albertel 6129:     if (!$symb) {
1.1172.2.26  raeburn  6130:         return if ($namespace eq 'courserequests');
                   6131:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6132:     } else {
1.1172.2.26  raeburn  6133:         unless ($namespace eq 'courserequests') {
                   6134:             $symb=&escape(&symbclean($symb));
                   6135:         }
1.122     albertel 6136:     }
1.188     www      6137:     if (!$namespace) { 
1.620     albertel 6138:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6139:           return ''; 
                   6140:        } 
                   6141:     }
1.620     albertel 6142:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6143:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6144:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6145:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6146: 
1.12      www      6147:     my %returnhash=();
1.800     albertel 6148:     foreach my $line (split(/\&/,$answer)) {
                   6149: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6150:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6151:     }
1.75      www      6152:     my $version;
                   6153:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6154:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6155:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6156:        }
1.75      www      6157:     }
1.13      www      6158:     return %returnhash;
1.34      www      6159: }
                   6160: 
                   6161: # ---------------------------------------------------------- Course Description
1.1118    foxr     6162: #
                   6163: #  
1.34      www      6164: 
                   6165: sub coursedescription {
1.731     albertel 6166:     my ($courseid,$args)=@_;
1.34      www      6167:     $courseid=~s/^\///;
1.49      www      6168:     $courseid=~s/\_/\//g;
1.34      www      6169:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6170:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6171:     my $normalid=$cdomain.'_'.$cnum;
                   6172:     # need to always cache even if we get errors otherwise we keep 
                   6173:     # trying and trying and trying to get the course description.
                   6174:     my %envhash=();
                   6175:     my %returnhash=();
1.731     albertel 6176:     
                   6177:     my $expiretime=600;
                   6178:     if ($env{'request.course.id'} eq $normalid) {
                   6179: 	$expiretime=120;
                   6180:     }
                   6181: 
                   6182:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6183:     if (!$args->{'freshen_cache'}
                   6184: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6185: 	foreach my $key (keys(%env)) {
                   6186: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6187: 	    my ($setting) = $1;
                   6188: 	    $returnhash{$setting} = $env{$key};
                   6189: 	}
                   6190: 	return %returnhash;
                   6191:     }
                   6192: 
1.1118    foxr     6193:     # get the data again
                   6194: 
1.731     albertel 6195:     if (!$args->{'one_time'}) {
                   6196: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6197:     }
1.811     albertel 6198: 
1.34      www      6199:     if ($chome ne 'no_host') {
1.302     albertel 6200:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6201:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6202: 	   my $username = $env{'user.name'}; # Defult username
                   6203: 	   if(defined $args->{'user'}) {
                   6204: 	       $username = $args->{'user'};
                   6205: 	   }
1.129     albertel 6206:            $returnhash{'home'}= $chome;
                   6207: 	   $returnhash{'domain'} = $cdomain;
                   6208: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6209:            if (!defined($returnhash{'type'})) {
                   6210:                $returnhash{'type'} = 'Course';
                   6211:            }
1.130     albertel 6212:            while (my ($name,$value) = each %returnhash) {
1.53      www      6213:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6214:            }
1.270     www      6215:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6216:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6217: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6218:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6219:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6220:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6221:        }
                   6222:     }
1.731     albertel 6223:     if (!$args->{'one_time'}) {
1.949     raeburn  6224: 	&appenv(\%envhash);
1.731     albertel 6225:     }
1.302     albertel 6226:     return %returnhash;
1.461     www      6227: }
                   6228: 
1.1080    raeburn  6229: sub update_released_required {
                   6230:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6231:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6232:         $cid = $env{'request.course.id'};
                   6233:         $cdom = $env{'course.'.$cid.'.domain'};
                   6234:         $cnum = $env{'course.'.$cid.'.num'};
                   6235:         $chome = $env{'course.'.$cid.'.home'};
                   6236:     }
                   6237:     if ($needsrelease) {
                   6238:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6239:         my $needsupdate;
                   6240:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6241:             $needsupdate = 1;
                   6242:         } else {
                   6243:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6244:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6245:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6246:                 $needsupdate = 1;
                   6247:             }
                   6248:         }
                   6249:         if ($needsupdate) {
                   6250:             my %needshash = (
                   6251:                              'internal.releaserequired' => $needsrelease,
                   6252:                             );
                   6253:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6254:             if ($putresult eq 'ok') {
                   6255:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6256:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6257:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6258:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6259:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6260:                 }
                   6261:             }
                   6262:         }
                   6263:     }
                   6264:     return;
                   6265: }
                   6266: 
1.461     www      6267: # -------------------------------------------------See if a user is privileged
                   6268: 
                   6269: sub privileged {
1.1172.2.23  raeburn  6270:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6271:     my $now = time;
1.1172.2.23  raeburn  6272:     my $roles;
                   6273:     if (ref($possroles) eq 'ARRAY') {
                   6274:         $roles = $possroles;
                   6275:     } else {
                   6276:         $roles = ['dc','su'];
                   6277:     }
                   6278:     if (ref($possdomains) eq 'ARRAY') {
                   6279:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6280:         foreach my $dom (@{$possdomains}) {
                   6281:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6282:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6283:                 foreach my $role (@{$roles}) {
                   6284:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6285:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6286:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6287:                             return 1 unless (($end && $end < $now) ||
                   6288:                                              ($start && $start > $now));
                   6289:                         }
                   6290:                     }
                   6291:                 }
                   6292:             }
                   6293:         }
                   6294:     } else {
                   6295:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6296:         my $now = time;
1.1170    droeschl 6297: 
1.1172.2.58  raeburn  6298:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6299:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6300:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6301:                 return 1 unless ($tend && $tend < $now)
                   6302:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6303:             }
1.1172.2.23  raeburn  6304:         }
                   6305:     }
1.461     www      6306:     return 0;
1.9       www      6307: }
1.1       albertel 6308: 
1.1172.2.23  raeburn  6309: sub privileged_by_domain {
                   6310:     my ($domains,$roles) = @_;
                   6311:     my %privileged = ();
                   6312:     my $cachetime = 60*60*24;
                   6313:     my $now = time;
                   6314:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6315:         return %privileged;
                   6316:     }
                   6317:     foreach my $dom (@{$domains}) {
                   6318:         next if (ref($privileged{$dom}) eq 'HASH');
                   6319:         my $needroles;
                   6320:         foreach my $role (@{$roles}) {
                   6321:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6322:             if (defined($cached)) {
                   6323:                 if (ref($result) eq 'HASH') {
                   6324:                     $privileged{$dom}{$role} = $result;
                   6325:                 }
                   6326:             } else {
                   6327:                 $needroles = 1;
                   6328:             }
                   6329:         }
                   6330:         if ($needroles) {
                   6331:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6332:             $privileged{$dom} = {};
                   6333:             foreach my $server (keys(%dompersonnel)) {
                   6334:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6335:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6336:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6337:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6338:                         next if ($end && $end < $now);
                   6339:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6340:                             $dompersonnel{$server}{$item};
                   6341:                     }
                   6342:                 }
                   6343:             }
                   6344:             if (ref($privileged{$dom}) eq 'HASH') {
                   6345:                 foreach my $role (@{$roles}) {
                   6346:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6347:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6348:                     } else {
                   6349:                         my %hash = ();
                   6350:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6351:                     }
                   6352:                 }
                   6353:             }
                   6354:         }
                   6355:     }
                   6356:     return %privileged;
                   6357: }
                   6358: 
1.103     harris41 6359: # -------------------------------------------------------- Get user privileges
1.11      www      6360: 
                   6361: sub rolesinit {
1.1169    droeschl 6362:     my ($domain, $username) = @_;
                   6363:     my %userroles = ('user.login.time' => time);
                   6364:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6365: 
                   6366:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6367:     # also, blocking can be triggered by an activating timer
                   6368:     # it's saved in the user's %env.
                   6369:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6370:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6371:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6372:         %timerintchk, %timerintenv);
                   6373: 
1.1162    raeburn  6374:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6375:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6376:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6377:     }
1.1169    droeschl 6378: 
1.1162    raeburn  6379:     foreach my $key (keys(%timerinterval)) {
                   6380:         my ($cid,$rest) = split(/\0/,$key);
                   6381:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6382:     }
1.1169    droeschl 6383: 
1.11      www      6384:     my %allroles=();
1.1162    raeburn  6385:     my %allgroups=();
1.11      www      6386: 
1.1172.2.58  raeburn  6387:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6388:         my $role = $rolesdump{$area};
                   6389:         $area =~ s/\_\w\w$//;
                   6390: 
                   6391:         my ($trole, $tend, $tstart, $group_privs);
                   6392: 
                   6393:         if ($role =~ /^cr/) {
                   6394:         # Custom role, defined by a user 
                   6395:         # e.g., user.role.cr/msu/smith/mynewrole
                   6396:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6397:                 $trole = $1;
                   6398:                 ($tend, $tstart) = split('_', $2);
                   6399:             } else {
                   6400:                 $trole = $role;
                   6401:             }
                   6402:         } elsif ($role =~ m|^gr/|) {
                   6403:         # Role of member in a group, defined within a course/community
                   6404:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6405:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6406:             next if $tstart eq '-1';
                   6407:             ($trole, $group_privs) = split(/\//, $trole);
                   6408:             $group_privs = &unescape($group_privs);
                   6409:         } else {
                   6410:         # Just a normal role, defined in roles.tab
                   6411:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6412:         }
                   6413: 
                   6414:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6415:                  $username);
                   6416:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6417: 
                   6418:         # role expired or not available yet?
                   6419:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6420:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6421: 
                   6422:         next if $area eq '' or $trole eq '';
                   6423: 
                   6424:         my $spec = "$trole.$area";
                   6425:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6426: 
                   6427:         if ($trole =~ /^cr\//) {
                   6428:         # Custom role, defined by a user
                   6429:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6430:         } elsif ($trole eq 'gr') {
                   6431:         # Role of a member in a group, defined within a course/community
                   6432:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6433:             next;
                   6434:         } else {
                   6435:         # Normal role, defined in roles.tab
                   6436:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6437:         }
                   6438: 
                   6439:         my $cid = $tdomain.'_'.$trest;
                   6440:         unless ($firstaccchk{$cid}) {
                   6441:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6442:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6443:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6444:                         $coursetimerstarts{$cid}{$item}; 
                   6445:                 }
                   6446:             }
                   6447:             $firstaccchk{$cid} = 1;
                   6448:         }
                   6449:         unless ($timerintchk{$cid}) {
                   6450:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6451:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6452:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6453:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6454:                 }
1.12      www      6455:             }
1.1169    droeschl 6456:             $timerintchk{$cid} = 1;
1.191     harris41 6457:         }
1.11      www      6458:     }
1.1169    droeschl 6459: 
1.1172.2.91  raeburn  6460:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6461:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6462:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6463:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6464: 
1.1162    raeburn  6465:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6466: }
                   6467: 
1.567     raeburn  6468: sub set_arearole {
1.1172.2.19  raeburn  6469:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6470:     unless ($nolog) {
1.567     raeburn  6471: # log the associated role with the area
1.1172.2.19  raeburn  6472:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6473:     }
1.743     albertel 6474:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6475: }
                   6476: 
                   6477: sub custom_roleprivs {
                   6478:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6479:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6480:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6481:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6482:         my ($rdummy,$roledef)=
                   6483:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6484:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6485:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6486:             if (defined($syspriv)) {
1.1043    raeburn  6487:                 if ($trest =~ /^$match_community$/) {
                   6488:                     $syspriv =~ s/bre\&S//; 
                   6489:                 }
1.567     raeburn  6490:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6491:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6492:             }
                   6493:             if ($tdomain ne '') {
                   6494:                 if (defined($dompriv)) {
                   6495:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6496:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6497:                 }
                   6498:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6499:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6500:                         my $rolename = $1;
                   6501:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6502:                     }
1.567     raeburn  6503:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6504:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6505:                 }
                   6506:             }
                   6507:         }
                   6508:     }
                   6509: }
                   6510: 
1.1172.2.89  raeburn  6511: sub course_adhocrole_privs {
                   6512:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6513:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6514:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6515:         my (%currprivs,%storeprivs);
                   6516:         foreach my $item (split(/:/,$coursepriv)) {
                   6517:             my ($priv,$restrict) = split(/\&/,$item);
                   6518:             $currprivs{$priv} = $restrict;
                   6519:         }
                   6520:         my (%possadd,%possremove,%full);
                   6521:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6522:             my ($priv,$restrict)=split(/\&/,$item);
                   6523:             $full{$priv} = $restrict;
                   6524:         }
                   6525:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6526:              next if ($item eq '');
                   6527:              my ($rule,$rest) = split(/=/,$item);
                   6528:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6529:              foreach my $priv (split(/:/,$rest)) {
                   6530:                  if ($priv ne '') {
                   6531:                      if ($rule eq 'off') {
                   6532:                          $possremove{$priv} = 1;
                   6533:                      } else {
                   6534:                          $possadd{$priv} = 1;
                   6535:                      }
                   6536:                  }
                   6537:              }
                   6538:          }
                   6539:          foreach my $priv (sort(keys(%full))) {
                   6540:              if (exists($currprivs{$priv})) {
                   6541:                  unless (exists($possremove{$priv})) {
                   6542:                      $storeprivs{$priv} = $currprivs{$priv};
                   6543:                  }
                   6544:              } elsif (exists($possadd{$priv})) {
                   6545:                  $storeprivs{$priv} = $full{$priv};
                   6546:              }
                   6547:          }
                   6548:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6549:      }
                   6550:      return $coursepriv;
                   6551: }
                   6552: 
1.678     raeburn  6553: sub group_roleprivs {
                   6554:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6555:     my $access = 1;
                   6556:     my $now = time;
                   6557:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6558:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6559:     if ($access) {
1.811     albertel 6560:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6561:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6562:     }
                   6563: }
1.567     raeburn  6564: 
                   6565: sub standard_roleprivs {
                   6566:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6567:     if (defined($pr{$trole.':s'})) {
                   6568:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6569:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6570:     }
                   6571:     if ($tdomain ne '') {
                   6572:         if (defined($pr{$trole.':d'})) {
                   6573:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6574:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6575:         }
                   6576:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6577:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6578:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6579:         }
                   6580:     }
                   6581: }
                   6582: 
                   6583: sub set_userprivs {
1.1064    raeburn  6584:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6585:     my $author=0;
                   6586:     my $adv=0;
1.1172.2.91  raeburn  6587:     my $rar=0;
1.678     raeburn  6588:     my %grouproles = ();
                   6589:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6590:         my @groupkeys; 
1.1000    raeburn  6591:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6592:             push(@groupkeys,$role);
                   6593:         }
                   6594:         if (ref($groups_roles) eq 'HASH') {
                   6595:             foreach my $key (keys(%{$groups_roles})) {
                   6596:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6597:                     push(@groupkeys,$key);
                   6598:                 }
                   6599:             }
                   6600:         }
                   6601:         if (@groupkeys > 0) {
                   6602:             foreach my $role (@groupkeys) {
                   6603:                 my ($trole,$area,$sec,$extendedarea);
                   6604:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6605:                     $trole = $1;
                   6606:                     $area = $2;
                   6607:                     $sec = $3;
                   6608:                     $extendedarea = $area.$sec;
                   6609:                     if (exists($$allgroups{$area})) {
                   6610:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6611:                             my $spec = $trole.'.'.$extendedarea;
                   6612:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6613:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6614:                         }
1.678     raeburn  6615:                     }
                   6616:                 }
                   6617:             }
                   6618:         }
                   6619:     }
1.800     albertel 6620:     foreach my $group (keys(%grouproles)) {
                   6621:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6622:     }
1.800     albertel 6623:     foreach my $role (keys(%{$allroles})) {
                   6624:         my %thesepriv;
1.941     raeburn  6625:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6626:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6627:             if ($item ne '') {
                   6628:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6629:                 if ($restrictions eq '') {
                   6630:                     $thesepriv{$privilege}='F';
                   6631:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6632:                     $thesepriv{$privilege}.=$restrictions;
                   6633:                 }
                   6634:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6635:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6636:             }
                   6637:         }
                   6638:         my $thesestr='';
1.1104    raeburn  6639:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6640: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6641: 	}
                   6642:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6643:     }
1.1172.2.91  raeburn  6644:     return ($author,$adv,$rar);
1.567     raeburn  6645: }
                   6646: 
1.994     raeburn  6647: sub role_status {
1.1104    raeburn  6648:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6649:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6650:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6651:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6652:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6653:             $$where = '/'.$two;
1.994     raeburn  6654:             $$trolecode=$$role.'.'.$$where;
                   6655:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6656:             $$tstatus='is';
1.1104    raeburn  6657:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6658:                 $$tstatus='future';
1.1034    raeburn  6659:                 if ($$tstart<$now) {
                   6660:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6661:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6662:                             my (%allroles,%allgroups,$group_privs,
                   6663:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6664:                             my %userroles = (
                   6665:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6666:                             );
1.1064    raeburn  6667:                             @rolecodes = ('cm'); 
1.1002    raeburn  6668:                             my $spec=$$role.'.'.$$where;
                   6669:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6670:                             if ($$role =~ /^cr\//) {
                   6671:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6672:                                 push(@rolecodes,'cr');
1.1002    raeburn  6673:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6674:                                 push(@rolecodes,$$role);
1.1002    raeburn  6675:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6676:                                                     $env{'user.name'});
1.1064    raeburn  6677:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6678:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6679:                                 $group_privs = &unescape($group_privs);
                   6680:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6681:                                 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  6682:                                 &get_groups_roles($tdomain,$trest,
                   6683:                                                   \%course_roles,\@rolecodes,
                   6684:                                                   \%groups_roles);
1.1002    raeburn  6685:                             } else {
1.1064    raeburn  6686:                                 push(@rolecodes,$$role);
1.1002    raeburn  6687:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6688:                             }
1.1172.2.91  raeburn  6689:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6690:                                                                    \%groups_roles);
1.1064    raeburn  6691:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6692:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6693:                         }
                   6694:                     }
1.1034    raeburn  6695:                     $$tstatus = 'is';
1.1002    raeburn  6696:                 }
1.994     raeburn  6697:             }
                   6698:             if ($$tend) {
1.1104    raeburn  6699:                 if ($$tend<$update) {
1.994     raeburn  6700:                     $$tstatus='expired';
                   6701:                 } elsif ($$tend<$now) {
                   6702:                     $$tstatus='will_not';
                   6703:                 }
                   6704:             }
                   6705:         }
                   6706:     }
                   6707: }
                   6708: 
1.1104    raeburn  6709: sub get_groups_roles {
                   6710:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6711:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6712:                   (ref($rolecodes) eq 'ARRAY') && 
                   6713:                   (ref($groups_roles) eq 'HASH')); 
                   6714:     if (keys(%{$cdom_courseroles}) > 0) {
                   6715:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6716:         if ($cdom ne '' && $cnum ne '') {
                   6717:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6718:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6719:                     my $crsrole = $1;
                   6720:                     my $crssec = $2;
                   6721:                     if ($crsrole =~ /^cr/) {
                   6722:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6723:                             push(@{$rolecodes},'cr');
                   6724:                         }
                   6725:                     } else {
                   6726:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6727:                             push(@{$rolecodes},$crsrole);
                   6728:                         }
                   6729:                     }
                   6730:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6731:                     if ($crssec ne '') {
                   6732:                         $rolekey .= "/$crssec";
                   6733:                     }
                   6734:                     $rolekey .= './';
                   6735:                     $groups_roles->{$rolekey} = $rolecodes;
                   6736:                 }
                   6737:             }
                   6738:         }
                   6739:     }
                   6740:     return;
                   6741: }
                   6742: 
                   6743: sub delete_env_groupprivs {
                   6744:     my ($where,$courseroles,$possroles) = @_;
                   6745:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6746:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6747:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6748:         %{$courseroles->{$udom}} =
                   6749:             &get_my_roles('','','userroles',['active'],
                   6750:                           $possroles,[$udom],1);
                   6751:     }
                   6752:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6753:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6754:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6755:             my $area = '/'.$cdom.'/'.$cnum;
                   6756:             my $privkey = "user.priv.$crsrole.$area";
                   6757:             if ($crssec ne '') {
                   6758:                 $privkey .= '/'.$crssec;
                   6759:             }
                   6760:             $privkey .= ".$area/$group";
                   6761:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6762:         }
                   6763:     }
                   6764:     return;
                   6765: }
                   6766: 
1.994     raeburn  6767: sub check_adhoc_privs {
1.1172.2.86  raeburn  6768:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6769:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6770:     if ($sec) {
                   6771:         $cckey .= '/'.$sec;
                   6772:     }
1.1172.2.9  raeburn  6773:     my $setprivs;
1.994     raeburn  6774:     if ($env{$cckey}) {
                   6775:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6776:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6777:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6778:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6779:             $setprivs = 1;
1.994     raeburn  6780:         }
                   6781:     } else {
1.1172.2.87  raeburn  6782:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6783:         $setprivs = 1;
1.994     raeburn  6784:     }
1.1172.2.9  raeburn  6785:     return $setprivs;
1.994     raeburn  6786: }
                   6787: 
                   6788: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6789: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6790:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6791:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6792:     if ($sec ne '') {
                   6793:         $area .= '/'.$sec;
                   6794:     }
1.994     raeburn  6795:     my $spec = $role.'.'.$area;
                   6796:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6797:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6798:     my %rolehash = ();
1.1172.2.89  raeburn  6799:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6800:         my $rolename = $1;
1.1172.2.84  raeburn  6801:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6802:         my %domdef = &get_domain_defaults($dcdom);
                   6803:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6804:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6805:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6806:             }
                   6807:         }
1.1172.2.84  raeburn  6808:     } else {
                   6809:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6810:     }
1.1172.2.91  raeburn  6811:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6812:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6813:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6814:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6815:         &appenv( {'request.role'        => $spec,
                   6816:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6817:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6818:                  }
                   6819:                );
                   6820:         my $tadv=0;
                   6821:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6822:         &appenv({'request.role.adv'    => $tadv});
                   6823:     }
1.994     raeburn  6824: }
                   6825: 
1.12      www      6826: # --------------------------------------------------------------- get interface
                   6827: 
                   6828: sub get {
1.131     albertel 6829:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6830:    my $items='';
1.800     albertel 6831:    foreach my $item (@$storearr) {
                   6832:        $items.=&escape($item).'&';
1.191     harris41 6833:    }
1.12      www      6834:    $items=~s/\&$//;
1.620     albertel 6835:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6836:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6837:    my $uhome=&homeserver($uname,$udomain);
                   6838: 
1.133     albertel 6839:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6840:    my @pairs=split(/\&/,$rep);
1.273     albertel 6841:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6842:      return @pairs;
                   6843:    }
1.15      www      6844:    my %returnhash=();
1.42      www      6845:    my $i=0;
1.800     albertel 6846:    foreach my $item (@$storearr) {
                   6847:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6848:       $i++;
1.191     harris41 6849:    }
1.15      www      6850:    return %returnhash;
1.27      www      6851: }
                   6852: 
                   6853: # --------------------------------------------------------------- del interface
                   6854: 
                   6855: sub del {
1.133     albertel 6856:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6857:    my $items='';
1.800     albertel 6858:    foreach my $item (@$storearr) {
                   6859:        $items.=&escape($item).'&';
1.191     harris41 6860:    }
1.984     neumanie 6861: 
1.27      www      6862:    $items=~s/\&$//;
1.620     albertel 6863:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6864:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6865:    my $uhome=&homeserver($uname,$udomain);
                   6866:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6867: }
                   6868: 
                   6869: # -------------------------------------------------------------- dump interface
                   6870: 
1.1172.2.22  raeburn  6871: sub unserialize {
                   6872:     my ($rep, $escapedkeys) = @_;
                   6873: 
                   6874:     return {} if $rep =~ /^error/;
                   6875: 
                   6876:     my %returnhash=();
                   6877:     foreach my $item (split(/\&/,$rep)) {
                   6878:         my ($key, $value) = split(/=/, $item, 2);
                   6879:         $key = unescape($key) unless $escapedkeys;
                   6880:         next if $key =~ /^error: 2 /;
                   6881:         $returnhash{$key} = &thaw_unescape($value);
                   6882:     }
                   6883:     return \%returnhash;
                   6884: }
                   6885: 
                   6886: # see Lond::dump_with_regexp
                   6887: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6888: sub dump {
1.1172.2.22  raeburn  6889:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6890:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6891:     if (!$uname) { $uname=$env{'user.name'}; }
                   6892:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6893: 
1.1172.2.55  raeburn  6894:     if ($regexp) {
                   6895:         $regexp=&escape($regexp);
                   6896:     } else {
                   6897:         $regexp='.';
                   6898:     }
1.1172.2.22  raeburn  6899:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6900:         # user is hosted on this machine
1.1172.2.55  raeburn  6901:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6902:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6903:         return %{&unserialize($reply, $escapedkeys)};
                   6904:     }
1.1166    raeburn  6905:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6906:     my @pairs=split(/\&/,$rep);
                   6907:     my %returnhash=();
1.1098    foxr     6908:     if (!($rep =~ /^error/ )) {
                   6909: 	foreach my $item (@pairs) {
                   6910: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6911:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6912: 	    next if ($key =~ /^error: 2 /);
                   6913: 	    $returnhash{$key}=&thaw_unescape($value);
                   6914: 	}
1.755     albertel 6915:     }
                   6916:     return %returnhash;
1.407     www      6917: }
                   6918: 
1.1098    foxr     6919: 
1.717     albertel 6920: # --------------------------------------------------------- dumpstore interface
                   6921: 
                   6922: sub dumpstore {
                   6923:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6924:    # same as dump but keys must be escaped. They may contain colon separated
                   6925:    # lists of values that may themself contain colons (e.g. symbs).
                   6926:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6927: }
                   6928: 
1.407     www      6929: # -------------------------------------------------------------- keys interface
                   6930: 
                   6931: sub getkeys {
                   6932:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6933:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6934:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6935:    my $uhome=&homeserver($uname,$udomain);
                   6936:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6937:    my @keyarray=();
1.800     albertel 6938:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6939:       next if ($key =~ /^error: 2 /);
1.800     albertel 6940:       push(@keyarray,&unescape($key));
1.407     www      6941:    }
                   6942:    return @keyarray;
1.318     matthew  6943: }
                   6944: 
1.319     matthew  6945: # --------------------------------------------------------------- currentdump
                   6946: sub currentdump {
1.328     matthew  6947:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6948:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6949:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6950:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6951:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6952:    my $rep;
                   6953: 
                   6954:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6955:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6956:                    $courseid)));
                   6957:    } else {
                   6958:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6959:    }
                   6960: 
1.318     matthew  6961:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6962:    #
1.318     matthew  6963:    my %returnhash=();
1.319     matthew  6964:    #
1.1172.2.118.  .1(raebu 6965:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6966:        # an old lond will not know currentdump
                   6967:        # Do a dump and make it look like a currentdump
1.822     albertel 6968:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6969:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6970:        my %hash = @tmp;
                   6971:        @tmp=();
1.424     matthew  6972:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6973:    } else {
                   6974:        my @pairs=split(/\&/,$rep);
1.800     albertel 6975:        foreach my $pair (@pairs) {
                   6976:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6977:            my ($symb,$param) = split(/:/,$key);
                   6978:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6979:                                                         &thaw_unescape($value);
1.319     matthew  6980:        }
1.191     harris41 6981:    }
1.12      www      6982:    return %returnhash;
1.424     matthew  6983: }
                   6984: 
                   6985: sub convert_dump_to_currentdump{
                   6986:     my %hash = %{shift()};
                   6987:     my %returnhash;
                   6988:     # Code ripped from lond, essentially.  The only difference
                   6989:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6990:     # we might run in to problems with parameter names =~ /^v\./
                   6991:     while (my ($key,$value) = each(%hash)) {
                   6992:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6993: 	$symb  = &unescape($symb);
                   6994: 	$param = &unescape($param);
1.424     matthew  6995:         next if ($v eq 'version' || $symb eq 'keys');
                   6996:         next if (exists($returnhash{$symb}) &&
                   6997:                  exists($returnhash{$symb}->{$param}) &&
                   6998:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6999:         $returnhash{$symb}->{$param}=$value;
                   7000:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7001:     }
                   7002:     #
                   7003:     # Remove all of the keys in the hashes which keep track of
                   7004:     # the version of the parameter.
                   7005:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7006:         # use a foreach because we are going to delete from the hash.
                   7007:         foreach my $key (keys(%$param_hash)) {
                   7008:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7009:         }
                   7010:     }
                   7011:     return \%returnhash;
1.12      www      7012: }
                   7013: 
1.627     albertel 7014: # ------------------------------------------------------ critical inc interface
                   7015: 
                   7016: sub cinc {
                   7017:     return &inc(@_,'critical');
                   7018: }
                   7019: 
1.449     matthew  7020: # --------------------------------------------------------------- inc interface
                   7021: 
                   7022: sub inc {
1.627     albertel 7023:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7024:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7025:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7026:     my $uhome=&homeserver($uname,$udomain);
                   7027:     my $items='';
                   7028:     if (! ref($store)) {
                   7029:         # got a single value, so use that instead
                   7030:         $items = &escape($store).'=&';
                   7031:     } elsif (ref($store) eq 'SCALAR') {
                   7032:         $items = &escape($$store).'=&';        
                   7033:     } elsif (ref($store) eq 'ARRAY') {
                   7034:         $items = join('=&',map {&escape($_);} @{$store});
                   7035:     } elsif (ref($store) eq 'HASH') {
                   7036:         while (my($key,$value) = each(%{$store})) {
                   7037:             $items.= &escape($key).'='.&escape($value).'&';
                   7038:         }
                   7039:     }
                   7040:     $items=~s/\&$//;
1.627     albertel 7041:     if ($critical) {
                   7042: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7043:     } else {
                   7044: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7045:     }
1.449     matthew  7046: }
                   7047: 
1.12      www      7048: # --------------------------------------------------------------- put interface
                   7049: 
                   7050: sub put {
1.134     albertel 7051:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7052:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7053:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7054:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7055:    my $items='';
1.800     albertel 7056:    foreach my $item (keys(%$storehash)) {
                   7057:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7058:    }
1.12      www      7059:    $items=~s/\&$//;
1.134     albertel 7060:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7061: }
                   7062: 
1.631     albertel 7063: # ------------------------------------------------------------ newput interface
                   7064: 
                   7065: sub newput {
                   7066:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7067:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7068:    if (!$uname) { $uname=$env{'user.name'}; }
                   7069:    my $uhome=&homeserver($uname,$udomain);
                   7070:    my $items='';
                   7071:    foreach my $key (keys(%$storehash)) {
                   7072:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7073:    }
                   7074:    $items=~s/\&$//;
                   7075:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7076: }
                   7077: 
                   7078: # ---------------------------------------------------------  putstore interface
                   7079: 
1.524     raeburn  7080: sub putstore {
1.1172.2.59  raeburn  7081:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7082:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7083:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7084:    my $uhome=&homeserver($uname,$udomain);
                   7085:    my $items='';
1.715     albertel 7086:    foreach my $key (keys(%$storehash)) {
                   7087:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7088:    }
1.715     albertel 7089:    $items=~s/\&$//;
1.716     albertel 7090:    my $esc_symb=&escape($symb);
                   7091:    my $esc_v=&escape($version);
1.715     albertel 7092:    my $reply =
1.716     albertel 7093:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7094: 	      $uhome);
1.1172.2.59  raeburn  7095:    if (($tolog) && ($reply eq 'ok')) {
                   7096:        my $namevalue='';
                   7097:        foreach my $key (keys(%{$storehash})) {
                   7098:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7099:        }
1.1172.2.118.  .14(raeb 7100:-21):        my $ip = &get_requestor_ip();
                   7101:-21):        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7102:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7103:                      '&version='.$esc_v.
                   7104:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7105:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7106:    }
1.715     albertel 7107:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7108:        # gfall back to way things use to be done
1.715     albertel 7109:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7110: 			    $uname);
1.524     raeburn  7111:    }
1.715     albertel 7112:    return $reply;
                   7113: }
                   7114: 
                   7115: sub old_putstore {
1.716     albertel 7116:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7117:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7118:     if (!$uname) { $uname=$env{'user.name'}; }
                   7119:     my $uhome=&homeserver($uname,$udomain);
                   7120:     my %newstorehash;
1.800     albertel 7121:     foreach my $item (keys(%$storehash)) {
                   7122: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7123: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7124:     }
                   7125:     my $items='';
                   7126:     my %allitems = ();
1.800     albertel 7127:     foreach my $item (keys(%newstorehash)) {
                   7128: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7129: 	    my $key = $1.':keys:'.$2;
                   7130: 	    $allitems{$key} .= $3.':';
                   7131: 	}
1.800     albertel 7132: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7133:     }
1.800     albertel 7134:     foreach my $item (keys(%allitems)) {
                   7135: 	$allitems{$item} =~ s/\:$//;
                   7136: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7137:     }
                   7138:     $items=~s/\&$//;
                   7139:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7140: }
                   7141: 
1.47      www      7142: # ------------------------------------------------------ critical put interface
                   7143: 
                   7144: sub cput {
1.134     albertel 7145:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7146:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7147:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7148:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7149:    my $items='';
1.800     albertel 7150:    foreach my $item (keys(%$storehash)) {
                   7151:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7152:    }
1.47      www      7153:    $items=~s/\&$//;
1.134     albertel 7154:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7155: }
                   7156: 
                   7157: # -------------------------------------------------------------- eget interface
                   7158: 
                   7159: sub eget {
1.133     albertel 7160:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7161:    my $items='';
1.800     albertel 7162:    foreach my $item (@$storearr) {
                   7163:        $items.=&escape($item).'&';
1.191     harris41 7164:    }
1.12      www      7165:    $items=~s/\&$//;
1.620     albertel 7166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7167:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7168:    my $uhome=&homeserver($uname,$udomain);
                   7169:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7170:    my @pairs=split(/\&/,$rep);
                   7171:    my %returnhash=();
1.42      www      7172:    my $i=0;
1.800     albertel 7173:    foreach my $item (@$storearr) {
                   7174:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7175:       $i++;
1.191     harris41 7176:    }
1.12      www      7177:    return %returnhash;
                   7178: }
                   7179: 
1.667     albertel 7180: # ------------------------------------------------------------ tmpput interface
                   7181: sub tmpput {
1.802     raeburn  7182:     my ($storehash,$server,$context)=@_;
1.667     albertel 7183:     my $items='';
1.800     albertel 7184:     foreach my $item (keys(%$storehash)) {
                   7185: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7186:     }
                   7187:     $items=~s/\&$//;
1.802     raeburn  7188:     if (defined($context)) {
                   7189:         $items .= ':'.&escape($context);
                   7190:     }
1.667     albertel 7191:     return &reply("tmpput:$items",$server);
                   7192: }
                   7193: 
                   7194: # ------------------------------------------------------------ tmpget interface
                   7195: sub tmpget {
1.688     albertel 7196:     my ($token,$server)=@_;
                   7197:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7198:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7199:     my %returnhash;
1.1172.2.85  raeburn  7200:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7201:         return %returnhash;
                   7202:     }
1.667     albertel 7203:     foreach my $item (split(/\&/,$rep)) {
                   7204: 	my ($key,$value)=split(/=/,$item);
                   7205: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7206:     }
                   7207:     return %returnhash;
                   7208: }
                   7209: 
1.1113    raeburn  7210: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7211: sub tmpdel {
                   7212:     my ($token,$server)=@_;
                   7213:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7214:     return &reply("tmpdel:$token",$server);
                   7215: }
                   7216: 
1.1172.2.13  raeburn  7217: # ------------------------------------------------------------ get_timebased_id
                   7218: 
                   7219: sub get_timebased_id {
                   7220:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7221:         $maxtries) = @_;
                   7222:     my ($newid,$error,$dellock);
                   7223:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7224:         return ('','ok','invalid call to get suffix');
                   7225:     }
                   7226: 
                   7227: # set defaults for any optional args for which values were not supplied
                   7228:     if ($who eq '') {
                   7229:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7230:     }
                   7231:     if (!$locktries) {
                   7232:         $locktries = 3;
                   7233:     }
                   7234:     if (!$maxtries) {
                   7235:         $maxtries = 10;
                   7236:     }
                   7237: 
                   7238:     if (($cdom eq '') || ($cnum eq '')) {
                   7239:         if ($env{'request.course.id'}) {
                   7240:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7241:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7242:         }
                   7243:         if (($cdom eq '') || ($cnum eq '')) {
                   7244:             return ('','ok','call to get suffix not in course context');
                   7245:         }
                   7246:     }
                   7247: 
                   7248: # construct locking item
                   7249:     my $lockhash = {
                   7250:                       $prefix."\0".'locked_'.$keyid => $who,
                   7251:                    };
                   7252:     my $tries = 0;
                   7253: 
                   7254: # attempt to get lock on nohist_$namespace file
                   7255:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7256:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7257:         $tries ++;
                   7258:         sleep 1;
                   7259:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7260:     }
                   7261: 
                   7262: # attempt to get unique identifier, based on current timestamp
                   7263:     if ($gotlock eq 'ok') {
                   7264:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7265:         my $id = time;
                   7266:         $newid = $id;
1.1172.2.56  raeburn  7267:         if ($idtype eq 'addcode') {
                   7268:             $newid .= &sixnum_code();
                   7269:         }
1.1172.2.13  raeburn  7270:         my $idtries = 0;
                   7271:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7272:             if ($idtype eq 'concat') {
                   7273:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7274:             } elsif ($idtype eq 'addcode') {
                   7275:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7276:             } else {
                   7277:                 $newid ++;
                   7278:             }
                   7279:             $idtries ++;
                   7280:         }
                   7281:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7282:             my %new_item =  (
                   7283:                               $prefix."\0".$newid => $who,
                   7284:                             );
                   7285:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7286:                                                  $cdom,$cnum);
                   7287:             if ($putresult ne 'ok') {
                   7288:                 undef($newid);
                   7289:                 $error = 'error saving new item: '.$putresult;
                   7290:             }
                   7291:         } else {
1.1172.2.56  raeburn  7292:              undef($newid);
1.1172.2.13  raeburn  7293:              $error = ('error: no unique suffix available for the new item ');
                   7294:         }
                   7295: #  remove lock
                   7296:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7297:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7298:     } else {
                   7299:         $error = "error: could not obtain lockfile\n";
                   7300:         $dellock = 'ok';
1.1172.2.58  raeburn  7301:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7302:             $dellock = 'nolock';
                   7303:         }
1.1172.2.13  raeburn  7304:     }
                   7305:     return ($newid,$dellock,$error);
                   7306: }
                   7307: 
1.1172.2.56  raeburn  7308: sub sixnum_code {
                   7309:     my $code;
                   7310:     for (0..6) {
                   7311:         $code .= int( rand(9) );
                   7312:     }
                   7313:     return $code;
                   7314: }
                   7315: 
1.765     albertel 7316: # -------------------------------------------------- portfolio access checking
                   7317: 
                   7318: sub portfolio_access {
1.1172.2.77  raeburn  7319:     my ($requrl,$clientip) = @_;
1.765     albertel 7320:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7321:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7322:     if ($result) {
                   7323:         my %setters;
                   7324:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7325:             my ($startblock,$endblock) =
                   7326:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7327:             if ($startblock && $endblock) {
                   7328:                 return 'B';
                   7329:             }
                   7330:         } else {
                   7331:             my ($startblock,$endblock) =
                   7332:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7333:             if ($startblock && $endblock) {
                   7334:                 return 'B';
                   7335:             }
                   7336:         }
                   7337:     }
1.765     albertel 7338:     if ($result eq 'ok') {
1.766     albertel 7339:        return 'F';
1.765     albertel 7340:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7341:        return 'A';
1.765     albertel 7342:     }
1.766     albertel 7343:     return '';
1.765     albertel 7344: }
                   7345: 
                   7346: sub get_portfolio_access {
1.1172.2.77  raeburn  7347:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7348: 
                   7349:     if (!ref($access_hash)) {
                   7350: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7351: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7352: 						   $file_name);
                   7353: 	$access_hash = $access_controls{$file_name};
                   7354:     }
                   7355: 
1.1172.2.77  raeburn  7356:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7357:     my $now = time;
                   7358:     if (ref($access_hash) eq 'HASH') {
                   7359:         foreach my $key (keys(%{$access_hash})) {
                   7360:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7361:             if ($start > $now) {
                   7362:                 next;
                   7363:             }
                   7364:             if ($end && $end<$now) {
                   7365:                 next;
                   7366:             }
                   7367:             if ($scope eq 'public') {
                   7368:                 $public = $key;
                   7369:                 last;
                   7370:             } elsif ($scope eq 'guest') {
                   7371:                 $guest = $key;
                   7372:             } elsif ($scope eq 'domains') {
                   7373:                 push(@domains,$key);
                   7374:             } elsif ($scope eq 'users') {
                   7375:                 push(@users,$key);
                   7376:             } elsif ($scope eq 'course') {
                   7377:                 push(@courses,$key);
                   7378:             } elsif ($scope eq 'group') {
                   7379:                 push(@groups,$key);
1.1172.2.77  raeburn  7380:             } elsif ($scope eq 'ip') {
                   7381:                 push(@ips,$key);
1.765     albertel 7382:             }
                   7383:         }
                   7384:         if ($public) {
                   7385:             return 'ok';
1.1172.2.77  raeburn  7386:         } elsif (@ips > 0) {
                   7387:             my $allowed;
                   7388:             foreach my $ipkey (@ips) {
                   7389:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7390:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7391:                         $allowed = 1;
                   7392:                         last;
                   7393:                     }
                   7394:                 }
                   7395:             }
                   7396:             if ($allowed) {
                   7397:                 return 'ok';
                   7398:             }
1.765     albertel 7399:         }
                   7400:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7401:             if ($guest) {
                   7402:                 return $guest;
                   7403:             }
                   7404:         } else {
                   7405:             if (@domains > 0) {
                   7406:                 foreach my $domkey (@domains) {
                   7407:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7408:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7409:                             return 'ok';
                   7410:                         }
                   7411:                     }
                   7412:                 }
                   7413:             }
                   7414:             if (@users > 0) {
                   7415:                 foreach my $userkey (@users) {
1.865     raeburn  7416:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7417:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7418:                             if (ref($item) eq 'HASH') {
                   7419:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7420:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7421:                                     return 'ok';
                   7422:                                 }
                   7423:                             }
                   7424:                         }
                   7425:                     } 
1.765     albertel 7426:                 }
                   7427:             }
                   7428:             my %roleshash;
                   7429:             my @courses_and_groups = @courses;
                   7430:             push(@courses_and_groups,@groups); 
                   7431:             if (@courses_and_groups > 0) {
                   7432:                 my (%allgroups,%allroles); 
                   7433:                 my ($start,$end,$role,$sec,$group);
                   7434:                 foreach my $envkey (%env) {
1.1060    raeburn  7435:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7436:                         my $cid = $2.'_'.$3; 
                   7437:                         if ($1 eq 'gr') {
                   7438:                             $group = $4;
                   7439:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7440:                         } else {
                   7441:                             if ($4 eq '') {
                   7442:                                 $sec = 'none';
                   7443:                             } else {
                   7444:                                 $sec = $4;
                   7445:                             }
                   7446:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7447:                         }
1.811     albertel 7448:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7449:                         my $cid = $2.'_'.$3;
                   7450:                         if ($4 eq '') {
                   7451:                             $sec = 'none';
                   7452:                         } else {
                   7453:                             $sec = $4;
                   7454:                         }
                   7455:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7456:                     }
                   7457:                 }
                   7458:                 if (keys(%allroles) == 0) {
                   7459:                     return;
                   7460:                 }
                   7461:                 foreach my $key (@courses_and_groups) {
                   7462:                     my %content = %{$$access_hash{$key}};
                   7463:                     my $cnum = $content{'number'};
                   7464:                     my $cdom = $content{'domain'};
                   7465:                     my $cid = $cdom.'_'.$cnum;
                   7466:                     if (!exists($allroles{$cid})) {
                   7467:                         next;
                   7468:                     }    
                   7469:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7470:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7471:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7472:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7473:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7474:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7475:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7476:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7477:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7478:                                         if (grep/^all$/,@sections) {
                   7479:                                             return 'ok';
                   7480:                                         } else {
                   7481:                                             if (grep/^$sec$/,@sections) {
                   7482:                                                 return 'ok';
                   7483:                                             }
                   7484:                                         }
                   7485:                                     }
                   7486:                                 }
                   7487:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7488:                                     if (grep/^none$/,@groups) {
                   7489:                                         return 'ok';
                   7490:                                     }
                   7491:                                 } else {
                   7492:                                     if (grep/^all$/,@groups) {
                   7493:                                         return 'ok';
                   7494:                                     } 
                   7495:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7496:                                         if (grep/^$group$/,@groups) {
                   7497:                                             return 'ok';
                   7498:                                         }
                   7499:                                     }
                   7500:                                 } 
                   7501:                             }
                   7502:                         }
                   7503:                     }
                   7504:                 }
                   7505:             }
                   7506:             if ($guest) {
                   7507:                 return $guest;
                   7508:             }
                   7509:         }
                   7510:     }
                   7511:     return;
                   7512: }
                   7513: 
                   7514: sub course_group_datechecker {
                   7515:     my ($dates,$now,$status) = @_;
                   7516:     my ($start,$end) = split(/\./,$dates);
                   7517:     if (!$start && !$end) {
                   7518:         return 'ok';
                   7519:     }
                   7520:     if (grep/^active$/,@{$status}) {
                   7521:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7522:             return 'ok';
                   7523:         }
                   7524:     }
                   7525:     if (grep/^previous$/,@{$status}) {
                   7526:         if ($end > $now ) {
                   7527:             return 'ok';
                   7528:         }
                   7529:     }
                   7530:     if (grep/^future$/,@{$status}) {
                   7531:         if ($start > $now) {
                   7532:             return 'ok';
                   7533:         }
                   7534:     }
                   7535:     return; 
                   7536: }
                   7537: 
                   7538: sub parse_portfolio_url {
                   7539:     my ($url) = @_;
                   7540: 
                   7541:     my ($type,$udom,$unum,$group,$file_name);
                   7542:     
1.823     albertel 7543:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7544: 	$type = 1;
                   7545:         $udom = $1;
                   7546:         $unum = $2;
                   7547:         $file_name = $3;
1.823     albertel 7548:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7549: 	$type = 2;
                   7550:         $udom = $1;
                   7551:         $unum = $2;
                   7552:         $group = $3;
                   7553:         $file_name = $3.'/'.$4;
                   7554:     }
                   7555:     if (wantarray) {
                   7556: 	return ($type,$udom,$unum,$file_name,$group);
                   7557:     }
                   7558:     return $type;
                   7559: }
                   7560: 
                   7561: sub is_portfolio_url {
                   7562:     my ($url) = @_;
                   7563:     return scalar(&parse_portfolio_url($url));
                   7564: }
                   7565: 
1.798     raeburn  7566: sub is_portfolio_file {
                   7567:     my ($file) = @_;
1.820     raeburn  7568:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7569:         return 1;
                   7570:     }
                   7571:     return;
                   7572: }
                   7573: 
1.976     raeburn  7574: sub usertools_access {
1.1084    raeburn  7575:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7576:     my ($access,%tools);
                   7577:     if ($context eq '') {
                   7578:         $context = 'tools';
                   7579:     }
                   7580:     if ($context eq 'requestcourses') {
                   7581:         %tools = (
                   7582:                       official   => 1,
                   7583:                       unofficial => 1,
1.1006    raeburn  7584:                       community  => 1,
1.1172.2.37  raeburn  7585:                       textbook   => 1,
1.985     raeburn  7586:                  );
1.1172.2.9  raeburn  7587:     } elsif ($context eq 'requestauthor') {
                   7588:         %tools = (
                   7589:                       requestauthor => 1,
                   7590:                  );
1.985     raeburn  7591:     } else {
                   7592:         %tools = (
                   7593:                       aboutme   => 1,
                   7594:                       blog      => 1,
1.1172.2.6  raeburn  7595:                       webdav    => 1,
1.985     raeburn  7596:                       portfolio => 1,
                   7597:                  );
                   7598:     }
1.976     raeburn  7599:     return if (!defined($tools{$tool}));
                   7600: 
1.1172.2.35  raeburn  7601:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7602:         $udom = $env{'user.domain'};
                   7603:         $uname = $env{'user.name'};
                   7604:     }
                   7605: 
1.978     raeburn  7606:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7607:         if ($action ne 'reload') {
1.985     raeburn  7608:             if ($context eq 'requestcourses') {
                   7609:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7610:             } elsif ($context eq 'requestauthor') {
                   7611:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7612:             } else {
                   7613:                 return $env{'environment.availabletools.'.$tool};
                   7614:             }
                   7615:         }
1.976     raeburn  7616:     }
                   7617: 
1.1172.2.9  raeburn  7618:     my ($toolstatus,$inststatus,$envkey);
                   7619:     if ($context eq 'requestauthor') {
                   7620:         $envkey = $context;
                   7621:     } else {
                   7622:         $envkey = $context.'.'.$tool;
                   7623:     }
1.976     raeburn  7624: 
1.985     raeburn  7625:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7626:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7627:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7628:         $inststatus = $env{'environment.inststatus'};
                   7629:     } else {
1.1084    raeburn  7630:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7631:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7632:             $inststatus = $userenvref->{'inststatus'};
                   7633:         } else {
1.1172.2.9  raeburn  7634:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7635:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7636:             $inststatus = $userenv{'inststatus'};
                   7637:         }
1.976     raeburn  7638:     }
                   7639: 
                   7640:     if ($toolstatus ne '') {
                   7641:         if ($toolstatus) {
                   7642:             $access = 1;
                   7643:         } else {
                   7644:             $access = 0;
                   7645:         }
                   7646:         return $access;
                   7647:     }
                   7648: 
1.1084    raeburn  7649:     my ($is_adv,%domdef);
                   7650:     if (ref($is_advref) eq 'HASH') {
                   7651:         $is_adv = $is_advref->{'is_adv'};
                   7652:     } else {
                   7653:         $is_adv = &is_advanced_user($udom,$uname);
                   7654:     }
                   7655:     if (ref($domdefref) eq 'HASH') {
                   7656:         %domdef = %{$domdefref};
                   7657:     } else {
                   7658:         %domdef = &get_domain_defaults($udom);
                   7659:     }
1.976     raeburn  7660:     if (ref($domdef{$tool}) eq 'HASH') {
                   7661:         if ($is_adv) {
                   7662:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7663:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7664:                     $access = 1;
                   7665:                 } else {
                   7666:                     $access = 0;
                   7667:                 }
                   7668:                 return $access;
                   7669:             }
                   7670:         }
                   7671:         if ($inststatus ne '') {
                   7672:             my ($hasaccess,$hasnoaccess);
                   7673:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7674:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7675:                     if ($domdef{$tool}{$affiliation}) {
                   7676:                         $hasaccess = 1;
                   7677:                     } else {
                   7678:                         $hasnoaccess = 1;
                   7679:                     }
                   7680:                 }
                   7681:             }
                   7682:             if ($hasaccess || $hasnoaccess) {
                   7683:                 if ($hasaccess) {
                   7684:                     $access = 1;
                   7685:                 } elsif ($hasnoaccess) {
                   7686:                     $access = 0; 
                   7687:                 }
                   7688:                 return $access;
                   7689:             }
                   7690:         } else {
                   7691:             if ($domdef{$tool}{'default'} ne '') {
                   7692:                 if ($domdef{$tool}{'default'}) {
                   7693:                     $access = 1;
                   7694:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7695:                     $access = 0;
                   7696:                 }
                   7697:                 return $access;
                   7698:             }
                   7699:         }
                   7700:     } else {
1.1172.2.6  raeburn  7701:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7702:             $access = 1;
                   7703:         } else {
                   7704:             $access = 0;
                   7705:         }
1.976     raeburn  7706:         return $access;
                   7707:     }
                   7708: }
                   7709: 
1.1050    raeburn  7710: sub is_course_owner {
                   7711:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7712:     if (($udom eq '') || ($uname eq '')) {
                   7713:         $udom = $env{'user.domain'};
                   7714:         $uname = $env{'user.name'};
                   7715:     }
                   7716:     unless (($udom eq '') || ($uname eq '')) {
                   7717:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7718:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7719:                 return 1;
                   7720:             } else {
                   7721:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7722:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7723:                     return 1;
                   7724:                 }
                   7725:             }
                   7726:         }
                   7727:     }
                   7728:     return;
                   7729: }
                   7730: 
1.976     raeburn  7731: sub is_advanced_user {
                   7732:     my ($udom,$uname) = @_;
1.1085    raeburn  7733:     if ($udom ne '' && $uname ne '') {
                   7734:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7735:             if (wantarray) {
                   7736:                 return ($env{'user.adv'},$env{'user.author'});
                   7737:             } else {
                   7738:                 return $env{'user.adv'};
                   7739:             }
1.1085    raeburn  7740:         }
                   7741:     }
1.976     raeburn  7742:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7743:     my %allroles;
1.1128    raeburn  7744:     my ($is_adv,$is_author);
1.976     raeburn  7745:     foreach my $role (keys(%roleshash)) {
                   7746:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7747:         my $area = '/'.$tdomain.'/'.$trest;
                   7748:         if ($sec ne '') {
                   7749:             $area .= '/'.$sec;
                   7750:         }
                   7751:         if (($area ne '') && ($trole ne '')) {
                   7752:             my $spec=$trole.'.'.$area;
                   7753:             if ($trole =~ /^cr\//) {
                   7754:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7755:             } elsif ($trole ne 'gr') {
                   7756:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7757:             }
1.1128    raeburn  7758:             if ($trole eq 'au') {
                   7759:                 $is_author = 1;
                   7760:             }
1.976     raeburn  7761:         }
                   7762:     }
                   7763:     foreach my $role (keys(%allroles)) {
                   7764:         last if ($is_adv);
                   7765:         foreach my $item (split(/:/,$allroles{$role})) {
                   7766:             if ($item ne '') {
                   7767:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7768:                 if ($privilege eq 'adv') {
                   7769:                     $is_adv = 1;
                   7770:                     last;
                   7771:                 }
                   7772:             }
                   7773:         }
                   7774:     }
1.1128    raeburn  7775:     if (wantarray) {
                   7776:         return ($is_adv,$is_author);
                   7777:     }
1.976     raeburn  7778:     return $is_adv;
                   7779: }
1.798     raeburn  7780: 
1.1035    raeburn  7781: sub check_can_request {
1.1036    raeburn  7782:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7783:     my $canreq = 0;
                   7784:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7785:     my @options = ('approval','validate','autolimit');
                   7786:     my $optregex = join('|',@options);
                   7787:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7788:         foreach my $type (@{$types}) {
                   7789:             if (&usertools_access($env{'user.name'},
                   7790:                                   $env{'user.domain'},
                   7791:                                   $type,undef,'requestcourses')) {
                   7792:                 $canreq ++;
1.1036    raeburn  7793:                 if (ref($request_domains) eq 'HASH') {
                   7794:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7795:                 }
1.1035    raeburn  7796:                 if ($dom eq $env{'user.domain'}) {
                   7797:                     $can_request->{$type} = 1;
                   7798:                 }
                   7799:             }
                   7800:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7801:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7802:                 if (@curr > 0) {
1.1036    raeburn  7803:                     foreach my $item (@curr) {
                   7804:                         if (ref($request_domains) eq 'HASH') {
                   7805:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7806:                             if ($otherdom ne '') {
                   7807:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7808:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7809:                                         push(@{$request_domains->{$type}},$otherdom);
                   7810:                                     }
                   7811:                                 } else {
                   7812:                                     push(@{$request_domains->{$type}},$otherdom);
                   7813:                                 }
                   7814:                             }
                   7815:                         }
                   7816:                     }
                   7817:                     unless($dom eq $env{'user.domain'}) {
                   7818:                         $canreq ++;
1.1035    raeburn  7819:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7820:                             $can_request->{$type} = 1;
                   7821:                         }
                   7822:                     }
                   7823:                 }
                   7824:             }
                   7825:         }
                   7826:     }
                   7827:     return $canreq;
                   7828: }
                   7829: 
1.341     www      7830: # ---------------------------------------------- Custom access rule evaluation
                   7831: 
                   7832: sub customaccess {
                   7833:     my ($priv,$uri)=@_;
1.807     albertel 7834:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7835:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7836:     $udom = &LONCAPA::clean_domain($udom);
                   7837:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7838:     my $access=0;
1.800     albertel 7839:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7840: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7841: 	if ($type eq 'user') {
                   7842: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7843: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7844: 		if ($tdom) {
                   7845: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7846: 		}
1.896     albertel 7847: 		if ($tuname) {
                   7848: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7849: 		}
                   7850: 		$access=($effect eq 'allow');
                   7851: 		last;
                   7852: 	    }
                   7853: 	} else {
                   7854: 	    if ($role) {
                   7855: 		if ($role ne $urole) { next; }
                   7856: 	    }
                   7857: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7858: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7859: 		if ($tdom) {
                   7860: 		    if ($tdom ne $udom) { next; }
                   7861: 		}
                   7862: 		if ($tcrs) {
                   7863: 		    if ($tcrs ne $ucrs) { next; }
                   7864: 		}
                   7865: 		if ($tsec) {
                   7866: 		    if ($tsec ne $usec) { next; }
                   7867: 		}
                   7868: 		$access=($effect eq 'allow');
                   7869: 		last;
                   7870: 	    }
                   7871: 	    if ($realm eq '' && $role eq '') {
                   7872: 		$access=($effect eq 'allow');
                   7873: 	    }
1.402     bowersj2 7874: 	}
1.341     www      7875:     }
                   7876:     return $access;
                   7877: }
                   7878: 
1.103     harris41 7879: # ------------------------------------------------- Check for a user privilege
1.12      www      7880: 
                   7881: sub allowed {
1.1172.2.118.  .8(raebu 7882:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7883:     my $ver_orguri=$uri;
1.439     www      7884:     $uri=&deversion($uri);
1.152     www      7885:     my $orguri=$uri;
1.52      www      7886:     $uri=&declutter($uri);
1.809     raeburn  7887: 
1.810     raeburn  7888:     if ($priv eq 'evb') {
                   7889: # Evade communication block restrictions for specified role in a course
                   7890:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7891:             return $1;
                   7892:         } else {
                   7893:             return;
                   7894:         }
                   7895:     }
                   7896: 
1.620     albertel 7897:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7898: # Free bre access to adm and meta resources
1.1172.2.118.  .13(raeb 7899:-21):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 7900: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7901: 	&& ($priv eq 'bre')) {
1.14      www      7902: 	return 'F';
1.159     www      7903:     }
                   7904: 
1.545     banghart 7905: # Free bre access to user's own portfolio contents
1.714     raeburn  7906:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7907:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7908: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7909:         my %setters;
                   7910:         my ($startblock,$endblock) = 
                   7911:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7912:         if ($startblock && $endblock) {
                   7913:             return 'B';
                   7914:         } else {
                   7915:             return 'F';
                   7916:         }
1.545     banghart 7917:     }
                   7918: 
1.762     raeburn  7919: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7920:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7921:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7922:         if (exists($env{'request.course.id'})) {
                   7923:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7924:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7925:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7926:                 my $courseprivid=$env{'request.course.id'};
                   7927:                 $courseprivid=~s/\_/\//;
                   7928:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7929:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7930:                     return $1; 
1.762     raeburn  7931:                 } else {
                   7932:                     if ($env{'request.course.sec'}) {
                   7933:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7934:                     }
                   7935:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7936:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7937:                         return $2;
                   7938:                     }
1.714     raeburn  7939:                 }
                   7940:             }
                   7941:         }
                   7942:     }
                   7943: 
1.159     www      7944: # Free bre to public access
                   7945: 
                   7946:     if ($priv eq 'bre') {
1.238     www      7947:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7948: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7949:            return 'F'; 
                   7950:         }
1.238     www      7951:         if ($copyright eq 'priv') {
                   7952:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7953: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7954: 		return '';
                   7955:             }
                   7956:         }
                   7957:         if ($copyright eq 'domain') {
                   7958:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7959: 	    unless (($env{'user.domain'} eq $1) ||
                   7960:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7961: 		return '';
                   7962:             }
1.262     matthew  7963:         }
1.620     albertel 7964:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7965:             # Library role, so allow browsing of resources in this domain.
                   7966:             return 'F';
1.238     www      7967:         }
1.341     www      7968:         if ($copyright eq 'custom') {
                   7969: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7970:         }
1.14      www      7971:     }
1.264     matthew  7972:     # Domain coordinator is trying to create a course
1.620     albertel 7973:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7974:         # uri is the requested domain in this case.
                   7975:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7976:         # a role of dc for the domain in question.
1.620     albertel 7977:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7978:     }
1.29      www      7979: 
1.52      www      7980:     my $thisallowed='';
                   7981:     my $statecond=0;
                   7982:     my $courseprivid='';
                   7983: 
1.1039    raeburn  7984:     my $ownaccess;
1.1043    raeburn  7985:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7986:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7987:         if ($uri eq '') {
                   7988:             $ownaccess = 1;
                   7989:         } else {
                   7990:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7991:                 my $udom = $env{'user.domain'};
                   7992:                 my $uname = $env{'user.name'};
                   7993:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7994:                     $ownaccess = 1;
1.1040    raeburn  7995:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7996:                     unless ($uri =~ m{\.\./}) {
                   7997:                         $ownaccess = 1;
                   7998:                     }
                   7999:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8000:                     my $now = time;
                   8001:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8002:                         my $adom = $1;
                   8003:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8004:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.118.  .21(raeb 8005:-21):                                 my ($start,$end) = split(/\./,$env{$key});
                   8006:-21):                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8007:                                     $ownaccess = 1;
                   8008:                                     last;
                   8009:                                 }
                   8010:                             }
                   8011:                         }
                   8012:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8013:                         my $adom = $1;
                   8014:                         my $aname = $2;
1.1042    raeburn  8015:                         foreach my $role ('ca','aa') { 
                   8016:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8017:                                 my ($start,$end) =
1.1172.2.118.  .21(raeb 8018:-21):                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8019:-21):                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8020:                                     $ownaccess = 1;
                   8021:                                     last;
                   8022:                                 }
1.1039    raeburn  8023:                             }
                   8024:                         }
                   8025:                     }
                   8026:                 }
                   8027:             }
                   8028:         }
                   8029:     }
                   8030: 
1.52      www      8031: # Course
                   8032: 
1.620     albertel 8033:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8034:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8035:             $thisallowed.=$1;
                   8036:         }
1.52      www      8037:     }
1.29      www      8038: 
1.52      www      8039: # Domain
                   8040: 
1.620     albertel 8041:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8042:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8043:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8044:             $thisallowed.=$1;
                   8045:         }
1.12      www      8046:     }
1.52      www      8047: 
1.1141    raeburn  8048: # User who is not author or co-author might still be able to edit
                   8049: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8050:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8051:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8052:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8053:             $thisallowed.=$1;
                   8054:         }
                   8055:     }
                   8056: 
1.52      www      8057: # Course: uri itself is a course
1.66      www      8058:     my $courseuri=$uri;
                   8059:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8060:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8061: 
1.620     albertel 8062:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8063:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8064:         if ($priv eq 'mip') {
                   8065:             my $rem = $1;
                   8066:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8067:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8068:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8069:                 if ($cdom ne '') {
                   8070:                     my %passwdconf = &get_passwdconf($cdom);
                   8071:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8072:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8073:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8074:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8075:                                 unless (@inststatuses) {
                   8076:                                     @inststatuses = ('default');
                   8077:                                 }
                   8078:                                 foreach my $status (@inststatuses) {
                   8079:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8080:                                         $thisallowed.=$rem;
                   8081:                                     }
                   8082:                                 }
                   8083:                             }
                   8084:                         }
                   8085:                     }
                   8086:                 }
                   8087:             }
                   8088:         } else {
                   8089:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8090:                 $thisallowed.=$1;
                   8091:             }
1.1039    raeburn  8092:         }
1.12      www      8093:     }
1.29      www      8094: 
1.665     albertel 8095: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8096: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8097:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8098: 	$thisallowed='';
1.671     raeburn  8099:         my ($match)=&is_on_map($uri);
                   8100:         if ($match) {
                   8101:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8102:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8103:                 my $value = $1;
                   8104:                 if ($noblockcheck) {
                   8105:                     $thisallowed.=$value;
1.1162    raeburn  8106:                 } else {
1.1172.2.118.  .8(raebu 8107:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8108:                     if (@blockers > 0) {
                   8109:                         $thisallowed = 'B';
                   8110:                     } else {
                   8111:                         $thisallowed.=$value;
                   8112:                     }
1.1162    raeburn  8113:                 }
1.671     raeburn  8114:             }
                   8115:         } else {
1.705     albertel 8116:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8117:             if ($refuri) {
                   8118:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8119:                     $thisallowed='F';
1.671     raeburn  8120:                 } else {
                   8121:                     $refuri=&declutter($refuri);
                   8122:                     my ($match) = &is_on_map($refuri);
                   8123:                     if ($match) {
1.1172.2.65  raeburn  8124:                         if ($noblockcheck) {
1.1162    raeburn  8125:                             $thisallowed='F';
1.1172.2.65  raeburn  8126:                         } else {
1.1172.2.118.  .8(raebu 8127:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8128:                             if (@blockers > 0) {
                   8129:                                 $thisallowed = 'B';
                   8130:                             } else {
                   8131:                                 $thisallowed='F';
                   8132:                             }
1.1162    raeburn  8133:                         }
1.671     raeburn  8134:                     }
1.669     raeburn  8135:                 }
1.671     raeburn  8136:             }
                   8137:         }
1.314     www      8138:     }
1.492     albertel 8139: 
1.766     albertel 8140:     if ($priv eq 'bre'
                   8141: 	&& $thisallowed ne 'F' 
                   8142: 	&& $thisallowed ne '2'
                   8143: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8144: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8145:     }
1.1172.2.118.  .8(raebu 8146:20): 
1.52      www      8147: # Full access at system, domain or course-wide level? Exit.
1.29      www      8148:     if ($thisallowed=~/F/) {
                   8149: 	return 'F';
                   8150:     }
                   8151: 
1.52      www      8152: # If this is generating or modifying users, exit with special codes
1.29      www      8153: 
1.643     www      8154:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8155: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8156: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8157: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8158: 	    unless ($auname) { return $thisallowed; }
                   8159: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8160: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8161: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8162: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8163: 	}
1.52      www      8164: 	return $thisallowed;
                   8165:     }
                   8166: #
1.103     harris41 8167: # Gathered so far: system, domain and course wide privileges
1.52      www      8168: #
                   8169: # Course: See if uri or referer is an individual resource that is part of 
                   8170: # the course
                   8171: 
1.620     albertel 8172:     if ($env{'request.course.id'}) {
1.232     www      8173: 
1.1172.2.115  raeburn  8174: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8175: 
                   8176:         if ($priv eq 'mip') {
                   8177:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8178:                 return $thisallowed;
                   8179:             } else {
                   8180:                 return '';
                   8181:             }
                   8182:         }
                   8183: 
1.620     albertel 8184:        $courseprivid=$env{'request.course.id'};
                   8185:        if ($env{'request.course.sec'}) {
                   8186:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8187:        }
                   8188:        $courseprivid=~s/\_/\//;
                   8189:        my $checkreferer=1;
1.232     www      8190:        my ($match,$cond)=&is_on_map($uri);
                   8191:        if ($match) {
                   8192:            $statecond=$cond;
1.620     albertel 8193:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8194:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8195:                my $value = $1;
                   8196:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8197:                    if ($noblockcheck) {
1.1162    raeburn  8198:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8199:                    } else {
1.1172.2.118.  .8(raebu 8200:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8201:                        if (@blockers > 0) {
                   8202:                            $thisallowed = 'B';
                   8203:                        } else {
                   8204:                            $thisallowed.=$value;
                   8205:                        }
1.1162    raeburn  8206:                    }
                   8207:                } else {
                   8208:                    $thisallowed.=$value;
                   8209:                }
1.52      www      8210:                $checkreferer=0;
                   8211:            }
1.29      www      8212:        }
1.1172.2.118.  .8(raebu 8213:20): 
1.148     www      8214:        if ($checkreferer) {
1.620     albertel 8215: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8216:             unless ($refuri) {
1.800     albertel 8217:                 foreach my $key (keys(%env)) {
                   8218: 		    if ($key=~/^httpref\..*\*/) {
                   8219: 			my $pattern=$key;
1.156     www      8220:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8221:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8222:                         $pattern=~s/\//\\\//g;
1.152     www      8223:                         if ($orguri=~/$pattern/) {
1.800     albertel 8224: 			    $refuri=$env{$key};
1.148     www      8225:                         }
                   8226:                     }
1.191     harris41 8227:                 }
1.148     www      8228:             }
1.232     www      8229: 
1.148     www      8230:          if ($refuri) { 
1.152     www      8231: 	  $refuri=&declutter($refuri);
1.232     www      8232:           my ($match,$cond)=&is_on_map($refuri);
                   8233:             if ($match) {
                   8234:               my $refstatecond=$cond;
1.620     albertel 8235:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8236:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8237:                   my $value = $1;
                   8238:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8239:                       if ($noblockcheck) {
1.1162    raeburn  8240:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8241:                       } else {
1.1172.2.118.  .8(raebu 8242:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8243:                           if (@blockers > 0) {
                   8244:                               $thisallowed = 'B';
                   8245:                           } else {
                   8246:                               $thisallowed.=$value;
                   8247:                           }
1.1162    raeburn  8248:                       }
                   8249:                   } else {
                   8250:                       $thisallowed.=$value;
                   8251:                   }
1.53      www      8252:                   $uri=$refuri;
                   8253:                   $statecond=$refstatecond;
1.52      www      8254:               }
                   8255:           }
1.148     www      8256:         }
1.29      www      8257:        }
1.52      www      8258:    }
1.29      www      8259: 
1.52      www      8260: #
1.103     harris41 8261: # Gathered now: all privileges that could apply, and condition number
1.52      www      8262: # 
                   8263: #
                   8264: # Full or no access?
                   8265: #
1.29      www      8266: 
1.52      www      8267:     if ($thisallowed=~/F/) {
                   8268: 	return 'F';
                   8269:     }
1.29      www      8270: 
1.52      www      8271:     unless ($thisallowed) {
                   8272:         return '';
                   8273:     }
1.29      www      8274: 
1.52      www      8275: # Restrictions exist, deal with them
                   8276: #
                   8277: #   C:according to course preferences
                   8278: #   R:according to resource settings
                   8279: #   L:unless locked
                   8280: #   X:according to user session state
                   8281: #
                   8282: 
                   8283: # Possibly locked functionality, check all courses
1.1172.2.118.  .21(raeb 8284:-21): # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8285: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.118.  .21(raeb 8286:-21): # courses, and 2 minutes for current course, in which user has st or ta role
                   8287:-21): # which is neither expired nor a future role (unless current course).
1.52      www      8288: 
1.1172.2.118.  .21(raeb 8289:-21):     my ($needlockcheck,$now,$crsonly);
1.52      www      8290:     if ($thisallowed=~/L/) {
1.1172.2.118.  .21(raeb 8291:-21):         $now = time;
                   8292:-21):         if ($priv eq 'bre') {
                   8293:-21):             if ($uri ne '') {
                   8294:-21):                 if ($orguri =~ m{^/+res/}) {
                   8295:-21):                     if ($uri =~ m{^lib/templates/}) {
                   8296:-21):                         if ($env{'request.course.id'}) {
                   8297:-21):                             $crsonly = 1;
                   8298:-21):                             $needlockcheck = 1;
                   8299:-21):                         }
                   8300:-21):                     } else {
                   8301:-21):                         $needlockcheck = 1;
                   8302:-21):                     }
                   8303:-21):                 } elsif ($env{'request.course.id'}) {
                   8304:-21):                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8305:-21):                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8306:-21):                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8307:-21):                         $crsonly = 1;
                   8308:-21):                     }
                   8309:-21):                     $needlockcheck = 1;
                   8310:-21):                 }
                   8311:-21):             }
                   8312:-21):         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8313:-21):             $needlockcheck = 1;
                   8314:-21):         }
                   8315:-21):     }
                   8316:-21):     if ($needlockcheck) {
                   8317:-21):         foreach my $envkey (keys(%env)) {
1.54      www      8318:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8319:                my $courseid=$2;
                   8320:                my $roleid=$1.'.'.$2;
1.92      www      8321:                $courseid=~s/^\///;
1.1172.2.118.  .21(raeb 8322:-21):                unless ($env{'request.role'} eq $roleid) {
                   8323:-21):                    my ($start,$end) = split(/\./,$env{$envkey});
                   8324:-21):                    next unless (($now >= $start) && (!$end || $end > $now));
                   8325:-21):                }
1.54      www      8326:                my $expiretime=600;
1.620     albertel 8327:                if ($env{'request.role'} eq $roleid) {
1.54      www      8328: 		  $expiretime=120;
                   8329:                }
                   8330: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8331:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8332:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8333: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8334:                }
1.620     albertel 8335:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8336:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8337: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8338:                        &log($env{'user.domain'},$env{'user.name'},
                   8339:                             $env{'user.home'},
1.57      www      8340:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8341:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8342:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8343: 		       return '';
                   8344:                    }
                   8345:                }
1.620     albertel 8346:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8347:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.118.  .21(raeb 8348:-21): 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8349:                        &log($env{'user.domain'},$env{'user.name'},
                   8350:                             $env{'user.home'},
1.57      www      8351:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8352:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8353:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8354: 		       return '';
                   8355:                    }
                   8356:                }
                   8357: 	   }
1.29      www      8358:        }
1.52      www      8359:     }
1.1172.2.118.  .8(raebu 8360:20): 
1.52      www      8361: #
                   8362: # Rest of the restrictions depend on selected course
                   8363: #
                   8364: 
1.620     albertel 8365:     unless ($env{'request.course.id'}) {
1.766     albertel 8366: 	if ($thisallowed eq 'A') {
                   8367: 	    return 'A';
1.814     raeburn  8368:         } elsif ($thisallowed eq 'B') {
                   8369:             return 'B';
1.766     albertel 8370: 	} else {
                   8371: 	    return '1';
                   8372: 	}
1.52      www      8373:     }
1.29      www      8374: 
1.52      www      8375: #
                   8376: # Now user is definitely in a course
                   8377: #
1.53      www      8378: 
                   8379: 
                   8380: # Course preferences
                   8381: 
                   8382:    if ($thisallowed=~/C/) {
1.620     albertel 8383:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8384:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8385:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8386: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8387: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8388: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8389: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8390: 			$env{'request.course.id'});
                   8391: 	   }
1.237     www      8392:            return '';
                   8393:        }
                   8394: 
1.620     albertel 8395:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8396: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8397: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8398: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8399: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8400: 			$env{'request.course.id'});
                   8401: 	   }
1.54      www      8402:            return '';
                   8403:        }
1.53      www      8404:    }
                   8405: 
                   8406: # Resource preferences
                   8407: 
                   8408:    if ($thisallowed=~/R/) {
1.620     albertel 8409:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8410:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8411: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8412: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8413: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8414: 	   }
                   8415: 	   return '';
1.54      www      8416:        }
1.53      www      8417:    }
1.30      www      8418: 
1.246     www      8419: # Restricted by state or randomout?
1.30      www      8420: 
1.52      www      8421:    if ($thisallowed=~/X/) {
1.620     albertel 8422:       if ($env{'acc.randomout'}) {
1.579     albertel 8423: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8424:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8425:             return ''; 
                   8426:          }
1.247     www      8427:       }
                   8428:       if (&condval($statecond)) {
1.52      www      8429: 	 return '2';
                   8430:       } else {
                   8431:          return '';
                   8432:       }
                   8433:    }
1.30      www      8434: 
1.766     albertel 8435:     if ($thisallowed eq 'A') {
                   8436: 	return 'A';
1.814     raeburn  8437:     } elsif ($thisallowed eq 'B') {
                   8438:         return 'B';
1.766     albertel 8439:     }
1.52      www      8440:    return 'F';
1.232     www      8441: }
1.1162    raeburn  8442: 
1.1172.2.13  raeburn  8443: # ------------------------------------------- Check construction space access
                   8444: 
                   8445: sub constructaccess {
                   8446:     my ($url,$setpriv)=@_;
                   8447: 
                   8448: # We do not allow editing of previous versions of files
                   8449:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8450: 
                   8451: # Get username and domain from URL
                   8452:     my ($ownername,$ownerdomain,$ownerhome);
                   8453: 
                   8454:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8455:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8456: 
                   8457: # The URL does not really point to any authorspace, forget it
                   8458:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8459: 
                   8460: # Now we need to see if the user has access to the authorspace of
                   8461: # $ownername at $ownerdomain
                   8462: 
                   8463:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8464: # Real author for this?
                   8465:        $ownerhome = $env{'user.home'};
                   8466:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8467:           return ($ownername,$ownerdomain,$ownerhome);
                   8468:        }
                   8469:     } else {
                   8470: # Co-author for this?
                   8471:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8472:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8473:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8474:             return ($ownername,$ownerdomain,$ownerhome);
                   8475:         }
                   8476:     }
                   8477: 
                   8478: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8479: # we might as well leave
                   8480:    unless ($setpriv) { return ''; }
                   8481: 
                   8482: # Backdoor access?
                   8483:     my $allowed=&allowed('eco',$ownerdomain);
                   8484: # Nope
                   8485:     unless ($allowed) { return ''; }
                   8486: # Looks like we may have access, but could be locked by the owner of the construction space
                   8487:     if ($allowed eq 'U') {
                   8488:         my %blocked=&get('environment',['domcoord.author'],
                   8489:                          $ownerdomain,$ownername);
                   8490: # Is blocked by owner
                   8491:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8492:     }
                   8493:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8494: # Grant temporary access
                   8495:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8496:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8497:         if (!$update) { $update = $then; }
                   8498:         my $refresh=$env{'user.refresh.time'};
                   8499:         if (!$refresh) { $refresh = $update; }
                   8500:         my $now = time;
                   8501:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8502:                            $now,'ca','constructaccess');
                   8503:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8504:         return($ownername,$ownerdomain,$ownerhome);
                   8505:     }
                   8506: # No business here
                   8507:     return '';
                   8508: }
                   8509: 
1.1172.2.66  raeburn  8510: # ----------------------------------------------------------- Content Blocking
                   8511: 
                   8512: {
                   8513: # Caches for faster Course Contents display where content blocking
                   8514: # is in operation (i.e., interval param set) for timed quiz.
                   8515: #
                   8516: # User for whom data are being temporarily cached.
                   8517: my $cacheduser='';
1.1172.2.118.  .8(raebu 8518:20): # Course for which data are being temporarily cached.
                   8519:20): my $cachedcid='';
1.1172.2.66  raeburn  8520: # Cached blockers for this user (a hash of blocking items).
                   8521: my %cachedblockers=();
                   8522: # When the data were last cached.
                   8523: my $cachedlast='';
                   8524: 
                   8525: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8526:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8527:     if (($uname ne '') && ($udom ne '')) {
                   8528:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8529:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8530:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8531:             return;
                   8532:         }
                   8533:     }
                   8534:     $cachedlast=time;
                   8535:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8536:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8537:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8538:20):     return;
1.1172.2.66  raeburn  8539: }
                   8540: 
1.1162    raeburn  8541: sub get_comm_blocks {
                   8542:     my ($cdom,$cnum) = @_;
                   8543:     if ($cdom eq '' || $cnum eq '') {
                   8544:         return unless ($env{'request.course.id'});
                   8545:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8546:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8547:     }
                   8548:     my %commblocks;
                   8549:     my $hashid=$cdom.'_'.$cnum;
                   8550:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8551:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8552:         %commblocks = %{$blocksref};
                   8553:     } else {
                   8554:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8555:         my $cachetime = 600;
                   8556:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8557:     }
                   8558:     return %commblocks;
                   8559: }
                   8560: 
1.1172.2.66  raeburn  8561: sub get_commblock_resources {
                   8562:     my ($blocks) = @_;
                   8563:     my %blockers = ();
                   8564:     return %blockers unless ($env{'request.course.id'});
                   8565:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8566:     my %commblocks;
                   8567:     if (ref($blocks) eq 'HASH') {
                   8568:         %commblocks = %{$blocks};
                   8569:     } else {
                   8570:         %commblocks = &get_comm_blocks();
                   8571:     }
1.1172.2.66  raeburn  8572:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8573:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8574:     return %blockers unless (ref($navmap));
                   8575:     my $now = time;
1.1162    raeburn  8576:     foreach my $block (keys(%commblocks)) {
                   8577:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8578:             my ($start,$end) = ($1,$2);
                   8579:             if ($start <= $now && $end >= $now) {
                   8580:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8581:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8582:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8583:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8584:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8585:                             }
                   8586:                         }
                   8587:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8588:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8589:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8590:                             }
                   8591:                         }
                   8592:                     }
                   8593:                 }
                   8594:             }
                   8595:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8596:             my $item = $1;
1.1163    raeburn  8597:             my @to_test;
1.1162    raeburn  8598:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8599:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8600:                     my @interval;
                   8601:                     my $type = 'map';
                   8602:                     if ($item eq 'course') {
                   8603:                         $type = 'course';
                   8604:                         @interval=&EXT("resource.0.interval");
                   8605:                     } else {
                   8606:                         if ($item =~ /___\d+___/) {
                   8607:                             $type = 'resource';
                   8608:                             @interval=&EXT("resource.0.interval",$item);
                   8609:                             if (ref($navmap)) {
                   8610:                                 my $res = $navmap->getBySymb($item);
                   8611:                                 push(@to_test,$res);
                   8612:                             }
1.1162    raeburn  8613:                         } else {
1.1172.2.66  raeburn  8614:                             my $mapsymb = &symbread($item,1);
                   8615:                             if ($mapsymb) {
                   8616:                                 if (ref($navmap)) {
                   8617:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118.  .11(raeb 8618:-20):                                     if (ref($mapres)) {
                   8619:-20):                                         my $first = $mapres->map_start();
                   8620:-20):                                         my $finish = $mapres->map_finish();
                   8621:-20):                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8622:-20):                                         if (ref($it)) {
                   8623:-20):                                             my $res;
                   8624:-20):                                             while ($res = $it->next(undef,1)) {
                   8625:-20):                                                 next unless (ref($res));
                   8626:-20):                                                 my $symb = $res->symb();
                   8627:-20):                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8628:-20):                                                 @interval=&EXT("resource.0.interval",$symb);
                   8629:-20):                                                 if ($interval[1] eq 'map') {
                   8630:-20):                                                     if ($res->answerable()) {
                   8631:-20):                                                         push(@to_test,$res);
                   8632:-20):                                                         last;
                   8633:-20):                                                     }
                   8634:-20):                                                 }
1.1162    raeburn  8635:                                             }
                   8636:                                         }
                   8637:                                     }
                   8638:                                 }
                   8639:                             }
                   8640:                         }
1.1172.2.66  raeburn  8641:                     }
1.1172.2.118.  .1(raebu 8642:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8643:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8644:                         my $first_access;
                   8645:                         if ($type eq 'resource') {
                   8646:                             $first_access=&get_first_access($interval[1],$item);
                   8647:                         } elsif ($type eq 'map') {
                   8648:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8649:                         } else {
                   8650:                             $first_access=&get_first_access($interval[1]);
                   8651:                         }
                   8652:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8653:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8654:                             if ($timesup > $now) {
                   8655:                                 my $activeblock;
                   8656:                                 foreach my $res (@to_test) {
                   8657:                                     if ($res->answerable()) {
                   8658:                                         $activeblock = 1;
                   8659:                                         last;
                   8660:                                     }
                   8661:                                 }
                   8662:                                 if ($activeblock) {
                   8663:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8664:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8665:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8666:                                          }
                   8667:                                     }
                   8668:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8669:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8670:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8671:                                         }
1.1162    raeburn  8672:                                     }
                   8673:                                 }
                   8674:                             }
                   8675:                         }
                   8676:                     }
                   8677:                 }
                   8678:             }
                   8679:         }
                   8680:     }
1.1172.2.66  raeburn  8681:     return %blockers;
1.1162    raeburn  8682: }
                   8683: 
1.1172.2.66  raeburn  8684: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8685:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8686:     my @blockers;
                   8687:     return unless ($env{'request.course.id'});
                   8688:     return unless ($priv eq 'bre');
                   8689:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8690:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8691:20):     my %blockinfo;
                   8692:20):     if (ref($blocks) eq 'HASH') {
                   8693:20):         %blockinfo = &get_commblock_resources($blocks);
                   8694:20):     } else {
                   8695:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8696:20):         %blockinfo = %cachedblockers;
                   8697:20):     }
                   8698:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8699:     my (%possibles,@symbs);
                   8700:     if (!$symb) {
1.1172.2.118.  .9(raebu 8701:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8702:     }
1.1172.2.66  raeburn  8703:     if ($symb) {
                   8704:         @symbs = ($symb);
                   8705:     } elsif (keys(%possibles)) {
                   8706:         @symbs = keys(%possibles);
                   8707:     }
                   8708:     my $noblock;
                   8709:     foreach my $symb (@symbs) {
                   8710:         last if ($noblock);
                   8711:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8712:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8713:             if ($block =~ /^firstaccess____(.+)$/) {
                   8714:                 my $item = $1;
1.1172.2.118.  .8(raebu 8715:20):                 unless ($blocked) {
                   8716:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8717:20):                         $noblock = 1;
                   8718:20):                         last;
                   8719:20):                     }
1.1172.2.66  raeburn  8720:                 }
1.1162    raeburn  8721:             }
1.1172.2.118.  .9(raebu 8722:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8723:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8724:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8725:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8726:                             push(@blockers,$block);
                   8727:                         }
                   8728:                     }
                   8729:                 }
1.1172.2.118.  .9(raebu 8730:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8731:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8732:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8733:20):                             push(@blockers,$block);
                   8734:20):                         }
1.1172.2.66  raeburn  8735:                     }
                   8736:                 }
1.1162    raeburn  8737:             }
                   8738:         }
                   8739:     }
1.1172.2.118.  .8(raebu 8740:20):     unless ($noblock) {
                   8741:20):         return @blockers;
                   8742:20):     }
                   8743:20):     return;
1.1172.2.66  raeburn  8744: }
1.1162    raeburn  8745: }
                   8746: 
1.1172.2.66  raeburn  8747: # -------------------------------- Deversion and split uri into path an filename
                   8748: 
1.1133    foxr     8749: #
1.1172.2.66  raeburn  8750: #   Removes the version from a URI and
1.1133    foxr     8751: #   splits it in to its filename and path to the filename.
                   8752: #   Seems like File::Basename could have done this more clearly.
                   8753: #   Parameters:
                   8754: #      $uri   - input URI
                   8755: #   Returns:
                   8756: #     Two element list consisting of 
                   8757: #     $pathname  - the URI up to and excluding the trailing /
                   8758: #     $filename  - The part of the URI following the last /
                   8759: #  NOTE:
                   8760: #    Another realization of this is simply:
                   8761: #    use File::Basename;
                   8762: #    ...
                   8763: #    $uri = shift;
                   8764: #    $filename = basename($uri);
                   8765: #    $path     = dirname($uri);
                   8766: #    return ($filename, $path);
                   8767: #
                   8768: #     The implementation below is probably faster however.
                   8769: #
1.710     albertel 8770: sub split_uri_for_cond {
                   8771:     my $uri=&deversion(&declutter(shift));
                   8772:     my @uriparts=split(/\//,$uri);
                   8773:     my $filename=pop(@uriparts);
                   8774:     my $pathname=join('/',@uriparts);
                   8775:     return ($pathname,$filename);
                   8776: }
1.232     www      8777: # --------------------------------------------------- Is a resource on the map?
                   8778: 
                   8779: sub is_on_map {
1.710     albertel 8780:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8781:     #Trying to find the conditional for the file
1.620     albertel 8782:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8783: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8784:     if ($match) {
1.289     bowersj2 8785: 	return (1,$1);
                   8786:     } else {
1.434     www      8787: 	return (0,0);
1.289     bowersj2 8788:     }
1.12      www      8789: }
                   8790: 
1.427     www      8791: # --------------------------------------------------------- Get symb from alias
                   8792: 
                   8793: sub get_symb_from_alias {
                   8794:     my $symb=shift;
                   8795:     my ($map,$resid,$url)=&decode_symb($symb);
                   8796: # Already is a symb
                   8797:     if ($url) { return $symb; }
                   8798: # Must be an alias
                   8799:     my $aliassymb='';
                   8800:     my %bighash;
1.620     albertel 8801:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8802:                             &GDBM_READER(),0640)) {
                   8803:         my $rid=$bighash{'mapalias_'.$symb};
                   8804: 	if ($rid) {
                   8805: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8806: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8807: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8808: 	}
                   8809:         untie %bighash;
                   8810:     }
                   8811:     return $aliassymb;
                   8812: }
                   8813: 
1.12      www      8814: # ----------------------------------------------------------------- Define Role
                   8815: 
                   8816: sub definerole {
                   8817:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8818:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8819:     foreach my $role (split(':',$sysrole)) {
                   8820: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8821:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8822:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8823: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8824:                return "refused:s:$crole&$cqual"; 
                   8825:             }
                   8826:         }
1.191     harris41 8827:     }
1.800     albertel 8828:     foreach my $role (split(':',$domrole)) {
                   8829: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8830:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8831:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8832: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8833:                return "refused:d:$crole&$cqual"; 
                   8834:             }
                   8835:         }
1.191     harris41 8836:     }
1.800     albertel 8837:     foreach my $role (split(':',$courole)) {
                   8838: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8839:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8840:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8841: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8842:                return "refused:c:$crole&$cqual"; 
                   8843:             }
                   8844:         }
1.191     harris41 8845:     }
1.1172.2.84  raeburn  8846:     my $uhome;
                   8847:     if (($uname ne '') && ($udom ne '')) {
                   8848:         $uhome = &homeserver($uname,$udom);
                   8849:         return $uhome if ($uhome eq 'no_host');
                   8850:     } else {
                   8851:         $uname = $env{'user.name'};
                   8852:         $udom = $env{'user.domain'};
                   8853:         $uhome = $env{'user.home'};
                   8854:     }
1.620     albertel 8855:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8856:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8857:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8858:     return reply($command,$uhome);
1.12      www      8859:   } else {
                   8860:     return 'refused';
                   8861:   }
1.105     harris41 8862: }
                   8863: 
                   8864: # ---------------- Make a metadata query against the network of library servers
                   8865: 
                   8866: sub metadata_query {
1.1172.2.33  raeburn  8867:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8868:     my %rhash;
1.845     albertel 8869:     my %libserv = &all_library();
1.244     matthew  8870:     my @server_list = (defined($server_array) ? @$server_array
                   8871:                                               : keys(%libserv) );
                   8872:     for my $server (@server_list) {
1.1172.2.33  raeburn  8873:         my $domains = '';
                   8874:         if (ref($domains_hash) eq 'HASH') {
                   8875:             $domains = $domains_hash->{$server};    
                   8876:         }
1.118     harris41 8877: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8878: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8879: 	    $rhash{$server}=$reply;
                   8880: 	}
                   8881: 	else {
                   8882: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8883: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8884: 			     $server);
                   8885: 	    $rhash{$server}=$reply;
                   8886: 	}
1.112     harris41 8887:     }
1.118     harris41 8888:     return \%rhash;
1.240     www      8889: }
                   8890: 
                   8891: # ----------------------------------------- Send log queries and wait for reply
                   8892: 
                   8893: sub log_query {
                   8894:     my ($uname,$udom,$query,%filters)=@_;
                   8895:     my $uhome=&homeserver($uname,$udom);
                   8896:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8897:     my $uhost=&hostname($uhome);
1.800     albertel 8898:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8899:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8900:                        $uhome);
1.479     albertel 8901:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8902:     return get_query_reply($queryid);
                   8903: }
                   8904: 
1.818     raeburn  8905: # -------------------------- Update MySQL table for portfolio file
                   8906: 
                   8907: sub update_portfolio_table {
1.821     raeburn  8908:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8909:     if ($group ne '') {
                   8910:         $file_name =~s /^\Q$group\E//;
                   8911:     }
1.818     raeburn  8912:     my $homeserver = &homeserver($uname,$udom);
                   8913:     my $queryid=
1.821     raeburn  8914:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8915:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8916:     my $reply = &get_query_reply($queryid);
                   8917:     return $reply;
                   8918: }
                   8919: 
1.899     raeburn  8920: # -------------------------- Update MySQL allusers table
                   8921: 
                   8922: sub update_allusers_table {
                   8923:     my ($uname,$udom,$names) = @_;
                   8924:     my $homeserver = &homeserver($uname,$udom);
                   8925:     my $queryid=
                   8926:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8927:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8928:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8929:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8930:                'generation='.&escape($names->{'generation'}).'%%'.
                   8931:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8932:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8933:     return;
1.899     raeburn  8934: }
                   8935: 
1.508     raeburn  8936: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8937: 
                   8938: sub fetch_enrollment_query {
1.511     raeburn  8939:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8940:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8941:     my $maxtries = 1;
1.508     raeburn  8942:     if ($context eq 'automated') {
                   8943:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8944:         $sleep = 2;
                   8945:         $loopmax = 100;
1.547     raeburn  8946:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8947:     } else {
                   8948:         $homeserver = &homeserver($cnum,$dom);
                   8949:     }
1.838     albertel 8950:     my $host=&hostname($homeserver);
1.506     raeburn  8951:     my $cmd = '';
1.1000    raeburn  8952:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8953:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8954:     }
                   8955:     $cmd =~ s/%%$//;
                   8956:     $cmd = &escape($cmd);
                   8957:     my $query = 'fetchenrollment';
1.620     albertel 8958:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8959:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8960:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8961:         return 'error: '.$queryid;
                   8962:     }
1.1172.2.93  raeburn  8963:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8964:     my $tries = 1;
                   8965:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8966:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8967:         $tries ++;
                   8968:     }
1.526     raeburn  8969:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8970:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8971:     } else {
1.901     albertel 8972:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8973:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8974:             foreach my $line (@responses) {
                   8975:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8976:                 $$replyref{$key} = $value;
                   8977:             }
                   8978:         } else {
1.1117    foxr     8979:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8980:             foreach my $line (@responses) {
                   8981:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8982:                 $$replyref{$key} = $value;
                   8983:                 if ($value > 0) {
1.800     albertel 8984:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8985:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8986:                         my $destname = $pathname.'/'.$filename;
                   8987:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8988:                         if ($xml_classlist =~ /^error/) {
                   8989:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8990:                         } else {
1.1172.2.96  raeburn  8991:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8992:                                 print FILE &unescape($xml_classlist);
                   8993:                                 close(FILE);
1.526     raeburn  8994:                             } else {
                   8995:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8996:                             }
                   8997:                         }
                   8998:                     }
                   8999:                 }
                   9000:             }
                   9001:         }
                   9002:         return 'ok';
                   9003:     }
                   9004:     return 'error';
                   9005: }
                   9006: 
1.242     www      9007: sub get_query_reply {
1.1172.2.79  raeburn  9008:     my ($queryid,$sleep,$loopmax) = @_;
                   9009:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9010:         $sleep = 0.2;
                   9011:     }
                   9012:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9013:         $loopmax = 100;
                   9014:     }
1.1117    foxr     9015:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9016:     my $reply='';
1.1172.2.79  raeburn  9017:     for (1..$loopmax) {
                   9018: 	sleep($sleep);
1.240     www      9019:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9020: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9021: 		$reply = join('',<$fh>);
                   9022: 		close($fh);
1.240     www      9023: 	   } else { return 'error: reply_file_error'; }
1.242     www      9024:            return &unescape($reply);
                   9025: 	}
1.240     www      9026:     }
1.242     www      9027:     return 'timeout:'.$queryid;
1.240     www      9028: }
                   9029: 
                   9030: sub courselog_query {
1.241     www      9031: #
                   9032: # possible filters:
                   9033: # url: url or symb
                   9034: # username
                   9035: # domain
                   9036: # action: view, submit, grade
                   9037: # start: timestamp
                   9038: # end: timestamp
                   9039: #
1.240     www      9040:     my (%filters)=@_;
1.620     albertel 9041:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9042:     if ($filters{'url'}) {
                   9043: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9044:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9045:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9046:     }
1.620     albertel 9047:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9048:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9049:     return &log_query($cname,$cdom,'courselog',%filters);
                   9050: }
                   9051: 
                   9052: sub userlog_query {
1.858     raeburn  9053: #
                   9054: # possible filters:
                   9055: # action: log check role
                   9056: # start: timestamp
                   9057: # end: timestamp
                   9058: #
1.240     www      9059:     my ($uname,$udom,%filters)=@_;
                   9060:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9061: }
                   9062: 
1.506     raeburn  9063: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9064: 
                   9065: sub auto_run {
1.508     raeburn  9066:     my ($cnum,$cdom) = @_;
1.876     raeburn  9067:     my $response = 0;
                   9068:     my $settings;
                   9069:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9070:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9071:         $settings = $domconfig{'autoenroll'};
                   9072:         if ($settings->{'run'} eq '1') {
                   9073:             $response = 1;
                   9074:         }
                   9075:     } else {
1.934     raeburn  9076:         my $homeserver;
                   9077:         if (&is_course($cdom,$cnum)) {
                   9078:             $homeserver = &homeserver($cnum,$cdom);
                   9079:         } else {
                   9080:             $homeserver = &domain($cdom,'primary');
                   9081:         }
                   9082:         if ($homeserver ne 'no_host') {
                   9083:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9084:         }
1.876     raeburn  9085:     }
1.506     raeburn  9086:     return $response;
                   9087: }
1.776     albertel 9088: 
1.506     raeburn  9089: sub auto_get_sections {
1.508     raeburn  9090:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9091:     my $homeserver;
                   9092:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9093:         $homeserver = &homeserver($cnum,$cdom);
                   9094:     }
                   9095:     if (!defined($homeserver)) { 
                   9096:         if ($cdom =~ /^$match_domain$/) {
                   9097:             $homeserver = &domain($cdom,'primary');
                   9098:         }
                   9099:     }
                   9100:     my @secs;
                   9101:     if (defined($homeserver)) {
                   9102:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9103:         unless ($response eq 'refused') {
                   9104:             @secs = split(/:/,$response);
                   9105:         }
1.506     raeburn  9106:     }
                   9107:     return @secs;
                   9108: }
1.776     albertel 9109: 
1.506     raeburn  9110: sub auto_new_course {
1.1099    raeburn  9111:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9112:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9113:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9114:     return $response;
                   9115: }
1.776     albertel 9116: 
1.506     raeburn  9117: sub auto_validate_courseID {
1.508     raeburn  9118:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9119:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9120:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9121:     return $response;
                   9122: }
1.776     albertel 9123: 
1.1007    raeburn  9124: sub auto_validate_instcode {
1.1020    raeburn  9125:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9126:     my ($homeserver,$response);
                   9127:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9128:         $homeserver = &homeserver($cnum,$cdom);
                   9129:     }
                   9130:     if (!defined($homeserver)) {
                   9131:         if ($cdom =~ /^$match_domain$/) {
                   9132:             $homeserver = &domain($cdom,'primary');
                   9133:         }
                   9134:     }
1.1065    raeburn  9135:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9136:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9137:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9138:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9139: }
                   9140: 
1.1172.2.118.  .20(raeb 9141:-21): sub auto_validate_inst_crosslist {
                   9142:-21):     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9143:-21):     my ($homeserver,$response);
                   9144:-21):     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9145:-21):         $homeserver = &homeserver($cnum,$cdom);
                   9146:-21):     }
                   9147:-21):     if (!defined($homeserver)) {
                   9148:-21):         if ($cdom =~ /^$match_domain$/) {
                   9149:-21):             $homeserver = &domain($cdom,'primary');
                   9150:-21):         }
                   9151:-21):     }
                   9152:-21):     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9153:-21):         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9154:-21):                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9155:-21):                          &escape($coowner),$homeserver);
                   9156:-21):     }
                   9157:-21):     return $response;
                   9158:-21): }
                   9159:-21): 
1.506     raeburn  9160: sub auto_create_password {
1.873     raeburn  9161:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9162:     my ($homeserver,$response);
1.506     raeburn  9163:     my $create_passwd = 0;
                   9164:     my $authchk = '';
1.873     raeburn  9165:     if ($udom =~ /^$match_domain$/) {
                   9166:         $homeserver = &domain($udom,'primary');
                   9167:     }
                   9168:     if ($homeserver eq '') {
                   9169:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9170:             $homeserver = &homeserver($cnum,$cdom);
                   9171:         }
                   9172:     }
                   9173:     if ($homeserver eq '') {
                   9174:         $authchk = 'nodomain';
1.506     raeburn  9175:     } else {
1.873     raeburn  9176:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9177:         if ($response eq 'refused') {
                   9178:             $authchk = 'refused';
                   9179:         } else {
1.901     albertel 9180:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9181:         }
1.506     raeburn  9182:     }
                   9183:     return ($authparam,$create_passwd,$authchk);
                   9184: }
                   9185: 
1.706     raeburn  9186: sub auto_photo_permission {
                   9187:     my ($cnum,$cdom,$students) = @_;
                   9188:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9189:     my ($outcome,$perm_reqd,$conditions) = 
                   9190: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9191:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9192: 	return (undef,undef);
                   9193:     }
1.706     raeburn  9194:     return ($outcome,$perm_reqd,$conditions);
                   9195: }
                   9196: 
                   9197: sub auto_checkphotos {
                   9198:     my ($uname,$udom,$pid) = @_;
                   9199:     my $homeserver = &homeserver($uname,$udom);
                   9200:     my ($result,$resulttype);
                   9201:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9202: 				   &escape($uname).':'.&escape($pid),
                   9203: 				   $homeserver));
1.709     albertel 9204:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9205: 	return (undef,undef);
                   9206:     }
1.706     raeburn  9207:     if ($outcome) {
                   9208:         ($result,$resulttype) = split(/:/,$outcome);
                   9209:     } 
                   9210:     return ($result,$resulttype);
                   9211: }
                   9212: 
                   9213: sub auto_photochoice {
                   9214:     my ($cnum,$cdom) = @_;
                   9215:     my $homeserver = &homeserver($cnum,$cdom);
                   9216:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9217: 						       &escape($cdom),
                   9218: 						       $homeserver)));
1.709     albertel 9219:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9220: 	return (undef,undef);
                   9221:     }
1.706     raeburn  9222:     return ($update,$comment);
                   9223: }
                   9224: 
                   9225: sub auto_photoupdate {
                   9226:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9227:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9228:     my $host=&hostname($homeserver);
1.706     raeburn  9229:     my $cmd = '';
                   9230:     my $maxtries = 1;
1.800     albertel 9231:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9232:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9233:     }
                   9234:     $cmd =~ s/%%$//;
                   9235:     $cmd = &escape($cmd);
                   9236:     my $query = 'institutionalphotos';
                   9237:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9238:     unless ($queryid=~/^\Q$host\E\_/) {
                   9239:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9240:         return 'error: '.$queryid;
                   9241:     }
                   9242:     my $reply = &get_query_reply($queryid);
                   9243:     my $tries = 1;
                   9244:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9245:         $reply = &get_query_reply($queryid);
                   9246:         $tries ++;
                   9247:     }
                   9248:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9249:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9250:     } else {
                   9251:         my @responses = split(/:/,$reply);
                   9252:         my $outcome = shift(@responses); 
                   9253:         foreach my $item (@responses) {
                   9254:             my ($key,$value) = split(/=/,$item);
                   9255:             $$photo{$key} = $value;
                   9256:         }
                   9257:         return $outcome;
                   9258:     }
                   9259:     return 'error';
                   9260: }
                   9261: 
1.521     raeburn  9262: sub auto_instcode_format {
1.793     albertel 9263:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9264: 	$cat_order) = @_;
1.521     raeburn  9265:     my $courses = '';
1.772     raeburn  9266:     my @homeservers;
1.521     raeburn  9267:     if ($caller eq 'global') {
1.841     albertel 9268: 	my %servers = &get_servers($codedom,'library');
                   9269: 	foreach my $tryserver (keys(%servers)) {
                   9270: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9271: 		push(@homeservers,$tryserver);
                   9272: 	    }
1.584     raeburn  9273:         }
1.1022    raeburn  9274:     } elsif ($caller eq 'requests') {
                   9275:         if ($codedom =~ /^$match_domain$/) {
                   9276:             my $chome = &domain($codedom,'primary');
                   9277:             unless ($chome eq 'no_host') {
                   9278:                 push(@homeservers,$chome);
                   9279:             }
                   9280:         }
1.521     raeburn  9281:     } else {
1.772     raeburn  9282:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9283:     }
1.793     albertel 9284:     foreach my $code (keys(%{$instcodes})) {
                   9285:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9286:     }
                   9287:     chop($courses);
1.772     raeburn  9288:     my $ok_response = 0;
                   9289:     my $response;
                   9290:     while (@homeservers > 0 && $ok_response == 0) {
                   9291:         my $server = shift(@homeservers); 
                   9292:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9293:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9294:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9295: 		split(/:/,$response);
1.772     raeburn  9296:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9297:             push(@{$codetitles},&str2array($codetitles_str));
                   9298:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9299:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9300:             $ok_response = 1;
                   9301:         }
                   9302:     }
                   9303:     if ($ok_response) {
1.521     raeburn  9304:         return 'ok';
1.772     raeburn  9305:     } else {
                   9306:         return $response;
1.521     raeburn  9307:     }
                   9308: }
                   9309: 
1.792     raeburn  9310: sub auto_instcode_defaults {
                   9311:     my ($domain,$returnhash,$code_order) = @_;
                   9312:     my @homeservers;
1.841     albertel 9313: 
                   9314:     my %servers = &get_servers($domain,'library');
                   9315:     foreach my $tryserver (keys(%servers)) {
                   9316: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9317: 	    push(@homeservers,$tryserver);
                   9318: 	}
1.792     raeburn  9319:     }
1.841     albertel 9320: 
1.792     raeburn  9321:     my $response;
1.841     albertel 9322:     foreach my $server (@homeservers) {
1.792     raeburn  9323:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9324:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9325: 	
                   9326: 	foreach my $pair (split(/\&/,$response)) {
                   9327: 	    my ($name,$value)=split(/\=/,$pair);
                   9328: 	    if ($name eq 'code_order') {
                   9329: 		@{$code_order} = split(/\&/,&unescape($value));
                   9330: 	    } else {
                   9331: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9332: 	    }
                   9333: 	}
                   9334: 	return 'ok';
1.792     raeburn  9335:     }
1.841     albertel 9336: 
                   9337:     return $response;
1.1003    raeburn  9338: }
                   9339: 
                   9340: sub auto_possible_instcodes {
1.1007    raeburn  9341:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9342:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9343:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9344:         return;
                   9345:     }
1.1003    raeburn  9346:     my (@homeservers,$uhome);
                   9347:     if (defined(&domain($domain,'primary'))) {
                   9348:         $uhome=&domain($domain,'primary');
                   9349:         push(@homeservers,&domain($domain,'primary'));
                   9350:     } else {
                   9351:         my %servers = &get_servers($domain,'library');
                   9352:         foreach my $tryserver (keys(%servers)) {
                   9353:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9354:                 push(@homeservers,$tryserver);
                   9355:             }
                   9356:         }
                   9357:     }
                   9358:     my $response;
                   9359:     foreach my $server (@homeservers) {
                   9360:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9361:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9362:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9363:             split(':',$response);
                   9364:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9365:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9366:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9367:             my ($name,$value)=split('=',$item);
                   9368:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9369:         }
                   9370:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9371:             my ($name,$value)=split('=',$item);
                   9372:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9373:         }
                   9374:         return 'ok';
                   9375:     }
                   9376:     return $response;
                   9377: }
1.792     raeburn  9378: 
1.1010    raeburn  9379: sub auto_courserequest_checks {
                   9380:     my ($dom) = @_;
1.1020    raeburn  9381:     my ($homeserver,%validations);
                   9382:     if ($dom =~ /^$match_domain$/) {
                   9383:         $homeserver = &domain($dom,'primary');
                   9384:     }
                   9385:     unless ($homeserver eq 'no_host') {
                   9386:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9387:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9388:             my @items = split(/&/,$response);
                   9389:             foreach my $item (@items) {
                   9390:                 my ($key,$value) = split('=',$item);
                   9391:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9392:             }
                   9393:         }
                   9394:     }
1.1010    raeburn  9395:     return %validations; 
                   9396: }
                   9397: 
1.1020    raeburn  9398: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9399:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9400:     my ($homeserver,$response);
                   9401:     if ($dom =~ /^$match_domain$/) {
                   9402:         $homeserver = &domain($dom,'primary');
                   9403:     }
1.1172.2.43  raeburn  9404:     unless ($homeserver eq 'no_host') {
                   9405:         my $customdata;
                   9406:         if (ref($custominfo) eq 'HASH') {
                   9407:             $customdata = &freeze_escape($custominfo);
                   9408:         }
1.1020    raeburn  9409:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9410:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9411:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9412:                                     $customdata,$homeserver));
1.1020    raeburn  9413:     }
                   9414:     return $response;
                   9415: }
                   9416: 
1.777     albertel 9417: sub auto_validate_class_sec {
1.918     raeburn  9418:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9419:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9420:     my $ownerlist;
                   9421:     if (ref($owners) eq 'ARRAY') {
                   9422:         $ownerlist = join(',',@{$owners});
                   9423:     } else {
                   9424:         $ownerlist = $owners;
                   9425:     }
1.773     raeburn  9426:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9427:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9428:     return $response;
                   9429: }
                   9430: 
1.1172.2.118.  .20(raeb 9431:-21): sub auto_instsec_reformat {
                   9432:-21):     my ($cdom,$action,$instsecref) = @_;
                   9433:-21):     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9434:-21):     my @homeservers;
                   9435:-21):     if (defined(&domain($cdom,'primary'))) {
                   9436:-21):         push(@homeservers,&domain($cdom,'primary'));
                   9437:-21):     } else {
                   9438:-21):         my %servers = &get_servers($cdom,'library');
                   9439:-21):         foreach my $tryserver (keys(%servers)) {
                   9440:-21):             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9441:-21):                 push(@homeservers,$tryserver);
                   9442:-21):             }
                   9443:-21):         }
                   9444:-21):     }
                   9445:-21):     my $response;
                   9446:-21):     my %reformatted = %{$instsecref};
                   9447:-21):     foreach my $server (@homeservers) {
                   9448:-21):         if (ref($instsecref) eq 'HASH') {
                   9449:-21):             my $info = &freeze_escape($instsecref);
                   9450:-21):             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9451:-21):                                 $action.':'.$info,$server);
                   9452:-21):             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9453:-21):             my @items = split(/&/,$response);
                   9454:-21):             foreach my $item (@items) {
                   9455:-21):                 my ($key,$value) = split(/=/,$item);
                   9456:-21):                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9457:-21):             }
                   9458:-21):         }
                   9459:-21):     }
                   9460:-21):     return %reformatted;
                   9461:-21): }
                   9462:-21): 
1.1172.2.94  raeburn  9463: sub auto_validate_instclasses {
                   9464:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9465:     my ($homeserver,%validations);
                   9466:     $homeserver = &homeserver($cnum,$cdom);
                   9467:     unless ($homeserver eq 'no_host') {
                   9468:         my $ownerlist;
                   9469:         if (ref($owners) eq 'ARRAY') {
                   9470:             $ownerlist = join(',',@{$owners});
                   9471:         } else {
                   9472:             $ownerlist = $owners;
                   9473:         }
                   9474:         if (ref($classesref) eq 'HASH') {
                   9475:             my $classes = &freeze_escape($classesref);
                   9476:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9477:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9478:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9479:                 my @items = split(/&/,$response);
                   9480:                 foreach my $item (@items) {
                   9481:                     my ($key,$value) = split('=',$item);
                   9482:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9483:                 }
                   9484:             }
                   9485:         }
                   9486:     }
                   9487:     return %validations;
                   9488: }
                   9489: 
1.1172.2.38  raeburn  9490: sub auto_crsreq_update {
                   9491:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9492:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9493:     my ($homeserver,%crsreqresponse);
                   9494:     if ($cdom =~ /^$match_domain$/) {
                   9495:         $homeserver = &domain($cdom,'primary');
                   9496:     }
                   9497:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9498:         my $info;
                   9499:         if (ref($inbound) eq 'HASH') {
                   9500:             $info = &freeze_escape($inbound);
                   9501:         }
                   9502:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9503:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9504:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9505:                             &escape($title).':'.&escape($code).':'.
                   9506:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9507:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9508:             my @items = split(/&/,$response);
                   9509:             foreach my $item (@items) {
                   9510:                 my ($key,$value) = split('=',$item);
                   9511:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9512:             }
                   9513:         }
                   9514:     }
                   9515:     return \%crsreqresponse;
                   9516: }
                   9517: 
1.1172.2.78  raeburn  9518: sub auto_export_grades {
                   9519:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9520:     my ($homeserver,%exportresponse);
                   9521:     if ($cdom =~ /^$match_domain$/) {
                   9522:         $homeserver = &domain($cdom,'primary');
                   9523:     }
                   9524:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9525:         my $info;
                   9526:         if (ref($inforef) eq 'HASH') {
                   9527:             $info = &freeze_escape($inforef);
                   9528:         }
                   9529:         if (ref($gradesref) eq 'HASH') {
                   9530:             my $grades = &freeze_escape($gradesref);
                   9531:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9532:                                 $info.':'.$grades,$homeserver);
                   9533:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9534:                 my @items = split(/&/,$response);
                   9535:                 foreach my $item (@items) {
                   9536:                     my ($key,$value) = split('=',$item);
                   9537:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9538:                 }
                   9539:             }
                   9540:         }
                   9541:     }
                   9542:     return \%exportresponse;
                   9543: }
                   9544: 
1.1172.2.68  raeburn  9545: sub check_instcode_cloning {
                   9546:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9547:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9548:         return;
                   9549:     }
                   9550:     my $canclone;
                   9551:     if (@{$code_order} > 0) {
                   9552:         my $instcoderegexp ='^';
                   9553:         my @clonecodes = split(/\&/,$cloner);
                   9554:         foreach my $item (@{$code_order}) {
                   9555:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9556:                 foreach my $pair (@clonecodes) {
                   9557:                     my ($key,$val) = split(/\=/,$pair,2);
                   9558:                     $val = &unescape($val);
                   9559:                     if ($key eq $item) {
                   9560:                         $instcoderegexp .= '('.$val.')';
                   9561:                         last;
                   9562:                     }
                   9563:                 }
                   9564:             } else {
                   9565:                 $instcoderegexp .= $codedefaults->{$item};
                   9566:             }
                   9567:         }
                   9568:         $instcoderegexp .= '$';
                   9569:         my (@from,@to);
                   9570:         eval {
                   9571:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9572:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9573:         };
                   9574:         if ((@from > 0) && (@to > 0)) {
                   9575:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9576:             if (!@diffs) {
                   9577:                 $canclone = 1;
                   9578:             }
                   9579:         }
                   9580:     }
                   9581:     return $canclone;
                   9582: }
                   9583: 
                   9584: sub default_instcode_cloning {
                   9585:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9586:     my (%codedefaults,@code_order,$canclone);
                   9587:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9588:         %codedefaults = %{$codedefaultsref};
                   9589:         @code_order = @{$codeorderref};
                   9590:     } elsif ($clonedom) {
                   9591:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9592:     }
                   9593:     if (($domdefclone) && (@code_order)) {
                   9594:         my @clonecodes = split(/\+/,$domdefclone);
                   9595:         my $instcoderegexp ='^';
                   9596:         foreach my $item (@code_order) {
                   9597:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9598:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9599:             } else {
                   9600:                 $instcoderegexp .= $codedefaults{$item};
                   9601:             }
                   9602:         }
                   9603:         $instcoderegexp .= '$';
                   9604:         my (@from,@to);
                   9605:         eval {
                   9606:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9607:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9608:         };
                   9609:         if ((@from > 0) && (@to > 0)) {
                   9610:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9611:             if (!@diffs) {
                   9612:                 $canclone = 1;
                   9613:             }
                   9614:         }
                   9615:     }
                   9616:     return $canclone;
                   9617: }
                   9618: 
1.679     raeburn  9619: # ------------------------------------------------------- Course Group routines
                   9620: 
                   9621: sub get_coursegroups {
1.809     raeburn  9622:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9623:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9624: }
                   9625: 
1.679     raeburn  9626: sub modify_coursegroup {
                   9627:     my ($cdom,$cnum,$groupsettings) = @_;
                   9628:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9629: }
                   9630: 
1.809     raeburn  9631: sub toggle_coursegroup_status {
                   9632:     my ($cdom,$cnum,$group,$action) = @_;
                   9633:     my ($from_namespace,$to_namespace);
                   9634:     if ($action eq 'delete') {
                   9635:         $from_namespace = 'coursegroups';
                   9636:         $to_namespace = 'deleted_groups';
                   9637:     } else {
                   9638:         $from_namespace = 'deleted_groups';
                   9639:         $to_namespace = 'coursegroups';
                   9640:     }
                   9641:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9642:     if (my $tmp = &error(%curr_group)) {
                   9643:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9644:         return ('read error',$tmp);
                   9645:     } else {
                   9646:         my %savedsettings = %curr_group; 
1.809     raeburn  9647:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9648:         my $deloutcome;
                   9649:         if ($result eq 'ok') {
1.809     raeburn  9650:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9651:         } else {
                   9652:             return ('write error',$result);
                   9653:         }
                   9654:         if ($deloutcome eq 'ok') {
                   9655:             return 'ok';
                   9656:         } else {
                   9657:             return ('delete error',$deloutcome);
                   9658:         }
                   9659:     }
                   9660: }
                   9661: 
1.679     raeburn  9662: sub modify_group_roles {
1.957     raeburn  9663:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9664:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9665:     my $role = 'gr/'.&escape($userprivs);
                   9666:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9667:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9668:     if ($result eq 'ok') {
                   9669:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9670:     }
1.679     raeburn  9671:     return $result;
                   9672: }
                   9673: 
                   9674: sub modify_coursegroup_membership {
                   9675:     my ($cdom,$cnum,$membership) = @_;
                   9676:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9677:     return $result;
                   9678: }
                   9679: 
1.682     raeburn  9680: sub get_active_groups {
                   9681:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9682:     my $now = time;
                   9683:     my %groups = ();
                   9684:     foreach my $key (keys(%env)) {
1.811     albertel 9685:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9686:             my ($start,$end) = split(/\./,$env{$key});
                   9687:             if (($end!=0) && ($end<$now)) { next; }
                   9688:             if (($start!=0) && ($start>$now)) { next; }
                   9689:             if ($1 eq $cdom && $2 eq $cnum) {
                   9690:                 $groups{$3} = $env{$key} ;
                   9691:             }
                   9692:         }
                   9693:     }
                   9694:     return %groups;
                   9695: }
                   9696: 
1.683     raeburn  9697: sub get_group_membership {
                   9698:     my ($cdom,$cnum,$group) = @_;
                   9699:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9700: }
                   9701: 
                   9702: sub get_users_groups {
                   9703:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9704:     my @usersgroups;
1.683     raeburn  9705:     my $cachetime=1800;
                   9706: 
                   9707:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9708:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9709:     if (defined($cached)) {
1.734     albertel 9710:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9711:     } else {  
                   9712:         $grouplist = '';
1.816     raeburn  9713:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9714:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9715:         my $access_end = $env{'course.'.$courseid.
                   9716:                               '.default_enrollment_end_date'};
                   9717:         my $now = time;
                   9718:         foreach my $key (keys(%roleshash)) {
                   9719:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9720:                 my $group = $1;
                   9721:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9722:                     my $start = $2;
                   9723:                     my $end = $1;
                   9724:                     if ($start == -1) { next; } # deleted from group
                   9725:                     if (($start!=0) && ($start>$now)) { next; }
                   9726:                     if (($end!=0) && ($end<$now)) {
                   9727:                         if ($access_end && $access_end < $now) {
                   9728:                             if ($access_end - $end < 86400) {
                   9729:                                 push(@usersgroups,$group);
1.733     raeburn  9730:                             }
                   9731:                         }
1.817     raeburn  9732:                         next;
1.733     raeburn  9733:                     }
1.817     raeburn  9734:                     push(@usersgroups,$group);
1.683     raeburn  9735:                 }
                   9736:             }
                   9737:         }
1.817     raeburn  9738:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9739:         $grouplist = join(':',@usersgroups);
                   9740:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9741:     }
1.733     raeburn  9742:     return @usersgroups;
1.683     raeburn  9743: }
                   9744: 
                   9745: sub devalidate_getgroups_cache {
                   9746:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9747:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9748: 
1.683     raeburn  9749:     my $hashid="$udom:$uname:$courseid";
                   9750:     &devalidate_cache_new('getgroups',$hashid);
                   9751: }
                   9752: 
1.12      www      9753: # ------------------------------------------------------------------ Plain Text
                   9754: 
                   9755: sub plaintext {
1.988     raeburn  9756:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9757:     if ($short =~ m{^cr/}) {
1.758     albertel 9758: 	return (split('/',$short))[-1];
                   9759:     }
1.742     raeburn  9760:     if (!defined($cid)) {
                   9761:         $cid = $env{'request.course.id'};
                   9762:     }
                   9763:     my %rolenames = (
1.1008    raeburn  9764:                       Course    => 'std',
                   9765:                       Community => 'alt1',
1.742     raeburn  9766:                     );
1.1037    raeburn  9767:     if ($cid ne '') {
                   9768:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9769:             unless ($forcedefault) {
                   9770:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9771:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9772:                 return &Apache::lonlocal::mt($roletext);
                   9773:             }
                   9774:         }
                   9775:     }
                   9776:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9777:         (defined($rolenames{$type})) && 
                   9778:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9779:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9780:     } elsif ($cid ne '') {
                   9781:         my $crstype = $env{'course.'.$cid.'.type'};
                   9782:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9783:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9784:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9785:         }
1.742     raeburn  9786:     }
1.1037    raeburn  9787:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9788: }
                   9789: 
                   9790: # ----------------------------------------------------------------- Assign Role
                   9791: 
                   9792: sub assignrole {
1.957     raeburn  9793:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9794:         $context)=@_;
1.21      www      9795:     my $mrole;
                   9796:     if ($role =~ /^cr\//) {
1.393     www      9797:         my $cwosec=$url;
1.811     albertel 9798:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9799: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9800:            my $refused = 1;
                   9801:            if ($context eq 'requestcourses') {
                   9802:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9803:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9804:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9805:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9806:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9807:                            if ($crsenv{'internal.courseowner'} eq
                   9808:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9809:                                $refused = '';
                   9810:                            }
                   9811:                        }
                   9812:                    }
                   9813:                }
                   9814:            }
                   9815:            if ($refused) {
                   9816:                &logthis('Refused custom assignrole: '.
                   9817:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9818:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9819:                return 'refused';
                   9820:            }
1.104     www      9821:         }
1.21      www      9822:         $mrole='cr';
1.678     raeburn  9823:     } elsif ($role =~ /^gr\//) {
                   9824:         my $cwogrp=$url;
1.811     albertel 9825:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9826:         unless (&allowed('mdg',$cwogrp)) {
                   9827:             &logthis('Refused group assignrole: '.
                   9828:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9829:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9830:             return 'refused';
                   9831:         }
                   9832:         $mrole='gr';
1.21      www      9833:     } else {
1.82      www      9834:         my $cwosec=$url;
1.811     albertel 9835:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9836:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9837:             my $refused;
                   9838:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9839:                 if (!(&allowed('c'.$role,$url))) {
                   9840:                     $refused = 1;
                   9841:                 }
                   9842:             } else {
                   9843:                 $refused = 1;
                   9844:             }
1.947     raeburn  9845:             if ($refused) {
1.1045    raeburn  9846:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9847:                 if (!$selfenroll && $context eq 'course') {
                   9848:                     my %crsenv;
                   9849:                     if ($role eq 'cc' || $role eq 'co') {
                   9850:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9851:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9852:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9853:                                 if ($crsenv{'internal.courseowner'} eq 
                   9854:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9855:                                     $refused = '';
                   9856:                                 }
                   9857:                             }
                   9858:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9859:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9860:                                 if ($crsenv{'internal.courseowner'} eq 
                   9861:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9862:                                     $refused = '';
                   9863:                                 }
                   9864:                             }
                   9865:                         }
                   9866:                     }
                   9867:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9868:                     $refused = '';
1.1017    raeburn  9869:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9870:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9871:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9872:                         my $wrongcc;
                   9873:                         if ($cnum =~ /^$match_community$/) {
                   9874:                             $wrongcc = 1 if ($role eq 'cc');
                   9875:                         } else {
                   9876:                             $wrongcc = 1 if ($role eq 'co');
                   9877:                         }
                   9878:                         unless ($wrongcc) {
                   9879:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9880:                             if ($crsenv{'internal.courseowner'} eq 
                   9881:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9882:                                 $refused = '';
                   9883:                             }
1.1017    raeburn  9884:                         }
                   9885:                     }
1.1172.2.9  raeburn  9886:                 } elsif ($context eq 'requestauthor') {
                   9887:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9888:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9889:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9890:                             $refused = '';
                   9891:                         } else {
                   9892:                             my %domdefaults = &get_domain_defaults($udom);
                   9893:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9894:                                 my $checkbystatus;
                   9895:                                 if ($env{'user.adv'}) {
                   9896:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9897:                                     if ($disposition eq 'automatic') {
                   9898:                                         $refused = '';
                   9899:                                     } elsif ($disposition eq '') {
                   9900:                                         $checkbystatus = 1;
                   9901:                                     }
                   9902:                                 } else {
                   9903:                                     $checkbystatus = 1;
                   9904:                                 }
                   9905:                                 if ($checkbystatus) {
                   9906:                                     if ($env{'environment.inststatus'}) {
                   9907:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9908:                                         foreach my $type (@inststatuses) {
                   9909:                                             if (($type ne '') &&
                   9910:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9911:                                                 $refused = '';
                   9912:                                             }
                   9913:                                         }
                   9914:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9915:                                         $refused = '';
                   9916:                                     }
                   9917:                                 }
                   9918:                             }
                   9919:                         }
                   9920:                     }
1.1017    raeburn  9921:                 }
                   9922:                 if ($refused) {
1.947     raeburn  9923:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9924:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9925: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9926:                     return 'refused';
                   9927:                 }
1.932     raeburn  9928:             }
1.1131    raeburn  9929:         } elsif ($role eq 'au') {
                   9930:             if ($url ne '/'.$udom.'/') {
                   9931:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9932:                          ' to assign author role for '.$uname.':'.$udom.
                   9933:                          ' in domain: '.$url.' refused (wrong domain).');
                   9934:                 return 'refused';
                   9935:             }
1.104     www      9936:         }
1.21      www      9937:         $mrole=$role;
                   9938:     }
1.620     albertel 9939:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9940:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9941:     if ($end) { $command.='_'.$end; }
1.21      www      9942:     if ($start) {
                   9943: 	if ($end) { 
1.81      www      9944:            $command.='_'.$start; 
1.21      www      9945:         } else {
1.81      www      9946:            $command.='_0_'.$start;
1.21      www      9947:         }
                   9948:     }
1.739     raeburn  9949:     my $origstart = $start;
                   9950:     my $origend = $end;
1.957     raeburn  9951:     my $delflag;
1.357     www      9952: # actually delete
                   9953:     if ($deleteflag) {
1.373     www      9954: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9955: # modify command to delete the role
1.620     albertel 9956:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9957:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9958: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9959: # set start and finish to negative values for userrolelog
                   9960:            $start=-1;
                   9961:            $end=-1;
1.957     raeburn  9962:            $delflag = 1;
1.357     www      9963:         }
                   9964:     }
                   9965: # send command
1.349     www      9966:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9967: # log new user role if status is ok
1.349     www      9968:     if ($answer eq 'ok') {
1.663     raeburn  9969: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9970:         if (($role eq 'cc') || ($role eq 'in') ||
                   9971:             ($role eq 'ep') || ($role eq 'ad') ||
                   9972:             ($role eq 'ta') || ($role eq 'st') ||
                   9973:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9974:             ($role eq 'co')) {
1.1172.2.13  raeburn  9975: # for course roles, perform group memberships changes triggered by role change.
                   9976:             unless ($role =~ /^gr/) {
                   9977:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9978:                                                  $origstart,$selfenroll,$context);
                   9979:             }
1.1172.2.9  raeburn  9980:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9981:                            $selfenroll,$context);
                   9982:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9983:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9984:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9985:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9986:                            $context);
                   9987:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9988:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9989:                              $context);
                   9990:         }
1.1053    raeburn  9991:         if ($role eq 'cc') {
                   9992:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9993:         }
1.349     www      9994:     }
                   9995:     return $answer;
1.169     harris41 9996: }
                   9997: 
1.1053    raeburn  9998: sub autoupdate_coowners {
                   9999:     my ($url,$end,$start,$uname,$udom) = @_;
                   10000:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10001:     if (($cdom ne '') && ($cnum ne '')) {
                   10002:         my $now = time;
                   10003:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10004:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10005:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10006:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.118.  .20(raeb 10007:-21):             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10008:             if ($instcode ne '') {
1.1056    raeburn  10009:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10010:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10011:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10012:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.118.  .20(raeb 10013:-21):                         unless ($result eq 'valid') {
                   10014:-21):                             if ($xlists ne '') {
                   10015:-21):                                 foreach my $xlist (split(',',$xlists)) {
                   10016:-21):                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10017:-21):                                     $result =
                   10018:-21):                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10019:-21):                                                                       $inst_crosslist,$uname.':'.$udom);
                   10020:-21):                                     last if ($result eq 'valid');
                   10021:-21):                                 }
                   10022:-21):                             }
                   10023:-21):                         }
1.1056    raeburn  10024:                         if ($result eq 'valid') {
                   10025:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10026:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10027:                                     push(@newcoowners,$coowner);
                   10028:                                 }
                   10029:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10030:                                     push(@newcoowners,$uname.':'.$udom);
                   10031:                                 }
                   10032:                                 @newcoowners = sort(@newcoowners);
                   10033:                             } else {
                   10034:                                 push(@newcoowners,$uname.':'.$udom);
                   10035:                             }
1.1172.2.118.  .20(raeb 10036:-21):                         } elsif ($coursehash{'internal.co-owners'}) {
                   10037:-21):                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10038:-21):                                 unless ($coowner eq $uname.':'.$udom) {
                   10039:-21):                                     push(@newcoowners,$coowner);
1.1053    raeburn  10040:                                 }
                   10041:                             }
1.1172.2.118.  .20(raeb 10042:-21):                             unless (@newcoowners > 0) {
                   10043:-21):                                 $delcoowners = 1;
                   10044:-21):                                 $coowners = '';
                   10045:-21):                             }
1.1053    raeburn  10046:                         }
                   10047:                         if (@newcoowners || $delcoowners) {
                   10048:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10049:                                             $delcoowners,@newcoowners);
                   10050:                         }
                   10051:                     }
                   10052:                 }
                   10053:             }
                   10054:         }
                   10055:     }
                   10056: }
                   10057: 
                   10058: sub store_coowners {
                   10059:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10060:     my $cid = $cdom.'_'.$cnum;
                   10061:     my ($coowners,$delresult,$putresult);
                   10062:     if (@newcoowners) {
                   10063:         $coowners = join(',',@newcoowners);
                   10064:         my %coownershash = (
                   10065:                             'internal.co-owners' => $coowners,
                   10066:                            );
                   10067:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10068:         if ($putresult eq 'ok') {
                   10069:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10070:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10071:             }
                   10072:         }
                   10073:     }
                   10074:     if ($delcoowners) {
                   10075:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10076:         if ($delresult eq 'ok') {
                   10077:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10078:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10079:             }
                   10080:         }
                   10081:     }
                   10082:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10083:         my %crsinfo =
                   10084:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10085:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10086:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10087:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10088:         }
                   10089:     }
                   10090: }
                   10091: 
1.169     harris41 10092: # -------------------------------------------------- Modify user authentication
1.197     www      10093: # Overrides without validation
                   10094: 
1.169     harris41 10095: sub modifyuserauth {
                   10096:     my ($udom,$uname,$umode,$upass)=@_;
                   10097:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10098:     my $allowed;
                   10099:     if (&allowed('mau',$udom)) {
                   10100:         $allowed = 1;
                   10101:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10102:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10103:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10104:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10105:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10106:         if (($cdom ne '') && ($cnum ne '')) {
                   10107:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10108:             if ($is_owner) {
                   10109:                 $allowed = 1;
                   10110:             }
                   10111:         }
                   10112:     }
                   10113:     unless ($allowed) { return 'refused'; }
1.197     www      10114:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10115:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10116:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10117:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10118: 		     &escape($upass),$uhome);
1.1172.2.118.  .14(raeb 10119:-21):     my $ip = &get_requestor_ip();
1.620     albertel 10120:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10121:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.118.  .14(raeb 10122:-21):          '(Remote '.$ip.'): '.$reply);
1.197     www      10123:     &log($udom,,$uname,$uhome,
1.620     albertel 10124:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10125:                                      $env{'user.name'}.', '.$umode.
1.1172.2.118.  .14(raeb 10126:-21):          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10127:     unless ($reply eq 'ok') {
1.197     www      10128:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10129: 	return 'error: '.$reply;
                   10130:     }   
1.170     harris41 10131:     return 'ok';
1.80      www      10132: }
                   10133: 
1.81      www      10134: # --------------------------------------------------------------- Modify a user
1.80      www      10135: 
1.81      www      10136: sub modifyuser {
1.206     matthew  10137:     my ($udom,    $uname, $uid,
                   10138:         $umode,   $upass, $first,
                   10139:         $middle,  $last,  $gene,
1.1058    raeburn  10140:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10141:     $udom= &LONCAPA::clean_domain($udom);
                   10142:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10143:     my $showcandelete = 'none';
                   10144:     if (ref($candelete) eq 'ARRAY') {
                   10145:         if (@{$candelete} > 0) {
                   10146:             $showcandelete = join(', ',@{$candelete});
                   10147:         }
                   10148:     }
1.81      www      10149:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10150:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10151: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10152:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10153:                                      ' desiredhome not specified'). 
1.620     albertel 10154:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10155:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10156:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10157:     my $newuser;
                   10158:     if ($uhome eq 'no_host') {
                   10159:         $newuser = 1;
                   10160:     }
1.80      www      10161: # ----------------------------------------------------------------- Create User
1.406     albertel 10162:     if (($uhome eq 'no_host') && 
                   10163: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10164:         my $unhome='';
1.844     albertel 10165:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10166:             $unhome = $desiredhome;
1.620     albertel 10167: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10168: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10169:         } else { # load balancing routine for determining $unhome
1.81      www      10170:             my $loadm=10000000;
1.841     albertel 10171: 	    my %servers = &get_servers($udom,'library');
                   10172: 	    foreach my $tryserver (keys(%servers)) {
                   10173: 		my $answer=reply('load',$tryserver);
                   10174: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10175: 		    $loadm=$answer;
                   10176: 		    $unhome=$tryserver;
                   10177: 		}
1.80      www      10178: 	    }
                   10179:         }
                   10180:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10181: 	    return 'error: unable to find a home server for '.$uname.
                   10182:                    ' in domain '.$udom;
1.80      www      10183:         }
                   10184:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10185:                          &escape($upass),$unhome);
                   10186: 	unless ($reply eq 'ok') {
                   10187:             return 'error: '.$reply;
                   10188:         }   
1.230     stredwic 10189:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10190:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10191: 	    return 'error: unable verify users home machine.';
1.80      www      10192:         }
1.209     matthew  10193:     }   # End of creation of new user
1.80      www      10194: # ---------------------------------------------------------------------- Add ID
                   10195:     if ($uid) {
                   10196:        $uid=~tr/A-Z/a-z/;
                   10197:        my %uidhash=&idrget($udom,$uname);
1.196     www      10198:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10199:          && (!$forceid)) {
1.80      www      10200: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10201: 	      return 'error: user id "'.$uid.'" does not match '.
                   10202:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10203:           }
                   10204:        } else {
                   10205: 	  &idput($udom,($uname => $uid));
                   10206:        }
                   10207:     }
                   10208: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10209:     my @tmp=&get('environment',
1.899     raeburn  10210: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10211:                     'permanentemail','inststatus'],
1.134     albertel 10212: 		   $udom,$uname);
1.1075    raeburn  10213:     my (%names,%oldnames);
1.313     matthew  10214:     if ($tmp[0] =~ m/^error:.*/) { 
                   10215:         %names=(); 
                   10216:     } else {
                   10217:         %names = @tmp;
1.1075    raeburn  10218:         %oldnames = %names;
1.313     matthew  10219:     }
1.388     www      10220: #
1.1058    raeburn  10221: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10222: # of users did not contain them), do not overwrite existing values
                   10223: # unless field is in $candelete array ref.  
                   10224: #
                   10225: 
                   10226:     my @fields = ('firstname','middlename','lastname','generation',
                   10227:                   'permanentemail','id');
                   10228:     my %newvalues;
                   10229:     if (ref($candelete) eq 'ARRAY') {
                   10230:         foreach my $field (@fields) {
                   10231:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10232:                 if ($field eq 'firstname') {
                   10233:                     $names{$field} = $first;
                   10234:                 } elsif ($field eq 'middlename') {
                   10235:                     $names{$field} = $middle;
                   10236:                 } elsif ($field eq 'lastname') {
                   10237:                     $names{$field} = $last;
                   10238:                 } elsif ($field eq 'generation') { 
                   10239:                     $names{$field} = $gene;
                   10240:                 } elsif ($field eq 'permanentemail') {
                   10241:                     $names{$field} = $email;
                   10242:                 } elsif ($field eq 'id') {
                   10243:                     $names{$field}  = $uid;
                   10244:                 }
                   10245:             }
                   10246:         }
                   10247:     }
1.388     www      10248:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10249:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10250:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10251:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10252:     if ($email) {
                   10253:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10254:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10255:     }
1.899     raeburn  10256:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10257:     if (defined($inststatus)) {
                   10258:         $names{'inststatus'} = '';
                   10259:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10260:         if (ref($usertypes) eq 'HASH') {
                   10261:             my @okstatuses; 
                   10262:             foreach my $item (split(/:/,$inststatus)) {
                   10263:                 if (defined($usertypes->{$item})) {
                   10264:                     push(@okstatuses,$item);  
                   10265:                 }
                   10266:             }
                   10267:             if (@okstatuses) {
                   10268:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10269:             }
                   10270:         }
                   10271:     }
1.1075    raeburn  10272:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10273:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10274:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10275:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10276:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10277:     } else {
                   10278:         $logmsg .= ' during self creation';
                   10279:     }
1.1075    raeburn  10280:     my $changed;
                   10281:     if ($newuser) {
                   10282:         $changed = 1;
                   10283:     } else {
                   10284:         foreach my $field (@fields) {
                   10285:             if ($names{$field} ne $oldnames{$field}) {
                   10286:                 $changed = 1;
                   10287:                 last;
                   10288:             }
                   10289:         }
                   10290:     }
                   10291:     unless ($changed) {
                   10292:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10293:         &logthis($logmsg);
                   10294:         return 'ok';
                   10295:     }
                   10296:     my $reply = &put('environment', \%names, $udom,$uname);
                   10297:     if ($reply ne 'ok') { 
                   10298:         return 'error: '.$reply;
                   10299:     }
1.1087    raeburn  10300:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10301:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10302:     }
1.1075    raeburn  10303:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10304:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10305:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10306:     &logthis($logmsg);
1.134     albertel 10307:     return 'ok';
1.80      www      10308: }
                   10309: 
1.81      www      10310: # -------------------------------------------------------------- Modify student
1.80      www      10311: 
1.81      www      10312: sub modifystudent {
                   10313:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10314:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10315:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10316:     if (!$cid) {
1.620     albertel 10317: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10318: 	    return 'not_in_class';
                   10319: 	}
1.80      www      10320:     }
                   10321: # --------------------------------------------------------------- Make the user
1.81      www      10322:     my $reply=&modifyuser
1.209     matthew  10323: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10324:          $desiredhome,$email,$inststatus);
1.80      www      10325:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10326:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10327:     # student's environment
1.297     matthew  10328:     $uid = undef if (!$forceid);
1.455     albertel 10329:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10330: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10331:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10332:     return $reply;
                   10333: }
                   10334: 
                   10335: sub modify_student_enrollment {
1.1172.2.23  raeburn  10336:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10337:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10338:     my ($cdom,$cnum,$chome);
                   10339:     if (!$cid) {
1.620     albertel 10340: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10341: 	    return 'not_in_class';
                   10342: 	}
1.620     albertel 10343: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10344: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10345:     } else {
                   10346: 	($cdom,$cnum)=split(/_/,$cid);
                   10347:     }
1.620     albertel 10348:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10349:     if (!$chome) {
1.457     raeburn  10350: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10351:     }
1.455     albertel 10352:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10353:     # Make sure the user exists
1.81      www      10354:     my $uhome=&homeserver($uname,$udom);
                   10355:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10356: 	return 'error: no such user';
                   10357:     }
1.297     matthew  10358:     # Get student data if we were not given enough information
                   10359:     if (!defined($first)  || $first  eq '' || 
                   10360:         !defined($last)   || $last   eq '' || 
                   10361:         !defined($uid)    || $uid    eq '' || 
                   10362:         !defined($middle) || $middle eq '' || 
                   10363:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10364:         # They did not supply us with enough data to enroll the student, so
                   10365:         # we need to pick up more information.
1.297     matthew  10366:         my %tmp = &get('environment',
1.294     matthew  10367:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10368:                        ,$udom,$uname);
                   10369: 
1.800     albertel 10370:         #foreach my $key (keys(%tmp)) {
                   10371:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10372:         #}
1.294     matthew  10373:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10374:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10375:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10376:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10377:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10378:     }
1.556     albertel 10379:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10380:     my $user = "$uname:$udom";
                   10381:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10382:     my $reply=cput('classlist',
1.1148    raeburn  10383: 		   {$user => 
1.1172.2.76  raeburn  10384: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10385: 		   $cdom,$cnum);
1.1148    raeburn  10386:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10387:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10388:     } else { 
1.81      www      10389: 	return 'error: '.$reply;
                   10390:     }
1.297     matthew  10391:     # Add student role to user
1.83      www      10392:     my $uurl='/'.$cid;
1.81      www      10393:     $uurl=~s/\_/\//g;
                   10394:     if ($usec) {
                   10395: 	$uurl.='/'.$usec;
                   10396:     }
1.1148    raeburn  10397:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10398:                              $selfenroll,$context);
                   10399:     if ($result ne 'ok') {
                   10400:         if ($old_entry{$user} ne '') {
                   10401:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10402:         } else {
                   10403:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10404:         }
                   10405:     }
                   10406:     return $result; 
1.21      www      10407: }
                   10408: 
1.556     albertel 10409: sub format_name {
                   10410:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10411:     my $name;
                   10412:     if ($first ne 'lastname') {
                   10413: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10414:     } else {
                   10415: 	if ($lastname=~/\S/) {
                   10416: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10417: 	    $name=~s/\s+,/,/;
                   10418: 	} else {
                   10419: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10420: 	}
                   10421:     }
                   10422:     $name=~s/^\s+//;
                   10423:     $name=~s/\s+$//;
                   10424:     $name=~s/\s+/ /g;
                   10425:     return $name;
                   10426: }
                   10427: 
1.84      www      10428: # ------------------------------------------------- Write to course preferences
                   10429: 
                   10430: sub writecoursepref {
                   10431:     my ($courseid,%prefs)=@_;
                   10432:     $courseid=~s/^\///;
                   10433:     $courseid=~s/\_/\//g;
                   10434:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10435:     my $chome=homeserver($cnum,$cdomain);
                   10436:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10437: 	return 'error: no such course';
                   10438:     }
                   10439:     my $cstring='';
1.800     albertel 10440:     foreach my $pref (keys(%prefs)) {
                   10441: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10442:     }
1.84      www      10443:     $cstring=~s/\&$//;
                   10444:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10445: }
                   10446: 
                   10447: # ---------------------------------------------------------- Make/modify course
                   10448: 
                   10449: sub createcourse {
1.741     raeburn  10450:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10451:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10452:     $url=&declutter($url);
                   10453:     my $cid='';
1.1028    raeburn  10454:     if ($context eq 'requestcourses') {
                   10455:         my $can_create = 0;
                   10456:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10457:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10458:20):             my $reload;
                   10459:20):             if (($callercontext eq 'auto') &&
                   10460:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10461:20):                 $reload = 'reload';
                   10462:20):             }
                   10463:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10464:                                   $context)) {
                   10465:                 $can_create = 1;
                   10466:             }
                   10467:         } else {
                   10468:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10469:                                            $category);
                   10470:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10471:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10472:                 if (@curr > 0) {
                   10473:                     my @options = qw(approval validate autolimit);
                   10474:                     my $optregex = join('|',@options);
                   10475:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10476:                         $can_create = 1;
                   10477:                     }
                   10478:                 }
                   10479:             }
                   10480:         }
                   10481:         if ($can_create) {
                   10482:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10483:                 unless (&allowed('ccc',$udom)) {
                   10484:                     return 'refused'; 
                   10485:                 }
1.1017    raeburn  10486:             }
                   10487:         } else {
                   10488:             return 'refused';
                   10489:         }
1.1028    raeburn  10490:     } elsif (!&allowed('ccc',$udom)) {
                   10491:         return 'refused';
1.84      www      10492:     }
1.1011    raeburn  10493: # --------------------------------------------------------------- Get Unique ID
                   10494:     my $uname;
                   10495:     if ($cnum =~ /^$match_courseid$/) {
                   10496:         my $chome=&homeserver($cnum,$udom,'true');
                   10497:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10498:             $uname = $cnum;
                   10499:         } else {
1.1038    raeburn  10500:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10501:         }
                   10502:     } else {
1.1038    raeburn  10503:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10504:     }
                   10505:     return $uname if ($uname =~ /^error/);
                   10506: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10507:     if (!defined($course_server)) {
                   10508:         if (defined(&domain($udom,'primary'))) {
                   10509:             $course_server = &domain($udom,'primary');
                   10510:         } else {
                   10511:             $course_server = $env{'user.home'}; 
                   10512:         }
                   10513:     }
                   10514:     my %host_servers =
                   10515:         &Apache::lonnet::get_servers($udom,'library');
                   10516:     unless ($host_servers{$course_server}) {
                   10517:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10518:     }
1.84      www      10519: # ------------------------------------------------------------- Make the course
                   10520:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10521:                       $course_server);
1.84      www      10522:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10523:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10524:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10525: 	return 'error: no such course';
                   10526:     }
1.271     www      10527: # ----------------------------------------------------------------- Course made
1.516     raeburn  10528: # log existence
1.1029    raeburn  10529:     my $now = time;
1.918     raeburn  10530:     my $newcourse = {
                   10531:                     $udom.'_'.$uname => {
1.921     raeburn  10532:                                      description => $description,
                   10533:                                      inst_code   => $inst_code,
                   10534:                                      owner       => $course_owner,
                   10535:                                      type        => $crstype,
1.1029    raeburn  10536:                                      creator     => $env{'user.name'}.':'.
                   10537:                                                     $env{'user.domain'},
                   10538:                                      created     => $now,
                   10539:                                      context     => $context,
1.918     raeburn  10540:                                                 },
                   10541:                     };
1.921     raeburn  10542:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10543: # set toplevel url
1.271     www      10544:     my $topurl=$url;
                   10545:     unless ($nonstandard) {
                   10546: # ------------------------------------------ For standard courses, make top url
                   10547:         my $mapurl=&clutter($url);
1.278     www      10548:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10549:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10550: <map>
                   10551: <resource id="1" type="start"></resource>
                   10552: <resource id="2" src="$mapurl"></resource>
                   10553: <resource id="3" type="finish"></resource>
                   10554: <link index="1" from="1" to="2"></link>
                   10555: <link index="2" from="2" to="3"></link>
                   10556: </map>
                   10557: ENDINITMAP
                   10558:         $topurl=&declutter(
1.638     albertel 10559:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10560:                           );
                   10561:     }
                   10562: # ----------------------------------------------------------- Write preferences
1.84      www      10563:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10564:                      ('description'              => $description,
                   10565:                       'url'                      => $topurl,
                   10566:                       'internal.creator'         => $env{'user.name'}.':'.
                   10567:                                                     $env{'user.domain'},
                   10568:                       'internal.created'         => $now,
                   10569:                       'internal.creationcontext' => $context)
                   10570:                     );
1.84      www      10571:     return '/'.$udom.'/'.$uname;
                   10572: }
                   10573: 
1.1011    raeburn  10574: # ------------------------------------------------------------------- Create ID
                   10575: sub generate_coursenum {
1.1038    raeburn  10576:     my ($udom,$crstype) = @_;
1.1011    raeburn  10577:     my $domdesc = &domain($udom);
                   10578:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10579:     my $first;
                   10580:     if ($crstype eq 'Community') {
                   10581:         $first = '0';
                   10582:     } else {
                   10583:         $first = int(1+rand(9)); 
                   10584:     } 
                   10585:     my $uname=$first.
1.1011    raeburn  10586:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10587:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10588:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10589: # ----------------------------------------------- Make sure that does not exist
                   10590:     my $uhome=&homeserver($uname,$udom,'true');
                   10591:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10592:         if ($crstype eq 'Community') {
                   10593:             $first = '0';
                   10594:         } else {
                   10595:             $first = int(1+rand(9));
                   10596:         }
                   10597:         $uname=$first.
1.1011    raeburn  10598:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10599:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10600:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10601:         $uhome=&homeserver($uname,$udom,'true');
                   10602:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10603:             return 'error: unable to generate unique course-ID';
                   10604:         }
                   10605:     }
                   10606:     return $uname;
                   10607: }
                   10608: 
1.813     albertel 10609: sub is_course {
1.1167    droeschl 10610:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10611:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10612:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10613:     my $uhome=&homeserver($cnum,$cdom);
                   10614:     my $iscourse;
                   10615:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10616:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10617:     } else {
                   10618:         my $hashid = $cdom.':'.$cnum;
                   10619:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10620:         unless (defined($cached)) {
                   10621:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10622:                                         $cnum,undef,undef,'.');
                   10623:             $iscourse = 0;
                   10624:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10625:                 $iscourse = 1;
                   10626:             }
                   10627:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10628:         }
                   10629:     }
                   10630:     return unless($iscourse);
1.1167    droeschl 10631:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10632: }
                   10633: 
1.1015    raeburn  10634: sub store_userdata {
                   10635:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10636:     my $result;
1.1016    raeburn  10637:     if ($datakey ne '') {
1.1013    raeburn  10638:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10639:             if ($udom eq '' || $uname eq '') {
                   10640:                 $udom = $env{'user.domain'};
                   10641:                 $uname = $env{'user.name'};
                   10642:             }
                   10643:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10644:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10645:                 $result = 'error: no_host';
                   10646:             } else {
1.1172.2.118.  .14(raeb 10647:-21):                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10648:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10649: 
                   10650:                 my $namevalue='';
                   10651:                 foreach my $key (keys(%{$storehash})) {
                   10652:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10653:                 }
                   10654:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10655:                 unless ($namespace eq 'courserequests') {
                   10656:                     $datakey = &escape($datakey);
                   10657:                 }
1.1105    raeburn  10658:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10659:                                   $namevalue,$uhome);
1.1013    raeburn  10660:             }
                   10661:         } else {
                   10662:             $result = 'error: data to store was not a hash reference'; 
                   10663:         }
                   10664:     } else {
                   10665:         $result= 'error: invalid requestkey'; 
                   10666:     }
                   10667:     return $result;
                   10668: }
                   10669: 
1.21      www      10670: # ---------------------------------------------------------- Assign Custom Role
                   10671: 
                   10672: sub assigncustomrole {
1.957     raeburn  10673:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10674:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10675:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10676: }
                   10677: 
                   10678: # ----------------------------------------------------------------- Revoke Role
                   10679: 
                   10680: sub revokerole {
1.957     raeburn  10681:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10682:     my $now=time;
1.965     raeburn  10683:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10684: }
                   10685: 
                   10686: # ---------------------------------------------------------- Revoke Custom Role
                   10687: 
                   10688: sub revokecustomrole {
1.957     raeburn  10689:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10690:     my $now=time;
1.357     www      10691:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10692:            $deleteflag,$selfenroll,$context);
1.17      www      10693: }
                   10694: 
1.533     banghart 10695: # ------------------------------------------------------------ Disk usage
1.535     albertel 10696: sub diskusage {
1.955     raeburn  10697:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10698:     $directorypath =~ s/\/$//;
                   10699:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10700:                        .&escape($getpropath).':'.&escape($uname).':'
                   10701:                        .&escape($udom),homeserver($uname,$udom));
                   10702:     if ($listing eq 'unknown_cmd') {
                   10703:         if ($getpropath) {
                   10704:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10705:         }
                   10706:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10707:     }
1.514     albertel 10708:     return $listing;
1.512     banghart 10709: }
                   10710: 
1.566     banghart 10711: sub is_locked {
1.1096    raeburn  10712:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10713:     my @check;
                   10714:     my $is_locked;
1.1093    raeburn  10715:     push (@check,$file_name);
1.613     albertel 10716:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10717: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10718:     my ($tmp)=keys(%locked);
                   10719:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10720:     
1.566     banghart 10721:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10722:         $is_locked = 'false';
                   10723:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10724:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10725:                $is_locked = 'true';
1.1096    raeburn  10726:                if (ref($which) eq 'ARRAY') {
                   10727:                    push(@{$which},$entry);
                   10728:                } else {
                   10729:                    last;
                   10730:                }
1.745     raeburn  10731:            }
                   10732:        }
1.566     banghart 10733:     } else {
                   10734:         $is_locked = 'false';
                   10735:     }
1.1093    raeburn  10736:     return $is_locked;
1.566     banghart 10737: }
                   10738: 
1.759     albertel 10739: sub declutter_portfile {
                   10740:     my ($file) = @_;
1.833     albertel 10741:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10742:     return $file;
                   10743: }
                   10744: 
1.559     banghart 10745: # ------------------------------------------------------------- Mark as Read Only
                   10746: 
                   10747: sub mark_as_readonly {
                   10748:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10749:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10750:     my ($tmp)=keys(%current_permissions);
                   10751:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10752:     foreach my $file (@{$files}) {
1.759     albertel 10753: 	$file = &declutter_portfile($file);
1.561     banghart 10754:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10755:     }
1.613     albertel 10756:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10757:     return;
                   10758: }
                   10759: 
1.572     banghart 10760: # ------------------------------------------------------------Save Selected Files
                   10761: 
                   10762: sub save_selected_files {
                   10763:     my ($user, $path, @files) = @_;
                   10764:     my $filename = $user."savedfiles";
1.573     banghart 10765:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10766:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10767:     foreach my $file (@files) {
1.620     albertel 10768:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10769:     }
                   10770:     foreach my $file (@other_files) {
1.574     banghart 10771:         print (OUT $file."\n");
1.572     banghart 10772:     }
1.574     banghart 10773:     close (OUT);
1.572     banghart 10774:     return 'ok';
                   10775: }
                   10776: 
1.574     banghart 10777: sub clear_selected_files {
                   10778:     my ($user) = @_;
                   10779:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10780:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10781:     print (OUT undef);
                   10782:     close (OUT);
                   10783:     return ("ok");    
                   10784: }
                   10785: 
1.572     banghart 10786: sub files_in_path {
                   10787:     my ($user, $path) = @_;
                   10788:     my $filename = $user."savedfiles";
                   10789:     my %return_files;
1.1172.2.96  raeburn  10790:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10791:     while (my $line_in = <IN>) {
1.574     banghart 10792:         chomp ($line_in);
                   10793:         my @paths_and_file = split (m!/!, $line_in);
                   10794:         my $file_part = pop (@paths_and_file);
                   10795:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10796:         $path_part.='/';
                   10797:         my $path_and_file = $path_part.$file_part;
                   10798:         if ($path_part eq $path) {
                   10799:             $return_files{$file_part}= 'selected';
                   10800:         }
                   10801:     }
1.574     banghart 10802:     close (IN);
                   10803:     return (\%return_files);
1.572     banghart 10804: }
                   10805: 
                   10806: # called in portfolio select mode, to show files selected NOT in current directory
                   10807: sub files_not_in_path {
                   10808:     my ($user, $path) = @_;
                   10809:     my $filename = $user."savedfiles";
                   10810:     my @return_files;
                   10811:     my $path_part;
1.1172.2.96  raeburn  10812:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10813:     while (my $line = <IN>) {
1.572     banghart 10814:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10815:         my @paths_and_file = split(m|/|, $line);
                   10816:         my $file_part = pop(@paths_and_file);
                   10817:         chomp($file_part);
                   10818:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10819:         $path_part .= '/';
                   10820:         my $path_and_file = $path_part.$file_part;
                   10821:         if ($path_part ne $path) {
1.800     albertel 10822:             push(@return_files, ($path_and_file));
1.572     banghart 10823:         }
                   10824:     }
1.800     albertel 10825:     close(OUT);
1.574     banghart 10826:     return (@return_files);
1.572     banghart 10827: }
                   10828: 
1.745     raeburn  10829: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10830: 
1.745     raeburn  10831: sub get_portfile_permissions {
                   10832:     my ($domain,$user) = @_;
1.613     albertel 10833:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10834:     my ($tmp)=keys(%current_permissions);
                   10835:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10836:     return \%current_permissions;
                   10837: }
                   10838: 
                   10839: #---------------------------------------------Get portfolio file access controls
                   10840: 
1.749     raeburn  10841: sub get_access_controls {
1.745     raeburn  10842:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10843:     my %access;
                   10844:     my $real_file = $file;
                   10845:     $file =~ s/\.meta$//;
1.745     raeburn  10846:     if (defined($file)) {
1.749     raeburn  10847:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10848:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10849:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10850:             }
                   10851:         }
1.745     raeburn  10852:     } else {
1.749     raeburn  10853:         foreach my $key (keys(%{$current_permissions})) {
                   10854:             if ($key =~ /\0accesscontrol$/) {
                   10855:                 if (defined($group)) {
                   10856:                     if ($key !~ m-^\Q$group\E/-) {
                   10857:                         next;
                   10858:                     }
                   10859:                 }
                   10860:                 my ($fullpath) = split(/\0/,$key);
                   10861:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10862:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10863:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10864:                     }
                   10865:                 }
                   10866:             }
                   10867:         }
                   10868:     }
                   10869:     return %access;
                   10870: }
                   10871: 
                   10872: sub modify_access_controls {
                   10873:     my ($file_name,$changes,$domain,$user)=@_;
                   10874:     my ($outcome,$deloutcome);
                   10875:     my %store_permissions;
                   10876:     my %new_values;
                   10877:     my %new_control;
                   10878:     my %translation;
                   10879:     my @deletions = ();
                   10880:     my $now = time;
                   10881:     if (exists($$changes{'activate'})) {
                   10882:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10883:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10884:             my $numnew = scalar(@newitems);
                   10885:             for (my $i=0; $i<$numnew; $i++) {
                   10886:                 my $newkey = $newitems[$i];
                   10887:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10888:                 if ($newkey =~ /^\d+:/) { 
                   10889:                     $newkey =~ s/^(\d+)/$newid/;
                   10890:                     $translation{$1} = $newid;
                   10891:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10892:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10893:                     $translation{$1} = $newid;
                   10894:                 }
1.749     raeburn  10895:                 $new_values{$file_name."\0".$newkey} = 
                   10896:                                           $$changes{'activate'}{$newitems[$i]};
                   10897:                 $new_control{$newkey} = $now;
                   10898:             }
                   10899:         }
                   10900:     }
                   10901:     my %todelete;
                   10902:     my %changed_items;
                   10903:     foreach my $action ('delete','update') {
                   10904:         if (exists($$changes{$action})) {
                   10905:             if (ref($$changes{$action}) eq 'HASH') {
                   10906:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10907:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10908:                     if ($action eq 'delete') { 
                   10909:                         $todelete{$itemnum} = 1;
                   10910:                     } else {
                   10911:                         $changed_items{$itemnum} = $key;
                   10912:                     }
                   10913:                 }
1.745     raeburn  10914:             }
                   10915:         }
1.749     raeburn  10916:     }
                   10917:     # get lock on access controls for file.
                   10918:     my $lockhash = {
                   10919:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10920:                                                        ':'.$env{'user.domain'},
                   10921:                    }; 
                   10922:     my $tries = 0;
                   10923:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10924:    
1.1172.2.79  raeburn  10925:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10926:         $tries ++;
1.1172.2.79  raeburn  10927:         sleep(0.1);
1.749     raeburn  10928:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10929:     }
                   10930:     if ($gotlock eq 'ok') {
                   10931:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10932:         my ($tmp)=keys(%curr_permissions);
                   10933:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10934:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10935:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10936:             if (ref($curr_controls) eq 'HASH') {
                   10937:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10938:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10939:                     if (defined($todelete{$itemnum})) {
                   10940:                         push(@deletions,$file_name."\0".$control_item);
                   10941:                     } else {
                   10942:                         if (defined($changed_items{$itemnum})) {
                   10943:                             $new_control{$changed_items{$itemnum}} = $now;
                   10944:                             push(@deletions,$file_name."\0".$control_item);
                   10945:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10946:                         } else {
                   10947:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10948:                         }
                   10949:                     }
1.745     raeburn  10950:                 }
                   10951:             }
                   10952:         }
1.970     raeburn  10953:         my ($group);
                   10954:         if (&is_course($domain,$user)) {
                   10955:             ($group,my $file) = split(/\//,$file_name,2);
                   10956:         }
1.749     raeburn  10957:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10958:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10959:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10960:         #  remove lock
                   10961:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10962:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10963:         my $sqlresult =
1.970     raeburn  10964:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10965:                                     $group);
1.749     raeburn  10966:     } else {
                   10967:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10968:     }
1.749     raeburn  10969:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10970: }
                   10971: 
1.827     raeburn  10972: sub make_public_indefinitely {
                   10973:     my ($requrl) = @_;
                   10974:     my $now = time;
                   10975:     my $action = 'activate';
                   10976:     my $aclnum = 0;
                   10977:     if (&is_portfolio_url($requrl)) {
                   10978:         my (undef,$udom,$unum,$file_name,$group) =
                   10979:             &parse_portfolio_url($requrl);
                   10980:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10981:         my %access_controls = &get_access_controls($current_perms,
                   10982:                                                    $group,$file_name);
                   10983:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10984:             my ($num,$scope,$end,$start) = 
                   10985:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10986:             if ($scope eq 'public') {
                   10987:                 if ($start <= $now && $end == 0) {
                   10988:                     $action = 'none';
                   10989:                 } else {
                   10990:                     $action = 'update';
                   10991:                     $aclnum = $num;
                   10992:                 }
                   10993:                 last;
                   10994:             }
                   10995:         }
                   10996:         if ($action eq 'none') {
                   10997:              return 'ok';
                   10998:         } else {
                   10999:             my %changes;
                   11000:             my $newend = 0;
                   11001:             my $newstart = $now;
                   11002:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11003:             $changes{$action}{$newkey} = {
                   11004:                 type => 'public',
                   11005:                 time => {
                   11006:                     start => $newstart,
                   11007:                     end   => $newend,
                   11008:                 },
                   11009:             };
                   11010:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11011:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11012:             return $outcome;
                   11013:         }
                   11014:     } else {
                   11015:         return 'invalid';
                   11016:     }
                   11017: }
                   11018: 
1.745     raeburn  11019: #------------------------------------------------------Get Marked as Read Only
                   11020: 
                   11021: sub get_marked_as_readonly {
                   11022:     my ($domain,$user,$what,$group) = @_;
                   11023:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11024:     my @readonly_files;
1.629     banghart 11025:     my $cmp1=$what;
                   11026:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11027:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11028:         if (defined($group)) {
                   11029:             if ($file_name !~ m-^\Q$group\E/-) {
                   11030:                 next;
                   11031:             }
                   11032:         }
1.561     banghart 11033:         if (ref($value) eq "ARRAY"){
                   11034:             foreach my $stored_what (@{$value}) {
1.629     banghart 11035:                 my $cmp2=$stored_what;
1.759     albertel 11036:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11037:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11038:                 }
1.629     banghart 11039:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11040:                     push(@readonly_files, $file_name);
1.745     raeburn  11041:                     last;
1.563     banghart 11042:                 } elsif (!defined($what)) {
                   11043:                     push(@readonly_files, $file_name);
1.745     raeburn  11044:                     last;
1.561     banghart 11045:                 }
                   11046:             }
1.745     raeburn  11047:         }
1.561     banghart 11048:     }
                   11049:     return @readonly_files;
                   11050: }
1.577     banghart 11051: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11052: 
1.577     banghart 11053: sub get_marked_as_readonly_hash {
1.745     raeburn  11054:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11055:     my %readonly_files;
1.745     raeburn  11056:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11057:         if (defined($group)) {
                   11058:             if ($file_name !~ m-^\Q$group\E/-) {
                   11059:                 next;
                   11060:             }
                   11061:         }
1.577     banghart 11062:         if (ref($value) eq "ARRAY"){
                   11063:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11064:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11065:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11066:                         if ($lock_descriptor eq 'graded') {
                   11067:                             $readonly_files{$file_name} = 'graded';
                   11068:                         } elsif ($lock_descriptor eq 'handback') {
                   11069:                             $readonly_files{$file_name} = 'handback';
                   11070:                         } else {
                   11071:                             if (!exists($readonly_files{$file_name})) {
                   11072:                                 $readonly_files{$file_name} = 'locked';
                   11073:                             }
                   11074:                         }
1.745     raeburn  11075:                     }
1.750     banghart 11076:                 } 
1.577     banghart 11077:             }
                   11078:         } 
                   11079:     }
                   11080:     return %readonly_files;
                   11081: }
1.559     banghart 11082: # ------------------------------------------------------------ Unmark as Read Only
                   11083: 
                   11084: sub unmark_as_readonly {
1.629     banghart 11085:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11086:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11087:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11088:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11089:     my $symb_crs = $what;
                   11090:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11091:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11092:     my ($tmp)=keys(%current_permissions);
                   11093:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11094:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11095:     foreach my $file (@readonly_files) {
1.759     albertel 11096: 	my $clean_file = &declutter_portfile($file);
                   11097: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11098: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11099:         my @new_locks;
                   11100:         my @del_keys;
                   11101:         if (ref($current_locks) eq "ARRAY"){
                   11102:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11103:                 my $compare=$locker;
1.749     raeburn  11104:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11105:                     $compare=join('',@{$locker});
1.746     raeburn  11106:                     if ($compare ne $symb_crs) {
                   11107:                         push(@new_locks, $locker);
                   11108:                     }
1.563     banghart 11109:                 }
                   11110:             }
1.650     albertel 11111:             if (scalar(@new_locks) > 0) {
1.563     banghart 11112:                 $current_permissions{$file} = \@new_locks;
                   11113:             } else {
                   11114:                 push(@del_keys, $file);
1.613     albertel 11115:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11116:                 delete($current_permissions{$file});
1.563     banghart 11117:             }
                   11118:         }
1.561     banghart 11119:     }
1.613     albertel 11120:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11121:     return;
                   11122: }
1.512     banghart 11123: 
1.17      www      11124: # ------------------------------------------------------------ Directory lister
                   11125: 
                   11126: sub dirlist {
1.955     raeburn  11127:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11128:     $uri=~s/^\///;
                   11129:     $uri=~s/\/$//;
1.253     stredwic 11130:     my ($udom, $uname);
1.955     raeburn  11131:     if ($getuserdir) {
1.253     stredwic 11132:         $udom = $userdomain;
                   11133:         $uname = $username;
1.955     raeburn  11134:     } else {
                   11135:         (undef,$udom,$uname)=split(/\//,$uri);
                   11136:         if(defined($userdomain)) {
                   11137:             $udom = $userdomain;
                   11138:         }
                   11139:         if(defined($username)) {
                   11140:             $uname = $username;
                   11141:         }
1.253     stredwic 11142:     }
1.955     raeburn  11143:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11144: 
1.955     raeburn  11145:     $dirRoot = $perlvar{'lonDocRoot'};
                   11146:     if (defined($getpropath)) {
                   11147:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11148:         $dirRoot =~ s/\/$//;
1.955     raeburn  11149:     } elsif (defined($getuserdir)) {
                   11150:         my $subdir=$uname.'__';
                   11151:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11152:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11153:                    ."/$udom/$subdir/$uname";
                   11154:     } elsif (defined($alternateRoot)) {
                   11155:         $dirRoot = $alternateRoot;
1.751     banghart 11156:     }
1.253     stredwic 11157: 
                   11158:     if($udom) {
                   11159:         if($uname) {
1.1135    raeburn  11160:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11161:             if ($uhome eq 'no_host') {
                   11162:                 return ([],'no_host');
                   11163:             }
1.955     raeburn  11164:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11165:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11166:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11167:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11168:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11169:             } else {
                   11170:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11171:             }
1.605     matthew  11172:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11173:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11174:                 @listing_results = split(/:/,$listing);
                   11175:             } else {
                   11176:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11177:             }
1.1135    raeburn  11178:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11179:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11180:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11181:                 return ([],$listing);
                   11182:             } else {
                   11183:                 return (\@listing_results);
1.1135    raeburn  11184:             }
1.955     raeburn  11185:         } elsif(!$alternateRoot) {
1.1136    raeburn  11186:             my (%allusers,%listerror);
1.841     albertel 11187: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11188:  	    foreach my $tryserver (keys(%servers)) {
                   11189:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11190:                                   &escape($udom),$tryserver);
                   11191:                 if ($listing eq 'unknown_cmd') {
                   11192: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11193: 				      $udom, $tryserver);
                   11194:                 } else {
                   11195:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11196:                 }
1.841     albertel 11197: 		if ($listing eq 'unknown_cmd') {
                   11198: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11199: 				      $udom, $tryserver);
                   11200: 		    @listing_results = split(/:/,$listing);
                   11201: 		} else {
                   11202: 		    @listing_results =
                   11203: 			map { &unescape($_); } split(/:/,$listing);
                   11204: 		}
1.1136    raeburn  11205:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11206:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11207:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11208:                     $listerror{$tryserver} = $listing;
                   11209:                 } else {
1.841     albertel 11210: 		    foreach my $line (@listing_results) {
                   11211: 			my ($entry) = split(/&/,$line,2);
                   11212: 			$allusers{$entry} = 1;
                   11213: 		    }
                   11214: 		}
1.253     stredwic 11215:             }
1.1136    raeburn  11216:             my @alluserslist=();
1.800     albertel 11217:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11218:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11219:             }
1.1172.2.80  raeburn  11220:             if (!%listerror) {
                   11221:                 # no errors
                   11222:                 return (\@alluserslist);
                   11223:             } elsif (scalar(keys(%servers)) == 1) {
                   11224:                 # one library server, one error
                   11225:                 my ($key) = keys(%listerror);
                   11226:                 return (\@alluserslist, $listerror{$key});
                   11227:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11228:                 # con_lost indicates that we might miss data from at least one
                   11229:                 # library server
                   11230:                 return (\@alluserslist, 'con_lost');
                   11231:             } else {
                   11232:                 # multiple library servers and no con_lost -> data should be
                   11233:                 # complete.
                   11234:                 return (\@alluserslist);
                   11235:             }
                   11236: 
1.253     stredwic 11237:         } else {
1.1136    raeburn  11238:             return ([],'missing username');
1.253     stredwic 11239:         }
1.955     raeburn  11240:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11241:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11242:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11243:         return (\@all_domains);
1.955     raeburn  11244:     } else {
1.1136    raeburn  11245:         return ([],'missing domain');
1.275     stredwic 11246:     }
                   11247: }
                   11248: 
                   11249: # --------------------------------------------- GetFileTimestamp
                   11250: # This function utilizes dirlist and returns the date stamp for
                   11251: # when it was last modified.  It will also return an error of -1
                   11252: # if an error occurs
                   11253: 
                   11254: sub GetFileTimestamp {
1.955     raeburn  11255:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11256:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11257:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11258:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11259:                                     undef,$getuserdir);
                   11260:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11261:         return -1;
                   11262:     }
                   11263:     if (ref($fileref) eq 'ARRAY') {
                   11264:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11265:         # @stats contains first the filename, then the stat output
                   11266:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11267:     } else {
                   11268:         return -1;
1.253     stredwic 11269:     }
1.26      www      11270: }
                   11271: 
1.712     albertel 11272: sub stat_file {
                   11273:     my ($uri) = @_;
1.787     albertel 11274:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11275: 
1.955     raeburn  11276:     my ($udom,$uname,$file);
1.712     albertel 11277:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11278: 	($udom,$uname,$file) =
1.811     albertel 11279: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11280: 	$file = 'userfiles/'.$file;
                   11281:     }
                   11282:     if ($uri =~ m-^/res/-) {
                   11283: 	($udom,$uname) = 
1.807     albertel 11284: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11285: 	$file = $uri;
                   11286:     }
                   11287: 
                   11288:     if (!$udom || !$uname || !$file) {
                   11289: 	# unable to handle the uri
                   11290: 	return ();
                   11291:     }
1.956     raeburn  11292:     my $getpropath;
                   11293:     if ($file =~ /^userfiles\//) {
                   11294:         $getpropath = 1;
                   11295:     }
1.1136    raeburn  11296:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11297:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11298:         return ();
                   11299:     } else {
                   11300:         if (ref($listref) eq 'ARRAY') {
                   11301:             my @stats = split('&',$listref->[0]);
                   11302: 	    shift(@stats); #filename is first
                   11303: 	    return @stats;
                   11304:         }
1.712     albertel 11305:     }
                   11306:     return ();
                   11307: }
                   11308: 
1.26      www      11309: # -------------------------------------------------------- Value of a Condition
                   11310: 
1.713     albertel 11311: # gets the value of a specific preevaluated condition
                   11312: #    stored in the string  $env{user.state.<cid>}
                   11313: # or looks up a condition reference in the bighash and if if hasn't
                   11314: # already been evaluated recurses into docondval to get the value of
                   11315: # the condition, then memoizing it to 
                   11316: #   $env{user.state.<cid>.<condition>}
1.40      www      11317: sub directcondval {
                   11318:     my $number=shift;
1.620     albertel 11319:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11320: 	&Apache::lonuserstate::evalstate();
                   11321:     }
1.713     albertel 11322:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11323: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11324:     } elsif ($number =~ /^_/) {
                   11325: 	my $sub_condition;
                   11326: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11327: 		&GDBM_READER(),0640)) {
                   11328: 	    $sub_condition=$bighash{'conditions'.$number};
                   11329: 	    untie(%bighash);
                   11330: 	}
                   11331: 	my $value = &docondval($sub_condition);
1.949     raeburn  11332: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11333: 	return $value;
                   11334:     }
1.620     albertel 11335:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11336:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11337:     } else {
                   11338:        return 2;
                   11339:     }
                   11340: }
                   11341: 
1.713     albertel 11342: # get the collection of conditions for this resource
1.26      www      11343: sub condval {
                   11344:     my $condidx=shift;
1.54      www      11345:     my $allpathcond='';
1.713     albertel 11346:     foreach my $cond (split(/\|/,$condidx)) {
                   11347: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11348: 	    $allpathcond.=
                   11349: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11350: 	}
1.191     harris41 11351:     }
1.54      www      11352:     $allpathcond=~s/\|$//;
1.713     albertel 11353:     return &docondval($allpathcond);
                   11354: }
                   11355: 
                   11356: #evaluates an expression of conditions
                   11357: sub docondval {
                   11358:     my ($allpathcond) = @_;
                   11359:     my $result=0;
                   11360:     if ($env{'request.course.id'}
                   11361: 	&& defined($allpathcond)) {
                   11362: 	my $operand='|';
                   11363: 	my @stack;
                   11364: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11365: 	    if ($chunk eq '(') {
                   11366: 		push @stack,($operand,$result);
                   11367: 	    } elsif ($chunk eq ')') {
                   11368: 		my $before=pop @stack;
                   11369: 		if (pop @stack eq '&') {
                   11370: 		    $result=$result>$before?$before:$result;
                   11371: 		} else {
                   11372: 		    $result=$result>$before?$result:$before;
                   11373: 		}
                   11374: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11375: 		$operand=$chunk;
                   11376: 	    } else {
                   11377: 		my $new=directcondval($chunk);
                   11378: 		if ($operand eq '&') {
                   11379: 		    $result=$result>$new?$new:$result;
                   11380: 		} else {
                   11381: 		    $result=$result>$new?$result:$new;
                   11382: 		}
                   11383: 	    }
                   11384: 	}
1.26      www      11385:     }
                   11386:     return $result;
1.421     albertel 11387: }
                   11388: 
                   11389: # ---------------------------------------------------- Devalidate courseresdata
                   11390: 
                   11391: sub devalidatecourseresdata {
                   11392:     my ($coursenum,$coursedomain)=@_;
                   11393:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11394:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11395: }
                   11396: 
1.763     www      11397: 
1.200     www      11398: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11399: #
                   11400: #  Parameters:
                   11401: #      $coursenum    - Number of the course.
                   11402: #      $coursedomain - Domain at which the course was created.
                   11403: #  Returns:
                   11404: #     A hash of the course parameters along (I think) with timestamps
                   11405: #     and version info.
1.877     foxr     11406: 
1.624     albertel 11407: sub get_courseresdata {
                   11408:     my ($coursenum,$coursedomain)=@_;
1.200     www      11409:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11410:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11411:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11412:     my %dumpreply;
1.417     albertel 11413:     unless (defined($cached)) {
1.624     albertel 11414: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11415: 	$result=\%dumpreply;
1.251     albertel 11416: 	my ($tmp) = keys(%dumpreply);
                   11417: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11418: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11419: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11420: 	    return $tmp;
1.416     albertel 11421: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11422: 	    $result=undef;
1.599     albertel 11423: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11424: 	}
                   11425:     }
1.624     albertel 11426:     return $result;
                   11427: }
                   11428: 
1.633     albertel 11429: sub devalidateuserresdata {
                   11430:     my ($uname,$udom)=@_;
                   11431:     my $hashid="$udom:$uname";
                   11432:     &devalidate_cache_new('userres',$hashid);
                   11433: }
                   11434: 
1.624     albertel 11435: sub get_userresdata {
                   11436:     my ($uname,$udom)=@_;
                   11437:     #most student don\'t have any data set, check if there is some data
                   11438:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11439: 
                   11440:     my $hashid="$udom:$uname";
                   11441:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11442:     if (!defined($cached)) {
                   11443: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11444: 	$result=\%resourcedata;
                   11445: 	&do_cache_new('userres',$hashid,$result,600);
                   11446:     }
                   11447:     my ($tmp)=keys(%$result);
                   11448:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11449: 	return $result;
                   11450:     }
                   11451:     #error 2 occurs when the .db doesn't exist
                   11452:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11453:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11454: 	    &logthis("<font color=\"blue\">WARNING:".
                   11455: 		     " Trying to get resource data for ".
                   11456: 		     $uname." at ".$udom.": ".
                   11457: 		     $tmp."</font>");
                   11458:         }
1.624     albertel 11459:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11460: 	#&EXT_cache_set($udom,$uname);
                   11461: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11462: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11463:     }
                   11464:     return $tmp;
                   11465: }
1.879     foxr     11466: #----------------------------------------------- resdata - return resource data
                   11467: #  Purpose:
                   11468: #    Return resource data for either users or for a course.
                   11469: #  Parameters:
                   11470: #     $name      - Course/user name.
                   11471: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11472:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11473: #     @which     - Array of names of resources desired.
                   11474: #  Returns:
                   11475: #     The value of the first reasource in @which that is found in the
                   11476: #     resource hash.
                   11477: #  Exceptional Conditions:
                   11478: #     If the $type passed in is not valid (not the string 'course' or 
                   11479: #     'user', an undefined  reference is returned.
                   11480: #     If none of the resources are found, an undef is returned
1.624     albertel 11481: sub resdata {
                   11482:     my ($name,$domain,$type,@which)=@_;
                   11483:     my $result;
                   11484:     if ($type eq 'course') {
                   11485: 	$result=&get_courseresdata($name,$domain);
                   11486:     } elsif ($type eq 'user') {
                   11487: 	$result=&get_userresdata($name,$domain);
                   11488:     }
                   11489:     if (!ref($result)) { return $result; }    
1.251     albertel 11490:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11491:20): 	if (defined($result->{$item->[0]})) {
                   11492:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11493:20):         }
1.250     albertel 11494:     }
1.291     albertel 11495:     return undef;
1.200     www      11496: }
                   11497: 
1.1172.2.118.  .10(raeb 11498:-20): sub get_domain_lti {
                   11499:-20):     my ($cdom,$context) = @_;
                   11500:-20):     my ($name,%lti);
                   11501:-20):     if ($context eq 'consumer') {
                   11502:-20):         $name = 'ltitools';
                   11503:-20):     } elsif ($context eq 'provider') {
                   11504:-20):         $name = 'lti';
                   11505:-20):     } else {
                   11506:-20):         return %lti;
                   11507:-20):     }
                   11508:-20):     my ($result,$cached)=&is_cached_new($name,$cdom);
          .1(raebu 11509:20):     if (defined($cached)) {
                   11510:20):         if (ref($result) eq 'HASH') {
          .10(raeb 11511:-20):             %lti = %{$result};
          .1(raebu 11512:20):         }
                   11513:20):     } else {
          .10(raeb 11514:-20):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11515:-20):         if (ref($domconfig{$name}) eq 'HASH') {
                   11516:-20):             %lti = %{$domconfig{$name}};
                   11517:-20):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11518:-20):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11519:-20):                 foreach my $id (keys(%lti)) {
                   11520:-20):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
          .1(raebu 11521:20):                         foreach my $item ('key','secret') {
          .10(raeb 11522:-20):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
          .1(raebu 11523:20):                         }
                   11524:20):                     }
                   11525:20):                 }
                   11526:20):             }
                   11527:20):         }
                   11528:20):         my $cachetime = 24*60*60;
          .10(raeb 11529:-20):         &do_cache_new($name,$cdom,\%lti,$cachetime);
          .1(raebu 11530:20):     }
          .10(raeb 11531:-20):     return %lti;
          .1(raebu 11532:20): }
                   11533:20): 
1.1172.2.31  raeburn  11534: sub get_numsuppfiles {
                   11535:     my ($cnum,$cdom,$ignorecache)=@_;
                   11536:     my $hashid=$cnum.':'.$cdom;
                   11537:     my ($suppcount,$cached);
                   11538:     unless ($ignorecache) {
                   11539:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11540:     }
                   11541:     unless (defined($cached)) {
                   11542:         my $chome=&homeserver($cnum,$cdom);
                   11543:         unless ($chome eq 'no_host') {
                   11544:             ($suppcount,my $errors) = (0,0);
                   11545:             my $suppmap = 'supplemental.sequence';
                   11546:             ($suppcount,$errors) =
                   11547:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11548:         }
                   11549:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11550:     }
                   11551:     return $suppcount;
                   11552: }
                   11553: 
1.379     matthew  11554: #
                   11555: # EXT resource caching routines
                   11556: #
                   11557: 
                   11558: sub clear_EXT_cache_status {
1.383     albertel 11559:     &delenv('cache.EXT.');
1.379     matthew  11560: }
                   11561: 
                   11562: sub EXT_cache_status {
                   11563:     my ($target_domain,$target_user) = @_;
1.383     albertel 11564:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11565:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11566:         # We know already the user has no data
                   11567:         return 1;
                   11568:     } else {
                   11569:         return 0;
                   11570:     }
                   11571: }
                   11572: 
                   11573: sub EXT_cache_set {
                   11574:     my ($target_domain,$target_user) = @_;
1.383     albertel 11575:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11576:     #&appenv({$cachename => time});
1.379     matthew  11577: }
                   11578: 
1.28      www      11579: # --------------------------------------------------------- Value of a Variable
1.58      www      11580: sub EXT {
1.715     albertel 11581: 
1.1172.2.28  raeburn  11582:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11583:     unless ($varname) { return ''; }
1.218     albertel 11584:     #get real user name/domain, courseid and symb
                   11585:     my $courseid;
1.359     albertel 11586:     my $publicuser;
1.427     www      11587:     if ($symbparm) {
                   11588: 	$symbparm=&get_symb_from_alias($symbparm);
                   11589:     }
1.218     albertel 11590:     if (!($uname && $udom)) {
1.790     albertel 11591:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11592:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11593:     } else {
1.620     albertel 11594: 	$courseid=$env{'request.course.id'};
1.218     albertel 11595:     }
1.48      www      11596:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11597:     my $rest;
1.320     albertel 11598:     if (defined($therest[0])) {
1.48      www      11599:        $rest=join('.',@therest);
                   11600:     } else {
                   11601:        $rest='';
                   11602:     }
1.320     albertel 11603: 
1.57      www      11604:     my $qualifierrest=$qualifier;
                   11605:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11606:     my $spacequalifierrest=$space;
                   11607:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11608:     if ($realm eq 'user') {
1.48      www      11609: # --------------------------------------------------------------- user.resource
                   11610: 	if ($space eq 'resource') {
1.651     albertel 11611: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11612: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11613: 		 &&
1.744     albertel 11614: 		 ($symbparm eq &symbread()) ) {	
                   11615: 		# if we are in the middle of processing the resource the
                   11616: 		# get the value we are planning on committing
                   11617:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11618:                     return $Apache::lonhomework::results{$qualifierrest};
                   11619:                 } else {
                   11620:                     return $Apache::lonhomework::history{$qualifierrest};
                   11621:                 }
1.335     albertel 11622: 	    } else {
1.359     albertel 11623: 		my %restored;
1.620     albertel 11624: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11625: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11626: 		} else {
                   11627: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11628: 		}
1.335     albertel 11629: 		return $restored{$qualifierrest};
                   11630: 	    }
1.48      www      11631: # ----------------------------------------------------------------- user.access
                   11632:         } elsif ($space eq 'access') {
1.218     albertel 11633: 	    # FIXME - not supporting calls for a specific user
1.48      www      11634:             return &allowed($qualifier,$rest);
                   11635: # ------------------------------------------ user.preferences, user.environment
                   11636:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11637: 	    if (($uname eq $env{'user.name'}) &&
                   11638: 		($udom eq $env{'user.domain'})) {
                   11639: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11640: 	    } else {
1.359     albertel 11641: 		my %returnhash;
                   11642: 		if (!$publicuser) {
                   11643: 		    %returnhash=&userenvironment($udom,$uname,
                   11644: 						 $qualifierrest);
                   11645: 		}
1.218     albertel 11646: 		return $returnhash{$qualifierrest};
                   11647: 	    }
1.48      www      11648: # ----------------------------------------------------------------- user.course
                   11649:         } elsif ($space eq 'course') {
1.218     albertel 11650: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11651:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11652: # ------------------------------------------------------------------- user.role
                   11653:         } elsif ($space eq 'role') {
1.218     albertel 11654: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11655:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11656:             if ($qualifier eq 'value') {
                   11657: 		return $role;
                   11658:             } elsif ($qualifier eq 'extent') {
                   11659:                 return $where;
                   11660:             }
                   11661: # ----------------------------------------------------------------- user.domain
                   11662:         } elsif ($space eq 'domain') {
1.218     albertel 11663:             return $udom;
1.48      www      11664: # ------------------------------------------------------------------- user.name
                   11665:         } elsif ($space eq 'name') {
1.218     albertel 11666:             return $uname;
1.48      www      11667: # ---------------------------------------------------- Any other user namespace
1.29      www      11668:         } else {
1.359     albertel 11669: 	    my %reply;
                   11670: 	    if (!$publicuser) {
                   11671: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11672: 	    }
                   11673: 	    return $reply{$qualifierrest};
1.48      www      11674:         }
1.236     www      11675:     } elsif ($realm eq 'query') {
                   11676: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11677:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11678: 						[$spacequalifierrest]);
1.620     albertel 11679: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11680:    } elsif ($realm eq 'request') {
1.48      www      11681: # ------------------------------------------------------------- request.browser
                   11682:         if ($space eq 'browser') {
1.1145    bisitz   11683:             return $env{'browser.'.$qualifier};
1.57      www      11684: # ------------------------------------------------------------ request.filename
                   11685:         } else {
1.620     albertel 11686:             return $env{'request.'.$spacequalifierrest};
1.29      www      11687:         }
1.28      www      11688:     } elsif ($realm eq 'course') {
1.48      www      11689: # ---------------------------------------------------------- course.description
1.620     albertel 11690:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11691:     } elsif ($realm eq 'resource') {
1.165     www      11692: 
1.620     albertel 11693: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11694: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11695: 	}
1.693     albertel 11696: 
1.1172.2.30  raeburn  11697:         if ($qualifier eq '') {
                   11698: 	    if ($space eq 'title') {
                   11699: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11700: 	        return &gettitle($symbparm);
                   11701: 	    }
1.693     albertel 11702: 	
1.1172.2.30  raeburn  11703: 	    if ($space eq 'map') {
                   11704: 	        my ($map) = &decode_symb($symbparm);
                   11705: 	        return &symbread($map);
                   11706: 	    }
                   11707:             if ($space eq 'maptitle') {
                   11708:                 my ($map) = &decode_symb($symbparm);
                   11709:                 return &gettitle($map);
                   11710:             }
                   11711: 	    if ($space eq 'filename') {
                   11712: 	        if ($symbparm) {
                   11713: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11714: 	        }
                   11715: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11716: 	    }
1.1172.2.30  raeburn  11717: 
                   11718:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11719:                 if ($space eq 'visibleparts') {
                   11720:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11721:                     my $item;
                   11722:                     if (ref($navmap)) {
                   11723:                         my $res = $navmap->getBySymb($symbparm);
                   11724:                         my $parts = $res->parts();
                   11725:                         if (ref($parts) eq 'ARRAY') {
                   11726:                             $item = join(',',@{$parts});
                   11727:                         }
                   11728:                         undef($navmap);
                   11729:                     }
                   11730:                     return $item;
                   11731:                 }
                   11732:             }
                   11733:         }
1.693     albertel 11734: 
                   11735: 	my ($section, $group, @groups);
1.593     albertel 11736: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11737:         if (($courseid eq '') && ($cid)) {
                   11738:             $courseid = $cid;
                   11739:         }
                   11740: 	if (($symbparm && $courseid) && 
                   11741: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11742: 
1.218     albertel 11743: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11744: 
1.60      www      11745: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11746: 	    my $symbp=$symbparm;
1.735     albertel 11747: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11748: 
                   11749: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11750: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11751: 
1.620     albertel 11752: 	    if (($env{'user.name'} eq $uname) &&
                   11753: 		($env{'user.domain'} eq $udom)) {
                   11754: 		$section=$env{'request.course.sec'};
1.733     raeburn  11755:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11756:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11757: 	    } else {
1.539     albertel 11758: 		if (! defined($usection)) {
1.551     albertel 11759: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11760: 		} else {
                   11761: 		    $section = $usection;
                   11762: 		}
1.733     raeburn  11763:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11764: 	    }
                   11765: 
                   11766: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11767: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11768: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11769: 
1.593     albertel 11770: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11771: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11772: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11773: 
1.60      www      11774: # ----------------------------------------------------------- first, check user
1.624     albertel 11775: 
                   11776: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11777: 				       ([$courselevelr,'resource'],
                   11778: 					[$courselevelm,'map'     ],
                   11779: 					[$courselevel, 'course'  ]));
1.931     albertel 11780: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11781: 
1.594     albertel 11782: # ------------------------------------------------ second, check some of course
1.684     raeburn  11783:             my $coursereply;
1.691     raeburn  11784:             if (@groups > 0) {
                   11785:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11786:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11787:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11788:             }
1.96      www      11789: 
1.684     raeburn  11790: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11791: 				  $env{'course.'.$courseid.'.domain'},
                   11792: 				  'course',
                   11793: 				  ([$seclevelr,   'resource'],
                   11794: 				   [$seclevelm,   'map'     ],
                   11795: 				   [$seclevel,    'course'  ],
                   11796: 				   [$courselevelr,'resource']));
                   11797: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11798: 
1.60      www      11799: # ------------------------------------------------------ third, check map parms
1.218     albertel 11800: 	    my %parmhash=();
                   11801: 	    my $thisparm='';
                   11802: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11803: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11804: 		    &GDBM_READER(),0640)) {
1.218     albertel 11805: 		$thisparm=$parmhash{$symbparm};
                   11806: 		untie(%parmhash);
                   11807: 	    }
1.927     albertel 11808: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11809: 	}
1.594     albertel 11810: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11811: 
1.218     albertel 11812: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11813: 	my $filename;
                   11814: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11815: 	if ($symbparm) {
1.409     www      11816: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11817: 	} else {
1.620     albertel 11818: 	    $filename=$env{'request.filename'};
1.282     albertel 11819: 	}
                   11820: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11821: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11822: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11823: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11824: 
1.927     albertel 11825: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11826: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11827: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11828: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11829: 				     $env{'course.'.$courseid.'.domain'},
                   11830: 				     'course',
1.927     albertel 11831: 				     ([$courselevelm,'map'   ],
                   11832: 				      [$courselevel, 'course']));
                   11833: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11834: 	}
1.145     www      11835: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11836: 	unless ($space eq '0') {
1.336     albertel 11837: 	    my @parts=split(/_/,$space);
                   11838: 	    my $id=pop(@parts);
                   11839: 	    my $part=join('_',@parts);
                   11840: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11841: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11842: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11843: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11844: 	}
1.395     albertel 11845: 	if ($recurse) { return undef; }
                   11846: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11847: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11848: # ---------------------------------------------------- Any other user namespace
                   11849:     } elsif ($realm eq 'environment') {
                   11850: # ----------------------------------------------------------------- environment
1.620     albertel 11851: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11852: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11853: 	} else {
1.770     albertel 11854: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11855: 		return '';
                   11856: 	    }
1.219     albertel 11857: 	    my %returnhash=&userenvironment($udom,$uname,
                   11858: 					    $spacequalifierrest);
                   11859: 	    return $returnhash{$spacequalifierrest};
                   11860: 	}
1.28      www      11861:     } elsif ($realm eq 'system') {
1.48      www      11862: # ----------------------------------------------------------------- system.time
                   11863: 	if ($space eq 'time') {
                   11864: 	    return time;
                   11865:         }
1.696     albertel 11866:     } elsif ($realm eq 'server') {
                   11867: # ----------------------------------------------------------------- system.time
                   11868: 	if ($space eq 'name') {
                   11869: 	    return $ENV{'SERVER_NAME'};
                   11870:         }
1.28      www      11871:     }
1.48      www      11872:     return '';
1.61      www      11873: }
                   11874: 
1.927     albertel 11875: sub get_reply {
                   11876:     my ($reply_value) = @_;
1.940     raeburn  11877:     if (ref($reply_value) eq 'ARRAY') {
                   11878:         if (wantarray) {
                   11879: 	    return @$reply_value;
                   11880:         }
                   11881:         return $reply_value->[0];
                   11882:     } else {
                   11883:         return $reply_value;
1.927     albertel 11884:     }
                   11885: }
                   11886: 
1.691     raeburn  11887: sub check_group_parms {
                   11888:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11889:     my @groupitems = ();
                   11890:     my $resultitem;
1.927     albertel 11891:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11892:     foreach my $group (@{$groups}) {
                   11893:         foreach my $level (@levels) {
1.927     albertel 11894:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11895:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11896:         }
                   11897:     }
                   11898:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11899:                             $env{'course.'.$courseid.'.domain'},
                   11900:                                      'course',@groupitems);
                   11901:     return $coursereply;
                   11902: }
                   11903: 
                   11904: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11905:     my ($courseid,@groups) = @_;
                   11906:     @groups = sort(@groups);
1.691     raeburn  11907:     return @groups;
                   11908: }
                   11909: 
1.395     albertel 11910: sub packages_tab_default {
                   11911:     my ($uri,$varname)=@_;
                   11912:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11913: 
                   11914:     my (@extension,@specifics,$do_default);
                   11915:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11916: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11917: 	if ($pack_type eq 'default') {
                   11918: 	    $do_default=1;
                   11919: 	} elsif ($pack_type eq 'extension') {
                   11920: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11921: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11922: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11923: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11924: 	}
                   11925:     }
                   11926:     # first look for a package that matches the requested part id
                   11927:     foreach my $package (@specifics) {
                   11928: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11929: 	next if ($pack_part ne $part);
                   11930: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11931: 	    return $packagetab{"$pack_type&$name&default"};
                   11932: 	}
                   11933:     }
                   11934:     # look for any possible matching non extension_ package
                   11935:     foreach my $package (@specifics) {
                   11936: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11937: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11938: 	    return $packagetab{"$pack_type&$name&default"};
                   11939: 	}
1.585     albertel 11940: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11941: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11942: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11943: 	}
                   11944:     }
1.738     albertel 11945:     # look for any posible extension_ match
                   11946:     foreach my $package (@extension) {
                   11947: 	my ($package,$pack_type)=@{$package};
                   11948: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11949: 	    return $packagetab{"$pack_type&$name&default"};
                   11950: 	}
                   11951: 	if (defined($packagetab{$package."&$name&default"})) {
                   11952: 	    return $packagetab{$package."&$name&default"};
                   11953: 	}
                   11954:     }
                   11955:     # look for a global default setting
                   11956:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11957: 	return $packagetab{"default&$name&default"};
                   11958:     }
1.395     albertel 11959:     return undef;
                   11960: }
                   11961: 
1.334     albertel 11962: sub add_prefix_and_part {
                   11963:     my ($prefix,$part)=@_;
                   11964:     my $keyroot;
                   11965:     if (defined($prefix) && $prefix !~ /^__/) {
                   11966: 	# prefix that has a part already
                   11967: 	$keyroot=$prefix;
                   11968:     } elsif (defined($prefix)) {
                   11969: 	# prefix that is missing a part
                   11970: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11971:     } else {
                   11972: 	# no prefix at all
                   11973: 	if (defined($part)) { $keyroot='_'.$part; }
                   11974:     }
                   11975:     return $keyroot;
                   11976: }
                   11977: 
1.71      www      11978: # ---------------------------------------------------------------- Get metadata
                   11979: 
1.599     albertel 11980: my %metaentry;
1.1070    www      11981: my %importedpartids;
1.1172.2.99  raeburn  11982: my %importedrespids;
1.71      www      11983: sub metadata {
1.176     www      11984:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11985:     $uri=&declutter($uri);
1.288     albertel 11986:     # if it is a non metadata possible uri return quickly
1.529     albertel 11987:     if (($uri eq '') || 
                   11988: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11989:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11990:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11991: 	return undef;
                   11992:     }
1.1172.2.49  raeburn  11993:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11994: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11995: 	return undef;
1.288     albertel 11996:     }
1.73      www      11997:     my $filename=$uri;
                   11998:     $uri=~s/\.meta$//;
1.172     www      11999: #
                   12000: # Is the metadata already cached?
1.177     www      12001: # Look at timestamp of caching
1.172     www      12002: # Everything is cached by the main uri, libraries are never directly cached
                   12003: #
1.428     albertel 12004:     if (!defined($liburi)) {
1.599     albertel 12005: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12006: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12007:     }
                   12008:     {
1.1069    www      12009: # Imported parts would go here
1.1172.2.99  raeburn  12010:         my @origfiletagids=();
1.1069    www      12011:         my $importedparts=0;
1.1172.2.99  raeburn  12012: 
                   12013: # Imported responseids would go here
                   12014:         my $importedresponses=0;
1.172     www      12015: #
                   12016: # Is this a recursive call for a library?
                   12017: #
1.599     albertel 12018: #	if (! exists($metacache{$uri})) {
                   12019: #	    $metacache{$uri}={};
                   12020: #	}
1.924     albertel 12021: 	my $cachetime = 60*60;
1.171     www      12022:         if ($liburi) {
                   12023: 	    $liburi=&declutter($liburi);
                   12024:             $filename=$liburi;
1.401     bowersj2 12025:         } else {
1.599     albertel 12026: 	    &devalidate_cache_new('meta',$uri);
                   12027: 	    undef(%metaentry);
1.401     bowersj2 12028: 	}
1.140     www      12029:         my %metathesekeys=();
1.73      www      12030:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12031: 	my $metastring;
1.1140    www      12032: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12033: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12034: 	    $metastring = 
1.929     albertel 12035: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12036: 					  ('grade_target' => 'meta'));
                   12037: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12038: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12039:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12040: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12041: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12042: 	    $metastring=&getfile($file);
1.489     albertel 12043: 	}
1.208     albertel 12044:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12045:         my $token;
1.140     www      12046:         undef %metathesekeys;
1.71      www      12047:         while ($token=$parser->get_token) {
1.339     albertel 12048: 	    if ($token->[0] eq 'S') {
                   12049: 		if (defined($token->[2]->{'package'})) {
1.172     www      12050: #
                   12051: # This is a package - get package info
                   12052: #
1.339     albertel 12053: 		    my $package=$token->[2]->{'package'};
                   12054: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12055: 		    if (defined($token->[2]->{'id'})) { 
                   12056: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12057: 		    }
1.599     albertel 12058: 		    if ($metaentry{':packages'}) {
                   12059: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12060: 		    } else {
1.599     albertel 12061: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12062: 		    }
1.736     albertel 12063: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12064: 			my $part=$keyroot;
                   12065: 			$part=~s/^\_//;
1.736     albertel 12066: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12067: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12068: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12069: 			    # ignore package.tab specified default values
                   12070:                             # here &package_tab_default() will fetch those
                   12071: 			    if ($subp eq 'default') { next; }
1.736     albertel 12072: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12073: 			    my $unikey;
                   12074: 			    if ($pack =~ /_0$/) {
                   12075: 				$unikey='parameter_0_'.$name;
                   12076: 				$part=0;
                   12077: 			    } else {
                   12078: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12079: 			    }
1.339     albertel 12080: 			    if ($subp eq 'display') {
                   12081: 				$value.=' [Part: '.$part.']';
                   12082: 			    }
1.599     albertel 12083: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12084: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12085: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12086: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12087: 			    }
1.599     albertel 12088: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12089: 				$metaentry{':'.$unikey}=
                   12090: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12091: 			    }
1.339     albertel 12092: 			}
                   12093: 		    }
                   12094: 		} else {
1.172     www      12095: #
                   12096: # This is not a package - some other kind of start tag
1.339     albertel 12097: #
                   12098: 		    my $entry=$token->[1];
1.1068    www      12099: 		    my $unikey='';
1.175     www      12100: 
1.339     albertel 12101: 		    if ($entry eq 'import') {
1.175     www      12102: #
                   12103: # Importing a library here
1.339     albertel 12104: #
1.1067    www      12105:                         my $location=$parser->get_text('/import');
                   12106:                         my $dir=$filename;
                   12107:                         $dir=~s|[^/]*$||;
                   12108:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12109: 
                   12110:                         my $importid=$token->[2]->{'id'};
1.1068    www      12111:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12112: #
                   12113: # Check metadata for imported file to
                   12114: # see if it contained response items
                   12115: #
                   12116:                         my %currmetaentry = %metaentry;
                   12117:                         my $libresponseorder = &metadata($location,'responseorder');
                   12118:                         my $origfile;
                   12119:                         if ($libresponseorder ne '') {
                   12120:                             if ($#origfiletagids<0) {
                   12121:                                 undef(%importedrespids);
                   12122:                                 undef(%importedpartids);
                   12123:                             }
                   12124:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12125:                             if (@{$importedrespids{$importid}} > 0) {
                   12126:                                 $importedresponses = 1;
                   12127: # We need to get the original file and the imported file to get the response order correct
                   12128: # Load and inspect original file
                   12129:                                 if ($#origfiletagids<0) {
                   12130:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12131:                                     $origfile=&getfile($origfilelocation);
                   12132:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12133:                                 }
                   12134:                             }
                   12135:                         }
                   12136: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12137: # hash populated for imported library file
                   12138:                         %metaentry = %currmetaentry;
                   12139:                         undef(%currmetaentry);
1.1068    www      12140:                         if ($importmode eq 'problem') {
1.1069    www      12141: # Import as problem/response
1.1068    www      12142:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12143:                         } elsif ($importmode eq 'part') {
                   12144: # Import as part(s)
1.1069    www      12145:                            $importedparts=1;
                   12146: # We need to get the original file and the imported file to get the part order correct
                   12147: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12148: # Load and inspect original file if we didn't do that already
                   12149:                            if ($#origfiletagids<0) {
                   12150:                                undef(%importedrespids);
                   12151:                                undef(%importedpartids);
                   12152:                                if ($origfile eq '') {
                   12153:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12154:                                    $origfile=&getfile($origfilelocation);
                   12155:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12156:                                }
1.1070    www      12157:                            }
                   12158: 
1.1069    www      12159: # Load and inspect imported file
                   12160:                            my $impfile=&getfile($location);
                   12161:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12162:                            if ($#impfilepartids>=0) {
                   12163: # This problem had parts
1.1070    www      12164:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12165:                            } else {
                   12166: # Importing by turning a single problem into a problem part
                   12167: # It gets the import-tags ID as part-ID
                   12168:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12169:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12170:                            }
1.1068    www      12171:                         } else {
                   12172: # Normal import
                   12173:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12174:                            if (defined($token->[2]->{'id'})) {
                   12175:                               $unikey.='_'.$token->[2]->{'id'};
                   12176:                            }
1.1067    www      12177:                         }
                   12178: 
1.339     albertel 12179: 			if ($depthcount<20) {
1.736     albertel 12180: 			    my $metadata = 
                   12181: 				&metadata($uri,'keys', $location,$unikey,
                   12182: 					  $depthcount+1);
                   12183: 			    foreach my $meta (split(',',$metadata)) {
                   12184: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12185: 				$metathesekeys{$meta}=1;
1.339     albertel 12186: 			    }
1.1068    www      12187: 			
                   12188:                         }
1.1067    www      12189: 		    } else {
                   12190: #
                   12191: # Not importing, some other kind of non-package, non-library start tag
                   12192: # 
                   12193:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12194:                         if (defined($token->[2]->{'id'})) {
                   12195:                             $unikey.='_'.$token->[2]->{'id'};
                   12196:                         }
1.339     albertel 12197: 			if (defined($token->[2]->{'name'})) { 
                   12198: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12199: 			}
                   12200: 			$metathesekeys{$unikey}=1;
1.736     albertel 12201: 			foreach my $param (@{$token->[3]}) {
                   12202: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12203: 				$token->[2]->{$param};
1.339     albertel 12204: 			}
                   12205: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12206: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12207: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12208: 		 # only ws inside the tag, and not in default, so use default
                   12209: 		 # as value
1.599     albertel 12210: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12211: 			} elsif ( $internaltext =~ /\S/ ) {
                   12212: 		  # something interesting inside the tag
                   12213: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12214: 			} else {
1.908     albertel 12215: 		  # no interesting values, don't set a default
1.339     albertel 12216: 			}
1.172     www      12217: # end of not-a-package not-a-library import
1.339     albertel 12218: 		    }
1.172     www      12219: # end of not-a-package start tag
1.339     albertel 12220: 		}
1.172     www      12221: # the next is the end of "start tag"
1.339     albertel 12222: 	    }
                   12223: 	}
1.483     albertel 12224: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12225: 	$extension = lc($extension);
                   12226: 	if ($extension eq 'htm') { $extension='html'; }
                   12227: 
1.737     albertel 12228: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12229: 	    #no specific packages #how's our extension
                   12230: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12231: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12232: 					 \%metathesekeys);
                   12233: 	}
1.883     albertel 12234: 
                   12235: 	if (!exists($metaentry{':packages'})
                   12236: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12237: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12238: 		#no specific packages well let's get default then
                   12239: 		if ($key!~/^default&/) { next; }
1.488     albertel 12240: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12241: 					     \%metathesekeys);
                   12242: 	    }
                   12243: 	}
1.338     www      12244: # are there custom rights to evaluate
1.599     albertel 12245: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12246: 
1.338     www      12247:     #
                   12248:     # Importing a rights file here
1.339     albertel 12249:     #
                   12250: 	    unless ($depthcount) {
1.599     albertel 12251: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12252: 		my $dir=$filename;
                   12253: 		$dir=~s|[^/]*$||;
                   12254: 		$location=&filelocation($dir,$location);
1.736     albertel 12255: 		my $rights_metadata =
                   12256: 		    &metadata($uri,'keys',$location,'_rights',
                   12257: 			      $depthcount+1);
                   12258: 		foreach my $rights (split(',',$rights_metadata)) {
                   12259: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12260: 		    $metathesekeys{$rights}=1;
1.339     albertel 12261: 		}
                   12262: 	    }
                   12263: 	}
1.737     albertel 12264: 	# uniqifiy package listing
                   12265: 	my %seen;
                   12266: 	my @uniq_packages =
                   12267: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12268: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12269: 
1.1172.2.99  raeburn  12270:         if (($importedresponses) || ($importedparts)) {
                   12271:             if ($importedparts) {
1.1070    www      12272: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12273:                 $metaentry{':partorder'}='';
                   12274:                 $metathesekeys{'partorder'}=1;
                   12275:             }
                   12276:             if ($importedresponses) {
                   12277: # We had imported responses and need to rebuild responseorder
                   12278:                 $metaentry{':responseorder'}='';
                   12279:                 $metathesekeys{'responseorder'}=1;
                   12280:             }
                   12281:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12282:                 my $origid = $origfiletagids[$index+1];
                   12283:                 if ($origfiletagids[$index] eq 'part') {
                   12284: # Original part, part of the problem
                   12285:                     if ($importedparts) {
                   12286:                         $metaentry{':partorder'}.=','.$origid;
                   12287:                     }
                   12288:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12289:                     if ($importedparts) {
                   12290: # We have imported parts at this position
                   12291:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12292:                     }
                   12293:                     if ($importedresponses) {
                   12294: # We have imported responses at this position
                   12295:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12296:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12297:                         }
                   12298:                     }
                   12299:                 } else {
                   12300: # Original response item, part of the problem
                   12301:                     if ($importedresponses) {
                   12302:                         $metaentry{':responseorder'}.=','.$origid;
                   12303:                     }
                   12304:                 }
                   12305:             }
                   12306:             if ($importedparts) {
                   12307:                 $metaentry{':partorder'}=~s/^\,//;
                   12308:             }
                   12309:             if ($importedresponses) {
                   12310:                 $metaentry{':responseorder'}=~s/^\,//;
                   12311:             }
1.1070    www      12312:         }
                   12313: 
1.737     albertel 12314: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12315: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12316: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12317: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12318: # this is the end of "was not already recently cached
1.71      www      12319:     }
1.599     albertel 12320:     return $metaentry{':'.$what};
1.261     albertel 12321: }
                   12322: 
1.488     albertel 12323: sub metadata_create_package_def {
1.483     albertel 12324:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12325:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12326:     if ($subp eq 'default') { next; }
                   12327:     
1.599     albertel 12328:     if (defined($metaentry{':packages'})) {
                   12329: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12330:     } else {
1.599     albertel 12331: 	$metaentry{':packages'}=$package;
1.483     albertel 12332:     }
                   12333:     my $value=$packagetab{$key};
                   12334:     my $unikey;
                   12335:     $unikey='parameter_0_'.$name;
1.599     albertel 12336:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12337:     $$metathesekeys{$unikey}=1;
1.599     albertel 12338:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12339: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12340:     }
1.599     albertel 12341:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12342: 	$metaentry{':'.$unikey}=
                   12343: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12344:     }
                   12345: }
                   12346: 
1.261     albertel 12347: sub metadata_generate_part0 {
                   12348:     my ($metadata,$metacache,$uri) = @_;
                   12349:     my %allnames;
1.737     albertel 12350:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12351: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12352: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12353: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12354: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12355: 	    $allnames{$name}=$part;
                   12356: 	  }
                   12357: 	}
                   12358:     }
                   12359:     foreach my $name (keys(%allnames)) {
                   12360:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12361:       my $key=":parameter_0_$name";
1.261     albertel 12362:       $$metacache{"$key.part"}='0';
                   12363:       $$metacache{"$key.name"}=$name;
1.428     albertel 12364:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12365: 					   $allnames{$name}.'_'.$name.
                   12366: 					   '.type'};
1.428     albertel 12367:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12368: 			     '.display'};
1.644     www      12369:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12370:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12371:       $$metacache{"$key.display"}=$olddis;
                   12372:     }
1.71      www      12373: }
                   12374: 
1.764     albertel 12375: # ------------------------------------------------------ Devalidate title cache
                   12376: 
                   12377: sub devalidate_title_cache {
                   12378:     my ($url)=@_;
                   12379:     if (!$env{'request.course.id'}) { return; }
                   12380:     my $symb=&symbread($url);
                   12381:     if (!$symb) { return; }
                   12382:     my $key=$env{'request.course.id'}."\0".$symb;
                   12383:     &devalidate_cache_new('title',$key);
                   12384: }
                   12385: 
1.1014    droeschl 12386: # ------------------------------------------------- Get the title of a course
                   12387: 
                   12388: sub current_course_title {
                   12389:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12390: }
1.301     www      12391: # ------------------------------------------------- Get the title of a resource
                   12392: 
                   12393: sub gettitle {
                   12394:     my $urlsymb=shift;
                   12395:     my $symb=&symbread($urlsymb);
1.534     albertel 12396:     if ($symb) {
1.620     albertel 12397: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12398: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12399: 	if (defined($cached)) { 
                   12400: 	    return $result;
                   12401: 	}
1.534     albertel 12402: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12403: 	my $title='';
1.907     albertel 12404: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12405: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12406: 	} else {
                   12407: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12408: 		    &GDBM_READER(),0640)) {
                   12409: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12410: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12411: 		untie(%bighash);
                   12412: 	    }
1.534     albertel 12413: 	}
                   12414: 	$title=~s/\&colon\;/\:/gs;
                   12415: 	if ($title) {
1.1159    www      12416: # Remember both $symb and $title for dynamic metadata
                   12417:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12418:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12419: # Cache this title and then return it
1.599     albertel 12420: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12421: 	}
                   12422: 	$urlsymb=$url;
                   12423:     }
                   12424:     my $title=&metadata($urlsymb,'title');
                   12425:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12426:     return $title;
1.301     www      12427: }
1.613     albertel 12428: 
1.614     albertel 12429: sub get_slot {
                   12430:     my ($which,$cnum,$cdom)=@_;
                   12431:     if (!$cnum || !$cdom) {
1.790     albertel 12432: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12433: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12434: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12435:     }
1.703     albertel 12436:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12437:     my %slotinfo;
                   12438:     if (exists($remembered{$key})) {
                   12439: 	$slotinfo{$which} = $remembered{$key};
                   12440:     } else {
                   12441: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12442: 	&Apache::lonhomework::showhash(%slotinfo);
                   12443: 	my ($tmp)=keys(%slotinfo);
                   12444: 	if ($tmp=~/^error:/) { return (); }
                   12445: 	$remembered{$key} = $slotinfo{$which};
                   12446:     }
1.616     albertel 12447:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12448: 	return %{$slotinfo{$which}};
                   12449:     }
                   12450:     return $slotinfo{$which};
1.614     albertel 12451: }
1.1150    raeburn  12452: 
                   12453: sub get_reservable_slots {
                   12454:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12455:     my $now = time;
                   12456:     my $reservable_info;
                   12457:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12458:     if (exists($remembered{$key})) {
                   12459:         $reservable_info = $remembered{$key};
                   12460:     } else {
                   12461:         my %resv;
                   12462:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12463:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12464:         $reservable_info = \%resv;
                   12465:         $remembered{$key} = $reservable_info;
                   12466:     }
                   12467:     return $reservable_info;
                   12468: }
                   12469: 
                   12470: sub get_course_slots {
                   12471:     my ($cnum,$cdom) = @_;
                   12472:     my $hashid=$cnum.':'.$cdom;
                   12473:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12474:     if (defined($cached)) {
                   12475:         if (ref($result) eq 'HASH') {
                   12476:             return %{$result};
                   12477:         }
                   12478:     } else {
                   12479:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12480:         my ($tmp) = keys(%slots);
                   12481:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12482:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12483:             return %slots;
                   12484:         }
                   12485:     }
                   12486:     return;
                   12487: }
                   12488: 
                   12489: sub devalidate_slots_cache {
                   12490:     my ($cnum,$cdom)=@_;
                   12491:     my $hashid=$cnum.':'.$cdom;
                   12492:     &devalidate_cache_new('allslots',$hashid);
                   12493: }
                   12494: 
1.1172.2.8  raeburn  12495: sub get_coursechange {
                   12496:     my ($cdom,$cnum) = @_;
                   12497:     if ($cdom eq '' || $cnum eq '') {
                   12498:         return unless ($env{'request.course.id'});
                   12499:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12500:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12501:     }
                   12502:     my $hashid=$cdom.'_'.$cnum;
                   12503:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12504:     if ((defined($cached)) && ($change ne '')) {
                   12505:         return $change;
                   12506:     } else {
                   12507:         my %crshash;
                   12508:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12509:         if ($crshash{'internal.contentchange'} eq '') {
                   12510:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12511:             if ($change eq '') {
                   12512:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12513:                 $change = $crshash{'internal.created'};
                   12514:             }
                   12515:         } else {
                   12516:             $change = $crshash{'internal.contentchange'};
                   12517:         }
                   12518:         my $cachetime = 600;
                   12519:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12520:     }
                   12521:     return $change;
                   12522: }
                   12523: 
                   12524: sub devalidate_coursechange_cache {
                   12525:     my ($cnum,$cdom)=@_;
                   12526:     my $hashid=$cnum.':'.$cdom;
                   12527:     &devalidate_cache_new('crschange',$hashid);
                   12528: }
                   12529: 
1.31      www      12530: # ------------------------------------------------- Update symbolic store links
                   12531: 
                   12532: sub symblist {
                   12533:     my ($mapname,%newhash)=@_;
1.438     www      12534:     $mapname=&deversion(&declutter($mapname));
1.31      www      12535:     my %hash;
1.620     albertel 12536:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12537:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12538:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12539: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12540: 		next if ($url eq 'last_known'
                   12541: 			 && $env{'form.no_update_last_known'});
                   12542: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12543: 						    $newhash{$url}->[1],
                   12544: 						    $newhash{$url}->[0]);
1.191     harris41 12545:             }
1.31      www      12546:             if (untie(%hash)) {
                   12547: 		return 'ok';
                   12548:             }
                   12549:         }
                   12550:     }
                   12551:     return 'error';
1.212     www      12552: }
                   12553: 
                   12554: # --------------------------------------------------------------- Verify a symb
                   12555: 
                   12556: sub symbverify {
1.1172.2.11  raeburn  12557:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12558:     my $thisfn=$thisurl;
1.439     www      12559:     $thisfn=&declutter($thisfn);
1.215     www      12560: # direct jump to resource in page or to a sequence - will construct own symbs
                   12561:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12562: # check URL part
1.409     www      12563:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12564: 
1.431     www      12565:     unless ($url eq $thisfn) { return 0; }
1.213     www      12566: 
1.216     www      12567:     $symb=&symbclean($symb);
1.510     www      12568:     $thisurl=&deversion($thisurl);
1.439     www      12569:     $thisfn=&deversion($thisfn);
1.213     www      12570: 
                   12571:     my %bighash;
                   12572:     my $okay=0;
1.431     www      12573: 
1.620     albertel 12574:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12575:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12576:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12577:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12578:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12579:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12580:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12581:             }
                   12582:         }
                   12583:         my $ids;
1.1172.2.118.  .5(raebu 12584:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12585:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12586:         } else {
                   12587:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12588:         }
1.1102    raeburn  12589:         unless ($ids) {
1.1172.2.13  raeburn  12590:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12591:             $ids=$bighash{$idkey};
1.216     www      12592:         }
                   12593:         if ($ids) {
                   12594: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12595:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12596:                 $symb =~ s/\?.+$//;
                   12597:             }
1.800     albertel 12598: 	    foreach my $id (split(/\,/,$ids)) {
                   12599: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12600:                if (
                   12601:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12602:    eq $symb) {
1.1172.2.11  raeburn  12603:                    if (ref($encstate)) {
                   12604:                        $$encstate = $bighash{'encrypted_'.$id};
                   12605:                    }
1.1172.2.13  raeburn  12606:                    if (($env{'request.role.adv'}) ||
                   12607:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12608:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12609:                        $okay=1;
                   12610:                        last;
                   12611:                    }
                   12612:                }
                   12613:            }
1.216     www      12614:         }
1.213     www      12615: 	untie(%bighash);
                   12616:     }
                   12617:     return $okay;
1.31      www      12618: }
                   12619: 
1.210     www      12620: # --------------------------------------------------------------- Clean-up symb
                   12621: 
                   12622: sub symbclean {
                   12623:     my $symb=shift;
1.568     albertel 12624:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12625: # remove version from map
                   12626:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12627: 
1.210     www      12628: # remove version from URL
                   12629:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12630: 
1.507     www      12631: # remove wrapper
                   12632: 
1.510     www      12633:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12634:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12635:     return $symb;
1.409     www      12636: }
                   12637: 
                   12638: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12639: 
                   12640: sub encode_symb {
                   12641:     my ($map,$resid,$url)=@_;
                   12642:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12643: }
1.409     www      12644: 
                   12645: sub decode_symb {
1.568     albertel 12646:     my $symb=shift;
                   12647:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12648:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12649:     return (&fixversion($map),$resid,&fixversion($url));
                   12650: }
                   12651: 
                   12652: sub fixversion {
                   12653:     my $fn=shift;
1.609     banghart 12654:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12655:     my %bighash;
                   12656:     my $uri=&clutter($fn);
1.620     albertel 12657:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12658: # is this cached?
1.599     albertel 12659:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12660:     if (defined($cached)) { return $result; }
                   12661: # unfortunately not cached, or expired
1.620     albertel 12662:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12663: 	    &GDBM_READER(),0640)) {
                   12664:  	if ($bighash{'version_'.$uri}) {
                   12665:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12666:  	    unless (($version eq 'mostrecent') || 
                   12667: 		    ($version==&getversion($uri))) {
1.440     www      12668:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12669:  	    }
                   12670:  	}
                   12671:  	untie %bighash;
1.413     www      12672:     }
1.599     albertel 12673:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12674: }
                   12675: 
                   12676: sub deversion {
                   12677:     my $url=shift;
                   12678:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12679:     return $url;
1.210     www      12680: }
                   12681: 
1.31      www      12682: # ------------------------------------------------------ Return symb list entry
                   12683: 
                   12684: sub symbread {
1.1172.2.118.  .8(raebu 12685:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12686:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12687:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12688:20):     if (defined($env{$cache_str})) {
          .8(raebu 12689:20):         unless (ref($possibles) eq 'HASH') {
                   12690:20):             if ($ignorecachednull) {
                   12691:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12692:20):             } else {
                   12693:20):                 return $env{$cache_str};
                   12694:20):             }
1.1172.2.66  raeburn  12695:         }
                   12696:     }
1.242     www      12697: # no filename provided? try from environment
1.1172.2.54  raeburn  12698:     unless ($thisfn) {
1.620     albertel 12699:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12700:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12701:         }
                   12702:         $thisfn=$env{'request.filename'};
1.44      www      12703:     }
1.569     albertel 12704:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12705: # is that filename actually a symb? Verify, clean, and return
                   12706:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12707: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12708:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12709: 	}
1.242     www      12710:     }
1.44      www      12711:     $thisfn=declutter($thisfn);
1.31      www      12712:     my %hash;
1.37      www      12713:     my %bighash;
                   12714:     my $syval='';
1.620     albertel 12715:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12716:         my $targetfn = $thisfn;
1.609     banghart 12717:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12718:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12719:         }
1.687     albertel 12720: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12721: 	    $targetfn=$1;
                   12722: 	}
1.1172.2.118.  .9(raebu 12723:20):         unless ($ignoresymbdb) {
          .8(raebu 12724:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12725:20):                           &GDBM_READER(),0640)) {
                   12726:20): 	        $syval=$hash{$targetfn};
                   12727:20):                 untie(%hash);
                   12728:20):             }
          .9(raebu 12729:20):             if ($syval && $checkforblock) {
                   12730:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12731:20):                 if (@blockers) {
                   12732:20):                     $syval='';
                   12733:20):                 }
                   12734:20):             }
1.37      www      12735:         }
                   12736: # ---------------------------------------------------------- There was an entry
                   12737:         if ($syval) {
1.601     albertel 12738: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12739: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12740: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12741: 		    #return $env{$cache_str}='';
1.601     albertel 12742: 		#}    
                   12743: 		#$syval.=$1;
                   12744: 	    #}
1.37      www      12745:         } else {
                   12746: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12747:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12748:                             &GDBM_READER(),0640)) {
1.37      www      12749: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12750:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12751:               unless ($ids) { 
                   12752:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12753:               }
                   12754:               unless ($ids) {
                   12755: # alias?
                   12756: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12757:               }
1.37      www      12758:               if ($ids) {
                   12759: # ------------------------------------------------------------------- Has ID(s)
                   12760:                  my @possibilities=split(/\,/,$ids);
1.39      www      12761:                  if ($#possibilities==0) {
                   12762: # ----------------------------------------------- There is only one possibility
1.37      www      12763: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12764: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12765: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12766:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12767:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12768:20):                              $possibles->{$syval} = 1;
                   12769:20):                          }
1.1172.2.66  raeburn  12770:                      }
                   12771:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12772:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12773:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12774:20):                              if (@blockers) {
                   12775:20):                                  $syval = '';
                   12776:20):                                  untie(%bighash);
                   12777:20):                                  return $env{$cache_str}='';
                   12778:20):                              }
1.1172.2.66  raeburn  12779:                          }
                   12780:                      }
                   12781:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12782: # ------------------------------------------ There is more than one possibility
                   12783:                      my $realpossible=0;
1.800     albertel 12784:                      foreach my $id (@possibilities) {
                   12785: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12786:                          my $canaccess;
                   12787:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12788:                              $canaccess = 1;
                   12789:                          } else {
                   12790:                              $canaccess = &allowed('bre',$file);
                   12791:                          }
                   12792:                          if ($canaccess) {
                   12793:          		     my ($mapid,$resid)=split(/\./,$id);
                   12794:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12795:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12796:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12797:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12798:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12799:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12800:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12801:20):                                      if (@blockers > 0) {
                   12802:20):                                          $syval = '';
                   12803:20):                                      } else {
1.1172.2.66  raeburn  12804:                                          $syval = $poss_syval;
                   12805:                                          $realpossible++;
                   12806:                                      }
                   12807:                                  } else {
                   12808:                                      $syval = $poss_syval;
                   12809:                                      $realpossible++;
                   12810:                                  }
1.1172.2.118.  .8(raebu 12811:20):                                  if ($syval) {
                   12812:20):                                      if (ref($possibles) eq 'HASH') {
                   12813:20):                                          $possibles->{$syval} = 1;
                   12814:20):                                      }
                   12815:20):                                  }
1.1172.2.66  raeburn  12816:                              }
1.39      www      12817: 			 }
1.191     harris41 12818:                      }
1.39      www      12819: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12820:                  } else {
                   12821:                      $syval='';
1.37      www      12822:                  }
                   12823: 	      }
1.1172.2.66  raeburn  12824:               untie(%bighash);
1.481     raeburn  12825:            }
1.31      www      12826:         }
1.62      www      12827:         if ($syval) {
1.1172.2.118.  .9(raebu 12828:20): 	    return $env{$cache_str}=$syval;
1.62      www      12829:         }
1.31      www      12830:     }
1.949     raeburn  12831:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12832:     return $env{$cache_str}='';
1.31      www      12833: }
                   12834: 
                   12835: # ---------------------------------------------------------- Return random seed
                   12836: 
1.32      www      12837: sub numval {
                   12838:     my $txt=shift;
                   12839:     $txt=~tr/A-J/0-9/;
                   12840:     $txt=~tr/a-j/0-9/;
                   12841:     $txt=~tr/K-T/0-9/;
                   12842:     $txt=~tr/k-t/0-9/;
                   12843:     $txt=~tr/U-Z/0-5/;
                   12844:     $txt=~tr/u-z/0-5/;
                   12845:     $txt=~s/\D//g;
1.564     albertel 12846:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12847:     return int($txt);
1.368     albertel 12848: }
                   12849: 
1.484     albertel 12850: sub numval2 {
                   12851:     my $txt=shift;
                   12852:     $txt=~tr/A-J/0-9/;
                   12853:     $txt=~tr/a-j/0-9/;
                   12854:     $txt=~tr/K-T/0-9/;
                   12855:     $txt=~tr/k-t/0-9/;
                   12856:     $txt=~tr/U-Z/0-5/;
                   12857:     $txt=~tr/u-z/0-5/;
                   12858:     $txt=~s/\D//g;
                   12859:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12860:     my $total;
                   12861:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12862:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12863:     return int($total);
                   12864: }
                   12865: 
1.575     albertel 12866: sub numval3 {
                   12867:     use integer;
                   12868:     my $txt=shift;
                   12869:     $txt=~tr/A-J/0-9/;
                   12870:     $txt=~tr/a-j/0-9/;
                   12871:     $txt=~tr/K-T/0-9/;
                   12872:     $txt=~tr/k-t/0-9/;
                   12873:     $txt=~tr/U-Z/0-5/;
                   12874:     $txt=~tr/u-z/0-5/;
                   12875:     $txt=~s/\D//g;
                   12876:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12877:     my $total;
                   12878:     foreach my $val (@txts) { $total+=$val; }
                   12879:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12880:     return $total;
                   12881: }
                   12882: 
1.675     albertel 12883: sub digest {
                   12884:     my ($data)=@_;
                   12885:     my $digest=&Digest::MD5::md5($data);
                   12886:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12887:     my ($e,$f);
                   12888:     {
                   12889:         use integer;
                   12890:         $e=($a+$b);
                   12891:         $f=($c+$d);
                   12892:         if ($_64bit) {
                   12893:             $e=(($e<<32)>>32);
                   12894:             $f=(($f<<32)>>32);
                   12895:         }
                   12896:     }
                   12897:     if (wantarray) {
                   12898: 	return ($e,$f);
                   12899:     } else {
                   12900: 	my $g;
                   12901: 	{
                   12902: 	    use integer;
                   12903: 	    $g=($e+$f);
                   12904: 	    if ($_64bit) {
                   12905: 		$g=(($g<<32)>>32);
                   12906: 	    }
                   12907: 	}
                   12908: 	return $g;
                   12909:     }
                   12910: }
                   12911: 
1.368     albertel 12912: sub latest_rnd_algorithm_id {
1.675     albertel 12913:     return '64bit5';
1.366     albertel 12914: }
1.32      www      12915: 
1.503     albertel 12916: sub get_rand_alg {
                   12917:     my ($courseid)=@_;
1.790     albertel 12918:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12919:     if ($courseid) {
1.620     albertel 12920: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12921:     }
                   12922:     return &latest_rnd_algorithm_id();
                   12923: }
                   12924: 
1.562     albertel 12925: sub validCODE {
                   12926:     my ($CODE)=@_;
                   12927:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12928:     return 0;
                   12929: }
                   12930: 
1.491     albertel 12931: sub getCODE {
1.620     albertel 12932:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12933:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12934: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12935: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12936: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12937:     }
                   12938:     return undef;
                   12939: }
1.1133    foxr     12940: #
                   12941: #  Determines the random seed for a specific context:
                   12942: #
                   12943: # parameters:
                   12944: #   symb      - in course context the symb for the seed.
                   12945: #   course_id - The course id of the form domain_coursenum.
                   12946: #   domain    - Domain for the user.
                   12947: #   course    - Course for the user.
                   12948: #   cenv      - environment of the course.
                   12949: #
                   12950: # NOTE:
                   12951: #   All parameters are picked out of the environment if missing
                   12952: #   or not defined.
                   12953: #   If a symb cannot be determined the current time is used instead.
                   12954: #
                   12955: #  For a given well defined symb, courside, domain, username,
                   12956: #  and course environment, the seed is reproducible.
                   12957: #
1.31      www      12958: sub rndseed {
1.1133    foxr     12959:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12960:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12961:     if (!defined($symb)) {
1.366     albertel 12962: 	unless ($symb=$wsymb) { return time; }
                   12963:     }
1.1146    foxr     12964:     if (!defined $courseid) { 
                   12965: 	$courseid=$wcourseid; 
                   12966:     }
                   12967:     if (!defined $domain) { $domain=$wdomain; }
                   12968:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12969: 
                   12970:     my $which;
                   12971:     if (defined($cenv->{'rndseed'})) {
                   12972: 	$which = $cenv->{'rndseed'};
                   12973:     } else {
                   12974: 	$which =&get_rand_alg($courseid);
                   12975:     }
1.491     albertel 12976:     if (defined(&getCODE())) {
1.675     albertel 12977: 	if ($which eq '64bit5') {
                   12978: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12979: 	} elsif ($which eq '64bit4') {
1.575     albertel 12980: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12981: 	} else {
                   12982: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12983: 	}
1.675     albertel 12984:     } elsif ($which eq '64bit5') {
                   12985: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12986:     } elsif ($which eq '64bit4') {
                   12987: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12988:     } elsif ($which eq '64bit3') {
                   12989: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12990:     } elsif ($which eq '64bit2') {
                   12991: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12992:     } elsif ($which eq '64bit') {
                   12993: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12994:     }
                   12995:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12996: }
                   12997: 
                   12998: sub rndseed_32bit {
                   12999:     my ($symb,$courseid,$domain,$username)=@_;
                   13000:     {
                   13001: 	use integer;
                   13002: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13003: 	my $symbseed=numval($symb) << 22;
                   13004: 	my $namechck=unpack("%32C*",$username) << 17;
                   13005: 	my $nameseed=numval($username) << 12;
                   13006: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13007: 	my $courseseed=unpack("%32C*",$courseid);
                   13008: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13009: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13010: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13011: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13012: 	return $num;
                   13013:     }
                   13014: }
                   13015: 
                   13016: sub rndseed_64bit {
                   13017:     my ($symb,$courseid,$domain,$username)=@_;
                   13018:     {
                   13019: 	use integer;
                   13020: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13021: 	my $symbseed=numval($symb) << 10;
                   13022: 	my $namechck=unpack("%32S*",$username);
                   13023: 	
                   13024: 	my $nameseed=numval($username) << 21;
                   13025: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13026: 	my $courseseed=unpack("%32S*",$courseid);
                   13027: 	
                   13028: 	my $num1=$symbchck+$symbseed+$namechck;
                   13029: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13031: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13032: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13033: 	return "$num1,$num2";
1.155     albertel 13034:     }
1.366     albertel 13035: }
                   13036: 
1.443     albertel 13037: sub rndseed_64bit2 {
                   13038:     my ($symb,$courseid,$domain,$username)=@_;
                   13039:     {
                   13040: 	use integer;
                   13041: 	# strings need to be an even # of cahracters long, it it is odd the
                   13042:         # last characters gets thrown away
                   13043: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13044: 	my $symbseed=numval($symb) << 10;
                   13045: 	my $namechck=unpack("%32S*",$username.' ');
                   13046: 	
                   13047: 	my $nameseed=numval($username) << 21;
1.501     albertel 13048: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13049: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13050: 	
                   13051: 	my $num1=$symbchck+$symbseed+$namechck;
                   13052: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13053: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13054: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13055: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13056: 	return "$num1,$num2";
                   13057:     }
                   13058: }
                   13059: 
                   13060: sub rndseed_64bit3 {
                   13061:     my ($symb,$courseid,$domain,$username)=@_;
                   13062:     {
                   13063: 	use integer;
                   13064: 	# strings need to be an even # of cahracters long, it it is odd the
                   13065:         # last characters gets thrown away
                   13066: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13067: 	my $symbseed=numval2($symb) << 10;
                   13068: 	my $namechck=unpack("%32S*",$username.' ');
                   13069: 	
                   13070: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13071: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13072: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13073: 	
                   13074: 	my $num1=$symbchck+$symbseed+$namechck;
                   13075: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13077: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13078: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13079: 	
1.503     albertel 13080: 	return "$num1:$num2";
1.443     albertel 13081:     }
                   13082: }
                   13083: 
1.575     albertel 13084: sub rndseed_64bit4 {
                   13085:     my ($symb,$courseid,$domain,$username)=@_;
                   13086:     {
                   13087: 	use integer;
                   13088: 	# strings need to be an even # of cahracters long, it it is odd the
                   13089:         # last characters gets thrown away
                   13090: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13091: 	my $symbseed=numval3($symb) << 10;
                   13092: 	my $namechck=unpack("%32S*",$username.' ');
                   13093: 	
                   13094: 	my $nameseed=numval3($username) << 21;
                   13095: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13096: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13097: 	
                   13098: 	my $num1=$symbchck+$symbseed+$namechck;
                   13099: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13101: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13103: 	
1.575     albertel 13104: 	return "$num1:$num2";
                   13105:     }
                   13106: }
                   13107: 
1.675     albertel 13108: sub rndseed_64bit5 {
                   13109:     my ($symb,$courseid,$domain,$username)=@_;
                   13110:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13111:     return "$num1:$num2";
                   13112: }
                   13113: 
1.366     albertel 13114: sub rndseed_CODE_64bit {
                   13115:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13116:     {
1.366     albertel 13117: 	use integer;
1.443     albertel 13118: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13119: 	my $symbseed=numval2($symb);
1.491     albertel 13120: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13121: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13122: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13123: 	my $num1=$symbseed+$CODEchck;
                   13124: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13125: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13126: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13127: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13128: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13129: 	return "$num1:$num2";
1.366     albertel 13130:     }
                   13131: }
                   13132: 
1.575     albertel 13133: sub rndseed_CODE_64bit4 {
                   13134:     my ($symb,$courseid,$domain,$username)=@_;
                   13135:     {
                   13136: 	use integer;
                   13137: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13138: 	my $symbseed=numval3($symb);
                   13139: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13140: 	my $CODEseed=numval3(&getCODE());
                   13141: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13142: 	my $num1=$symbseed+$CODEchck;
                   13143: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13144: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13145: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13146: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13147: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13148: 	return "$num1:$num2";
                   13149:     }
                   13150: }
                   13151: 
1.675     albertel 13152: sub rndseed_CODE_64bit5 {
                   13153:     my ($symb,$courseid,$domain,$username)=@_;
                   13154:     my $code = &getCODE();
                   13155:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13156:     return "$num1:$num2";
                   13157: }
                   13158: 
1.366     albertel 13159: sub setup_random_from_rndseed {
                   13160:     my ($rndseed)=@_;
1.503     albertel 13161:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13162: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13163:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13164:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13165:         } else {
                   13166:             &Math::Random::random_set_seed($num1,$num2);
                   13167:         }
1.366     albertel 13168:     } else {
                   13169: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13170:     }
1.36      albertel 13171: }
                   13172: 
1.474     albertel 13173: sub latest_receipt_algorithm_id {
1.835     albertel 13174:     return 'receipt3';
1.474     albertel 13175: }
                   13176: 
1.480     www      13177: sub recunique {
                   13178:     my $fucourseid=shift;
                   13179:     my $unique;
1.835     albertel 13180:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13181: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13182: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13183:     } else {
                   13184: 	$unique=$perlvar{'lonReceipt'};
                   13185:     }
                   13186:     return unpack("%32C*",$unique);
                   13187: }
                   13188: 
                   13189: sub recprefix {
                   13190:     my $fucourseid=shift;
                   13191:     my $prefix;
1.835     albertel 13192:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13193: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13194: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13195:     } else {
                   13196: 	$prefix=$perlvar{'lonHostID'};
                   13197:     }
                   13198:     return unpack("%32C*",$prefix);
                   13199: }
                   13200: 
1.76      www      13201: sub ireceipt {
1.474     albertel 13202:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13203: 
                   13204:     my $return =&recprefix($fucourseid).'-';
                   13205: 
                   13206:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13207: 	$env{'request.state'} eq 'construct') {
                   13208: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13209: 	return $return;
                   13210:     }
                   13211: 
1.76      www      13212:     my $cuname=unpack("%32C*",$funame);
                   13213:     my $cudom=unpack("%32C*",$fudom);
                   13214:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13215:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13216:     my $cunique=&recunique($fucourseid);
1.474     albertel 13217:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13218:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13219: 
1.790     albertel 13220: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13221: 			       
                   13222: 	$return.= ($cunique%$cuname+
                   13223: 		   $cunique%$cudom+
                   13224: 		   $cusymb%$cuname+
                   13225: 		   $cusymb%$cudom+
                   13226: 		   $cucourseid%$cuname+
                   13227: 		   $cucourseid%$cudom+
                   13228: 		   $cpart%$cuname+
                   13229: 		   $cpart%$cudom);
                   13230:     } else {
                   13231: 	$return.= ($cunique%$cuname+
                   13232: 		   $cunique%$cudom+
                   13233: 		   $cusymb%$cuname+
                   13234: 		   $cusymb%$cudom+
                   13235: 		   $cucourseid%$cuname+
                   13236: 		   $cucourseid%$cudom);
                   13237:     }
                   13238:     return $return;
1.76      www      13239: }
                   13240: 
                   13241: sub receipt {
1.474     albertel 13242:     my ($part)=@_;
1.790     albertel 13243:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13244:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13245: }
1.260     ng       13246: 
1.790     albertel 13247: sub whichuser {
                   13248:     my ($passedsymb)=@_;
                   13249:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13250:     if (defined($env{'form.grade_symb'})) {
                   13251: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13252: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13253: 	if (!$allowed &&
                   13254: 	    exists($env{'request.course.sec'}) &&
                   13255: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13256: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13257: 			      '/'.$env{'request.course.sec'});
                   13258: 	}
                   13259: 	if ($allowed) {
                   13260: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13261: 	    $courseid=$tmp_courseid;
                   13262: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13263: 	    ($name)=&get_env_multiple('form.grade_username');
                   13264: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13265: 	}
                   13266:     }
                   13267:     if (!$passedsymb) {
                   13268: 	$symb=&symbread();
                   13269:     } else {
                   13270: 	$symb=$passedsymb;
                   13271:     }
                   13272:     $courseid=$env{'request.course.id'};
                   13273:     $domain=$env{'user.domain'};
                   13274:     $name=$env{'user.name'};
                   13275:     if ($name eq 'public' && $domain eq 'public') {
                   13276: 	if (!defined($env{'form.username'})) {
                   13277: 	    $env{'form.username'}.=time.rand(10000000);
                   13278: 	}
                   13279: 	$name.=$env{'form.username'};
                   13280:     }
                   13281:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13282: 
                   13283: }
                   13284: 
1.36      albertel 13285: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13286: # returns either the contents of the file or 
                   13287: # -1 if the file doesn't exist
1.481     raeburn  13288: #
                   13289: # if the target is a file that was uploaded via DOCS, 
                   13290: # a check will be made to see if a current copy exists on the local server,
                   13291: # if it does this will be served, otherwise a copy will be retrieved from
                   13292: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13293: # the local server.   
1.472     albertel 13294: 
1.36      albertel 13295: sub getfile {
1.538     albertel 13296:     my ($file) = @_;
1.609     banghart 13297:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13298:     &repcopy($file);
                   13299:     return &readfile($file);
                   13300: }
                   13301: 
                   13302: sub repcopy_userfile {
                   13303:     my ($file)=@_;
1.1142    raeburn  13304:     my $londocroot = $perlvar{'lonDocRoot'};
                   13305:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13306:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13307:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13308: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13309:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13310:     if (-e "$file") {
1.828     www      13311: # we already have a local copy, check it out
1.538     albertel 13312: 	my @fileinfo = stat($file);
1.828     www      13313: 	my $rtncode;
                   13314: 	my $info;
1.538     albertel 13315: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13316: 	if ($lwpresp ne 'ok') {
1.828     www      13317: # there is no such file anymore, even though we had a local copy
1.482     albertel 13318: 	    if ($rtncode eq '404') {
1.538     albertel 13319: 		unlink($file);
1.482     albertel 13320: 	    }
                   13321: 	    return -1;
                   13322: 	}
                   13323: 	if ($info < $fileinfo[9]) {
1.828     www      13324: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13325: 	    return 'ok';
1.828     www      13326: 	} else {
                   13327: # the file is outdated, get rid of it
                   13328: 	    unlink($file);
1.482     albertel 13329: 	}
1.828     www      13330:     }
                   13331: # one way or the other, at this point, we don't have the file
                   13332: # construct the correct path for the file
                   13333:     my @parts = ($cdom,$cnum); 
                   13334:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13335: 	push @parts, split(/\//,$1);
                   13336:     }
                   13337:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13338:     foreach my $part (@parts) {
                   13339: 	$path .= '/'.$part;
                   13340: 	if (!-e $path) {
                   13341: 	    mkdir($path,0770);
1.482     albertel 13342: 	}
                   13343:     }
1.828     www      13344: # now the path exists for sure
                   13345: # get a user agent
                   13346:     my $ua=new LWP::UserAgent;
                   13347:     my $transferfile=$file.'.in.transfer';
                   13348: # FIXME: this should flock
                   13349:     if (-e $transferfile) { return 'ok'; }
                   13350:     my $request;
                   13351:     $uri=~s/^\///;
1.980     raeburn  13352:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13353:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13354:     my $protocol = $protocol{$homeserver};
                   13355:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13356:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13357:     my $response=$ua->request($request,$transferfile);
                   13358: # did it work?
                   13359:     if ($response->is_error()) {
                   13360: 	unlink($transferfile);
                   13361: 	&logthis("Userfile repcopy failed for $uri");
                   13362: 	return -1;
                   13363:     }
                   13364: # worked, rename the transfer file
                   13365:     rename($transferfile,$file);
1.607     raeburn  13366:     return 'ok';
1.481     raeburn  13367: }
                   13368: 
1.517     albertel 13369: sub tokenwrapper {
                   13370:     my $uri=shift;
1.980     raeburn  13371:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13372:     $uri=~s|^/||;
1.620     albertel 13373:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13374:     my $token=$1;
1.552     albertel 13375:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13376:     if ($udom && $uname && $file) {
                   13377: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13378:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13379:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13380:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13381:         my $protocol = $protocol{$homeserver};
                   13382:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13383:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13384:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13385:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13386:     } else {
                   13387:         return '/adm/notfound.html';
                   13388:     }
                   13389: }
                   13390: 
1.828     www      13391: # call with reqtype HEAD: get last modification time
                   13392: # call with reqtype GET: get the file contents
                   13393: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13394: #
1.481     raeburn  13395: sub getuploaded {
                   13396:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13397:     $uri=~s/^\///;
1.980     raeburn  13398:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13399:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13400:     my $protocol = $protocol{$homeserver};
                   13401:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13402:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13403:     my $ua=new LWP::UserAgent;
                   13404:     my $request=new HTTP::Request($reqtype,$uri);
                   13405:     my $response=$ua->request($request);
                   13406:     $$rtncode = $response->code;
1.482     albertel 13407:     if (! $response->is_success()) {
                   13408: 	return 'failed';
                   13409:     }      
                   13410:     if ($reqtype eq 'HEAD') {
1.486     www      13411: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13412:     } elsif ($reqtype eq 'GET') {
                   13413: 	$$info = $response->content;
1.472     albertel 13414:     }
1.482     albertel 13415:     return 'ok';
1.36      albertel 13416: }
                   13417: 
1.481     raeburn  13418: sub readfile {
                   13419:     my $file = shift;
                   13420:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13421:     my $fh;
1.1172.2.96  raeburn  13422:     open($fh,"<",$file);
1.481     raeburn  13423:     my $a='';
1.800     albertel 13424:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13425:     return $a;
                   13426: }
                   13427: 
1.36      albertel 13428: sub filelocation {
1.590     banghart 13429:     my ($dir,$file) = @_;
                   13430:     my $location;
                   13431:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13432: 
                   13433:     if ($file =~ m-^/adm/-) {
                   13434: 	$file=~s-^/adm/wrapper/-/-;
                   13435: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13436:     }
1.882     albertel 13437: 
1.1139    www      13438:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13439:         $location = $file;
1.609     banghart 13440:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13441:         my ($udom,$uname,$filename)=
1.811     albertel 13442:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13443:         my $home=&homeserver($uname,$udom);
                   13444:         my $is_me=0;
                   13445:         my @ids=&current_machine_ids();
                   13446:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13447:         if ($is_me) {
1.1117    foxr     13448:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13449:         } else {
                   13450:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13451:   	      $udom.'/'.$uname.'/'.$filename;
                   13452:         }
1.882     albertel 13453:     } elsif ($file =~ m-^/adm/-) {
                   13454: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13455:     } else {
                   13456:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13457:         $file=~s:^/(res|priv)/:/:;
                   13458:         my $space=$1;
1.590     banghart 13459:         if ( !( $file =~ m:^/:) ) {
                   13460:             $location = $dir. '/'.$file;
                   13461:         } else {
1.1142    raeburn  13462:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13463:         }
1.59      albertel 13464:     }
1.590     banghart 13465:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13466:     while ($location=~m{/\.\./}) {
                   13467: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13468: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13469: 	} else {
                   13470: 	    $location=~ s{/\.\./}{/}g;
                   13471: 	}
                   13472:     } #remove dir/..
1.590     banghart 13473:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13474:     return $location;
1.46      www      13475: }
1.36      albertel 13476: 
1.46      www      13477: sub hreflocation {
                   13478:     my ($dir,$file)=@_;
1.980     raeburn  13479:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13480: 	$file=filelocation($dir,$file);
1.700     albertel 13481:     } elsif ($file=~m-^/adm/-) {
                   13482: 	$file=~s-^/adm/wrapper/-/-;
                   13483: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13484:     }
                   13485:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13486: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13487:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13488: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13489: 	        {/uploaded/$1/$2/}x;
1.46      www      13490:     }
1.913     albertel 13491:     if ($file=~ m{^/userfiles/}) {
                   13492: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13493:     }
1.462     albertel 13494:     return $file;
1.465     albertel 13495: }
                   13496: 
1.1139    www      13497: 
                   13498: 
                   13499: 
                   13500: 
1.465     albertel 13501: sub current_machine_domains {
1.853     albertel 13502:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13503: }
                   13504: 
                   13505: sub machine_domains {
                   13506:     my ($hostname) = @_;
1.465     albertel 13507:     my @domains;
1.838     albertel 13508:     my %hostname = &all_hostnames();
1.465     albertel 13509:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13510: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13511: 	if ($hostname eq $name) {
1.844     albertel 13512: 	    push(@domains,&host_domain($id));
1.465     albertel 13513: 	}
                   13514:     }
                   13515:     return @domains;
                   13516: }
                   13517: 
                   13518: sub current_machine_ids {
1.853     albertel 13519:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13520: }
                   13521: 
                   13522: sub machine_ids {
                   13523:     my ($hostname) = @_;
                   13524:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13525:     my @ids;
1.888     albertel 13526:     my %name_to_host = &all_names();
1.889     albertel 13527:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13528: 	return @{ $name_to_host{$hostname} };
                   13529:     }
                   13530:     return;
1.31      www      13531: }
                   13532: 
1.824     raeburn  13533: sub additional_machine_domains {
                   13534:     my @domains;
1.1172.2.96  raeburn  13535:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13536:     while( my $line = <$fh>) {
                   13537:         $line =~ s/\s//g;
                   13538:         push(@domains,$line);
                   13539:     }
                   13540:     return @domains;
                   13541: }
                   13542: 
                   13543: sub default_login_domain {
                   13544:     my $domain = $perlvar{'lonDefDomain'};
                   13545:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13546:     foreach my $posdom (&current_machine_domains(),
                   13547:                         &additional_machine_domains()) {
                   13548:         if (lc($posdom) eq lc($testdomain)) {
                   13549:             $domain=$posdom;
                   13550:             last;
                   13551:         }
                   13552:     }
                   13553:     return $domain;
                   13554: }
                   13555: 
1.1172.2.106  raeburn  13556: sub shared_institution {
1.1172.2.118.  .15(raeb 13557:-21):     my ($dom,$lonhost) = @_;
                   13558:-21):     if ($lonhost eq '') {
                   13559:-21):         $lonhost = $perlvar{'lonHostID'};
                   13560:-21):     }
1.1172.2.106  raeburn  13561:     my $same_intdom;
1.1172.2.118.  .15(raeb 13562:-21):     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13563:     if ($hostintdom ne '') {
                   13564:         my %iphost = &get_iphost();
                   13565:         my $primary_id = &domain($dom,'primary');
                   13566:         my $primary_ip = &get_host_ip($primary_id);
                   13567:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13568:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13569:                 my $intdom = &internet_dom($id);
                   13570:                 if ($intdom eq $hostintdom) {
                   13571:                     $same_intdom = 1;
                   13572:                     last;
                   13573:                 }
                   13574:             }
                   13575:         }
                   13576:     }
                   13577:     return $same_intdom;
                   13578: }
                   13579: 
1.1172.2.118.  .3(raebu 13580:20): sub uses_sts {
                   13581:20):     my ($ignore_cache) = @_;
                   13582:20):     my $lonhost = $perlvar{'lonHostID'};
                   13583:20):     my $hostname = &hostname($lonhost);
                   13584:20):     my $sts_on;
                   13585:20):     if ($protocol{$lonhost} eq 'https') {
                   13586:20):         my $cachetime = 12*3600;
                   13587:20):         if (!$ignore_cache) {
                   13588:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13589:20):             if (defined($cached)) {
                   13590:20):                 return $sts_on;
                   13591:20):             }
                   13592:20):         }
          .4(raebu 13593:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13594:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13595:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13596:20):         my $response=$ua->request($request);
          .3(raebu 13597:20):         if ($response->is_success) {
                   13598:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13599:20):             if ($has_sts eq '') {
                   13600:20):                 $sts_on = 0;
                   13601:20):             } else {
                   13602:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13603:20):                     my $maxage = $1;
                   13604:20):                     if ($maxage) {
                   13605:20):                         $sts_on = 1;
                   13606:20):                     } else {
                   13607:20):                         $sts_on = 0;
                   13608:20):                     }
                   13609:20):                 } else {
                   13610:20):                     $sts_on = 0;
                   13611:20):                 }
                   13612:20):             }
                   13613:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13614:20):         }
                   13615:20):     }
                   13616:20):     return;
                   13617:20): }
                   13618:20): 
          .14(raeb 13619:-21): sub get_requestor_ip {
                   13620:-21):     my ($r,$nolookup,$noproxy) = @_;
                   13621:-21):     my $from_ip;
                   13622:-21):     if (ref($r)) {
                   13623:-21):         $from_ip = $r->get_remote_host($nolookup);
                   13624:-21):     } else {
                   13625:-21):         $from_ip = $ENV{'REMOTE_ADDR'};
                   13626:-21):     }
                   13627:-21):     return $from_ip;
                   13628:-21): }
                   13629:-21): 
1.31      www      13630: # ------------------------------------------------------------- Declutters URLs
                   13631: 
                   13632: sub declutter {
                   13633:     my $thisfn=shift;
1.569     albertel 13634:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13635:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13636:         $thisfn=~s{^/home/httpd/html}{};
                   13637:     }
1.31      www      13638:     $thisfn=~s/^\///;
1.697     albertel 13639:     $thisfn=~s|^adm/wrapper/||;
                   13640:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13641:     $thisfn=~s/^res\///;
1.1172    bisitz   13642:     $thisfn=~s/^priv\///;
1.1032    raeburn  13643:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13644:         $thisfn=~s/\?.+$//;
                   13645:     }
1.268     www      13646:     return $thisfn;
                   13647: }
                   13648: 
                   13649: # ------------------------------------------------------------- Clutter up URLs
                   13650: 
                   13651: sub clutter {
                   13652:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13653:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13654: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13655:        $thisfn='/res'.$thisfn; 
                   13656:     }
1.1031    raeburn  13657:     if ($thisfn !~m|^/adm|) {
                   13658: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13659: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13660: 	} else {
                   13661: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13662: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13663: 	    if ($embstyle eq 'ssi'
                   13664: 		|| ($embstyle eq 'hdn')
                   13665: 		|| ($embstyle eq 'rat')
                   13666: 		|| ($embstyle eq 'prv')
                   13667: 		|| ($embstyle eq 'ign')) {
                   13668: 		#do nothing with these
                   13669: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13670: 		|| ($embstyle eq 'emb')
                   13671: 		|| ($embstyle eq 'wrp')) {
                   13672: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13673: 	    } elsif ($embstyle eq 'unk'
                   13674: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13675: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13676: 	    } else {
1.718     www      13677: #		&logthis("Got a blank emb style");
1.695     albertel 13678: 	    }
1.694     albertel 13679: 	}
1.1172.2.118.  .1(raebu 13680:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13681:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13682:     }
1.31      www      13683:     return $thisfn;
1.12      www      13684: }
                   13685: 
1.787     albertel 13686: sub clutter_with_no_wrapper {
                   13687:     my $uri = &clutter(shift);
                   13688:     if ($uri =~ m-^/adm/-) {
                   13689: 	$uri =~ s-^/adm/wrapper/-/-;
                   13690: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13691:     }
                   13692:     return $uri;
                   13693: }
                   13694: 
1.557     albertel 13695: sub freeze_escape {
                   13696:     my ($value)=@_;
                   13697:     if (ref($value)) {
                   13698: 	$value=&nfreeze($value);
                   13699: 	return '__FROZEN__'.&escape($value);
                   13700:     }
                   13701:     return &escape($value);
                   13702: }
                   13703: 
1.11      www      13704: 
1.557     albertel 13705: sub thaw_unescape {
                   13706:     my ($value)=@_;
                   13707:     if ($value =~ /^__FROZEN__/) {
                   13708: 	substr($value,0,10,undef);
                   13709: 	$value=&unescape($value);
                   13710: 	return &thaw($value);
                   13711:     }
                   13712:     return &unescape($value);
                   13713: }
                   13714: 
1.436     albertel 13715: sub correct_line_ends {
                   13716:     my ($result)=@_;
                   13717:     $$result =~s/\r\n/\n/mg;
                   13718:     $$result =~s/\r/\n/mg;
1.415     albertel 13719: }
1.1       albertel 13720: # ================================================================ Main Program
                   13721: 
1.184     www      13722: sub goodbye {
1.204     albertel 13723:    &logthis("Starting Shut down");
1.443     albertel 13724: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13725:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13726: #converted
1.599     albertel 13727: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13728:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13729: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13730: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13731: #1.1 only
1.870     albertel 13732: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13733: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13734: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13735: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13736:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13737:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13738:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13739:    &flushcourselogs();
                   13740:    &logthis("Shutting down");
                   13741: }
                   13742: 
1.852     albertel 13743: sub get_dns {
1.1172.2.17  raeburn  13744:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13745:     if (!$ignore_cache) {
                   13746: 	my ($content,$cached)=
                   13747: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13748: 	if ($cached) {
1.1172.2.17  raeburn  13749: 	    &$func($content,$hashref);
1.869     albertel 13750: 	    return;
                   13751: 	}
                   13752:     }
                   13753: 
                   13754:     my %alldns;
1.1172.2.96  raeburn  13755:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13756:         foreach my $dns (<$config>) {
                   13757: 	    next if ($dns !~ /^\^(\S*)/x);
                   13758:             my $line = $1;
                   13759:             my ($host,$protocol) = split(/:/,$line);
                   13760:             if ($protocol ne 'https') {
                   13761:                 $protocol = 'http';
                   13762:             }
                   13763: 	    $alldns{$host} = $protocol;
1.979     raeburn  13764:         }
1.1172.2.96  raeburn  13765:         close($config);
1.869     albertel 13766:     }
                   13767:     while (%alldns) {
1.1172.2.52  raeburn  13768: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13769: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13770:         $ua->timeout(30);
1.979     raeburn  13771: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13772: 	my $response=$ua->request($request);
1.979     raeburn  13773:         delete($alldns{$dns});
1.852     albertel 13774: 	next if ($response->is_error());
                   13775: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13776:         unless ($nocache) {
1.1172.2.23  raeburn  13777: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13778:         }
                   13779: 	&$func(\@content,$hashref);
1.869     albertel 13780: 	return;
1.852     albertel 13781:     }
1.871     albertel 13782:     my $which = (split('/',$url))[3];
                   13783:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13784:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13785:         my @content = <$config>;
                   13786:         &$func(\@content,$hashref);
                   13787:     }
1.1172.2.17  raeburn  13788:     return;
                   13789: }
                   13790: 
                   13791: # ------------------------------------------------------Get DNS checksums file
                   13792: sub parse_dns_checksums_tab {
                   13793:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13794:     my $lonhost = $perlvar{'lonHostID'};
                   13795:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13796:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13797:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13798:     my $webconfdir = '/etc/httpd/conf';
                   13799:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13800:         $webconfdir = '/etc/apache2';
                   13801:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13802:         if ($1 >= 10) {
                   13803:             $webconfdir = '/etc/apache2';
                   13804:         }
                   13805:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13806:         if ($1 >= 10.0) {
                   13807:             $webconfdir = '/etc/apache2';
                   13808:         }
                   13809:     }
1.1172.2.17  raeburn  13810:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13811:     my (%chksum,%revnum);
                   13812:     if (ref($lines) eq 'ARRAY') {
                   13813:         chomp(@{$lines});
1.1172.2.34  raeburn  13814:         my $version = shift(@{$lines});
                   13815:         if ($version eq $release) {
1.1172.2.17  raeburn  13816:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13817:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13818:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13819:                     if ($webconfdir eq '/etc/apache2') {
                   13820:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13821:                     }
                   13822:                 }
1.1172.2.34  raeburn  13823:                 $chksum{$file} = $shasum;
                   13824:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13825:             }
                   13826:             if (ref($hashref) eq 'HASH') {
                   13827:                 %{$hashref} = (
                   13828:                                 sums     => \%chksum,
                   13829:                                 versions => \%revnum,
                   13830:                               );
                   13831:             }
                   13832:         }
                   13833:     }
1.869     albertel 13834:     return;
1.852     albertel 13835: }
1.1172.2.17  raeburn  13836: 
                   13837: sub fetch_dns_checksums {
                   13838:     my %checksums;
1.1172.2.34  raeburn  13839:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13840:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13841:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13842:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13843:              \%checksums);
                   13844:     return \%checksums;
                   13845: }
                   13846: 
1.327     albertel 13847: # ------------------------------------------------------------ Read domain file
                   13848: {
1.852     albertel 13849:     my $loaded;
1.846     albertel 13850:     my %domain;
                   13851: 
1.852     albertel 13852:     sub parse_domain_tab {
                   13853: 	my ($lines) = @_;
                   13854: 	foreach my $line (@$lines) {
                   13855: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13856: 
1.846     albertel 13857: 	    chomp($line);
1.852     albertel 13858: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13859: 	    my %this_domain;
                   13860: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13861: 			       'lang_def', 'city', 'longi', 'lati',
                   13862: 			       'primary') {
                   13863: 		$this_domain{$field} = shift(@elements);
                   13864: 	    }
                   13865: 	    $domain{$name} = \%this_domain;
1.852     albertel 13866: 	}
                   13867:     }
1.864     albertel 13868: 
                   13869:     sub reset_domain_info {
                   13870: 	undef($loaded);
                   13871: 	undef(%domain);
                   13872:     }
                   13873: 
1.852     albertel 13874:     sub load_domain_tab {
1.1172.2.70  raeburn  13875: 	my ($ignore_cache,$nocache) = @_;
                   13876: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13877: 	my $fh;
1.1172.2.96  raeburn  13878: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13879: 	    my @lines = <$fh>;
                   13880: 	    &parse_domain_tab(\@lines);
1.448     albertel 13881: 	}
1.852     albertel 13882: 	close($fh);
                   13883: 	$loaded = 1;
1.327     albertel 13884:     }
1.846     albertel 13885: 
                   13886:     sub domain {
1.852     albertel 13887: 	&load_domain_tab() if (!$loaded);
                   13888: 
1.846     albertel 13889: 	my ($name,$what) = @_;
                   13890: 	return if ( !exists($domain{$name}) );
                   13891: 
                   13892: 	if (!$what) {
                   13893: 	    return $domain{$name}{'description'};
                   13894: 	}
                   13895: 	return $domain{$name}{$what};
                   13896:     }
1.974     raeburn  13897: 
                   13898:     sub domain_info {
                   13899:         &load_domain_tab() if (!$loaded);
                   13900:         return %domain;
                   13901:     }
                   13902: 
1.327     albertel 13903: }
                   13904: 
                   13905: 
1.1       albertel 13906: # ------------------------------------------------------------- Read hosts file
                   13907: {
1.838     albertel 13908:     my %hostname;
1.844     albertel 13909:     my %hostdom;
1.845     albertel 13910:     my %libserv;
1.852     albertel 13911:     my $loaded;
1.888     albertel 13912:     my %name_to_host;
1.1074    raeburn  13913:     my %internetdom;
1.1107    raeburn  13914:     my %LC_dns_serv;
1.852     albertel 13915: 
                   13916:     sub parse_hosts_tab {
                   13917: 	my ($file) = @_;
                   13918: 	foreach my $configline (@$file) {
                   13919: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13920:             chomp($configline);
                   13921: 	    if ($configline =~ /^\^/) {
                   13922:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13923:                     $LC_dns_serv{$1} = 1;
                   13924:                 }
                   13925:                 next;
                   13926:             }
1.1074    raeburn  13927: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13928: 	    $name=~s/\s//g;
                   13929: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13930:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13931:                     my $curr = $hostname{$id};
                   13932:                     my $skip;
                   13933:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13934:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13935:                             $skip = 1;
                   13936:                         } else {
                   13937:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13938:                         }
                   13939:                     }
                   13940:                     unless ($skip) {
                   13941:                         push(@{$name_to_host{$name}},$id);
                   13942:                     }
                   13943:                 } else {
                   13944:                     push(@{$name_to_host{$name}},$id);
                   13945:                 }
1.852     albertel 13946: 		$hostname{$id}=$name;
                   13947: 		$hostdom{$id}=$domain;
                   13948: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13949:                 if (defined($protocol)) {
                   13950:                     if ($protocol eq 'https') {
                   13951:                         $protocol{$id} = $protocol;
                   13952:                     } else {
                   13953:                         $protocol{$id} = 'http'; 
                   13954:                     }
1.968     raeburn  13955:                 } else {
1.969     raeburn  13956:                     $protocol{$id} = 'http';
1.968     raeburn  13957:                 }
1.1074    raeburn  13958:                 if (defined($intdom)) {
                   13959:                     $internetdom{$id} = $intdom;
                   13960:                 }
1.852     albertel 13961: 	    }
                   13962: 	}
                   13963:     }
1.864     albertel 13964:     
                   13965:     sub reset_hosts_info {
1.897     albertel 13966: 	&purge_remembered();
1.864     albertel 13967: 	&reset_domain_info();
                   13968: 	&reset_hosts_ip_info();
1.892     albertel 13969: 	undef(%name_to_host);
1.864     albertel 13970: 	undef(%hostname);
                   13971: 	undef(%hostdom);
                   13972: 	undef(%libserv);
                   13973: 	undef($loaded);
                   13974:     }
1.1       albertel 13975: 
1.852     albertel 13976:     sub load_hosts_tab {
1.1172.2.70  raeburn  13977: 	my ($ignore_cache,$nocache) = @_;
                   13978: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13979: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13980: 	my @config = <$config>;
                   13981: 	&parse_hosts_tab(\@config);
                   13982: 	close($config);
                   13983: 	$loaded=1;
1.1       albertel 13984:     }
1.852     albertel 13985: 
1.838     albertel 13986:     sub hostname {
1.852     albertel 13987: 	&load_hosts_tab() if (!$loaded);
                   13988: 
1.838     albertel 13989: 	my ($lonid) = @_;
                   13990: 	return $hostname{$lonid};
                   13991:     }
1.845     albertel 13992: 
1.838     albertel 13993:     sub all_hostnames {
1.852     albertel 13994: 	&load_hosts_tab() if (!$loaded);
                   13995: 
1.838     albertel 13996: 	return %hostname;
                   13997:     }
1.845     albertel 13998: 
1.888     albertel 13999:     sub all_names {
1.1172.2.70  raeburn  14000:         my ($ignore_cache,$nocache) = @_;
                   14001: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14002: 
                   14003: 	return %name_to_host;
                   14004:     }
                   14005: 
1.974     raeburn  14006:     sub all_host_domain {
                   14007:         &load_hosts_tab() if (!$loaded);
                   14008:         return %hostdom;
                   14009:     }
                   14010: 
1.845     albertel 14011:     sub is_library {
1.852     albertel 14012: 	&load_hosts_tab() if (!$loaded);
                   14013: 
1.845     albertel 14014: 	return exists($libserv{$_[0]});
                   14015:     }
                   14016: 
                   14017:     sub all_library {
1.852     albertel 14018: 	&load_hosts_tab() if (!$loaded);
                   14019: 
1.845     albertel 14020: 	return %libserv;
                   14021:     }
                   14022: 
1.1062    droeschl 14023:     sub unique_library {
                   14024: 	#2x reverse removes all hostnames that appear more than once
                   14025:         my %unique = reverse &all_library();
                   14026:         return reverse %unique;
                   14027:     }
                   14028: 
1.841     albertel 14029:     sub get_servers {
1.852     albertel 14030: 	&load_hosts_tab() if (!$loaded);
                   14031: 
1.841     albertel 14032: 	my ($domain,$type) = @_;
                   14033: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14034: 	                                          : %hostname;
                   14035: 	my %result;
1.842     albertel 14036: 	if (ref($domain) eq 'ARRAY') {
                   14037: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14038: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14039: 		    $result{$host} = $hostname;
                   14040: 		}
                   14041: 	    }
                   14042: 	} else {
                   14043: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14044: 		if ($hostdom{$host} eq $domain) {
                   14045: 		    $result{$host} = $hostname;
                   14046: 		}
1.841     albertel 14047: 	    }
                   14048: 	}
                   14049: 	return %result;
                   14050:     }
1.845     albertel 14051: 
1.1062    droeschl 14052:     sub get_unique_servers {
                   14053:         my %unique = reverse &get_servers(@_);
                   14054: 	return reverse %unique;
                   14055:     }
                   14056: 
1.844     albertel 14057:     sub host_domain {
1.852     albertel 14058: 	&load_hosts_tab() if (!$loaded);
                   14059: 
1.844     albertel 14060: 	my ($lonid) = @_;
                   14061: 	return $hostdom{$lonid};
                   14062:     }
                   14063: 
1.841     albertel 14064:     sub all_domains {
1.852     albertel 14065: 	&load_hosts_tab() if (!$loaded);
                   14066: 
1.841     albertel 14067: 	my %seen;
                   14068: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14069: 	return @uniq;
                   14070:     }
1.1074    raeburn  14071: 
                   14072:     sub internet_dom {
                   14073:         &load_hosts_tab() if (!$loaded);
                   14074: 
                   14075:         my ($lonid) = @_;
                   14076:         return $internetdom{$lonid};
                   14077:     }
1.1107    raeburn  14078: 
                   14079:     sub is_LC_dns {
                   14080:         &load_hosts_tab() if (!$loaded);
                   14081: 
                   14082:         my ($hostname) = @_;
                   14083:         return exists($LC_dns_serv{$hostname});
                   14084:     }
                   14085: 
1.1       albertel 14086: }
                   14087: 
1.847     albertel 14088: { 
                   14089:     my %iphost;
1.856     albertel 14090:     my %name_to_ip;
                   14091:     my %lonid_to_ip;
1.869     albertel 14092: 
1.847     albertel 14093:     sub get_hosts_from_ip {
                   14094: 	my ($ip) = @_;
                   14095: 	my %iphosts = &get_iphost();
                   14096: 	if (ref($iphosts{$ip})) {
                   14097: 	    return @{$iphosts{$ip}};
                   14098: 	}
                   14099: 	return;
1.839     albertel 14100:     }
1.864     albertel 14101:     
                   14102:     sub reset_hosts_ip_info {
                   14103: 	undef(%iphost);
                   14104: 	undef(%name_to_ip);
                   14105: 	undef(%lonid_to_ip);
                   14106:     }
1.856     albertel 14107: 
                   14108:     sub get_host_ip {
                   14109: 	my ($lonid) = @_;
                   14110: 	if (exists($lonid_to_ip{$lonid})) {
                   14111: 	    return $lonid_to_ip{$lonid};
                   14112: 	}
                   14113: 	my $name=&hostname($lonid);
                   14114:    	my $ip = gethostbyname($name);
                   14115: 	return if (!$ip || length($ip) ne 4);
                   14116: 	$ip=inet_ntoa($ip);
                   14117: 	$name_to_ip{$name}   = $ip;
                   14118: 	$lonid_to_ip{$lonid} = $ip;
                   14119: 	return $ip;
                   14120:     }
1.847     albertel 14121:     
                   14122:     sub get_iphost {
1.1172.2.70  raeburn  14123: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14124: 
1.869     albertel 14125: 	if (!$ignore_cache) {
                   14126: 	    if (%iphost) {
                   14127: 		return %iphost;
                   14128: 	    }
                   14129: 	    my ($ip_info,$cached)=
                   14130: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14131: 	    if ($cached) {
                   14132: 		%iphost      = %{$ip_info->[0]};
                   14133: 		%name_to_ip  = %{$ip_info->[1]};
                   14134: 		%lonid_to_ip = %{$ip_info->[2]};
                   14135: 		return %iphost;
                   14136: 	    }
                   14137: 	}
1.894     albertel 14138: 
                   14139: 	# get yesterday's info for fallback
                   14140: 	my %old_name_to_ip;
                   14141: 	my ($ip_info,$cached)=
                   14142: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14143: 	if ($cached) {
                   14144: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14145: 	}
                   14146: 
1.1172.2.70  raeburn  14147: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14148: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14149: 	    my $ip;
                   14150: 	    if (!exists($name_to_ip{$name})) {
                   14151: 		$ip = gethostbyname($name);
                   14152: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14153: 		    if (defined($old_name_to_ip{$name})) {
                   14154: 			$ip = $old_name_to_ip{$name};
                   14155: 			&logthis("Can't find $name defaulting to old $ip");
                   14156: 		    } else {
                   14157: 			&logthis("Name $name no IP found");
                   14158: 			next;
                   14159: 		    }
                   14160: 		} else {
                   14161: 		    $ip=inet_ntoa($ip);
1.847     albertel 14162: 		}
                   14163: 		$name_to_ip{$name} = $ip;
                   14164: 	    } else {
                   14165: 		$ip = $name_to_ip{$name};
1.653     albertel 14166: 	    }
1.888     albertel 14167: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14168: 		$lonid_to_ip{$id} = $ip;
                   14169: 	    }
                   14170: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14171: 	}
1.1172.2.70  raeburn  14172:         unless ($nocache) {
                   14173: 	    &do_cache_new('iphost','iphost',
                   14174: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14175: 		          48*60*60);
                   14176:         }
1.869     albertel 14177: 
1.847     albertel 14178: 	return %iphost;
1.598     albertel 14179:     }
                   14180: 
1.992     raeburn  14181:     #
                   14182:     #  Given a DNS returns the loncapa host name for that DNS 
                   14183:     # 
                   14184:     sub host_from_dns {
                   14185:         my ($dns) = @_;
                   14186:         my @hosts;
                   14187:         my $ip;
                   14188: 
1.993     raeburn  14189:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14190:             $ip = $name_to_ip{$dns};
                   14191:         }
                   14192:         if (!$ip) {
                   14193:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14194:             if (length($ip) == 4) { 
                   14195: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14196:             }
                   14197:         }
                   14198:         if ($ip) {
                   14199: 	    @hosts = get_hosts_from_ip($ip);
                   14200: 	    return $hosts[0];
                   14201:         }
                   14202:         return undef;
1.986     foxr     14203:     }
1.992     raeburn  14204: 
1.1074    raeburn  14205:     sub get_internet_names {
                   14206:         my ($lonid) = @_;
                   14207:         return if ($lonid eq '');
                   14208:         my ($idnref,$cached)=
                   14209:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14210:         if ($cached) {
                   14211:             return $idnref;
                   14212:         }
                   14213:         my $ip = &get_host_ip($lonid);
                   14214:         my @hosts = &get_hosts_from_ip($ip);
                   14215:         my %iphost = &get_iphost();
                   14216:         my (@idns,%seen);
                   14217:         foreach my $id (@hosts) {
                   14218:             my $dom = &host_domain($id);
                   14219:             my $prim_id = &domain($dom,'primary');
                   14220:             my $prim_ip = &get_host_ip($prim_id);
                   14221:             next if ($seen{$prim_ip});
                   14222:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14223:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14224:                     my $intdom = &internet_dom($id);
                   14225:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14226:                         push(@idns,$intdom);
                   14227:                     }
                   14228:                 }
                   14229:             }
                   14230:             $seen{$prim_ip} = 1;
                   14231:         }
1.1172.2.23  raeburn  14232:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14233:     }
                   14234: 
1.986     foxr     14235: }
                   14236: 
1.1079    raeburn  14237: sub all_loncaparevs {
1.1172.2.39  raeburn  14238:     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  14239: }
                   14240: 
1.1172.2.27  raeburn  14241: # ------------------------------------------------------- Read loncaparev table
                   14242: {
                   14243:     sub load_loncaparevs {
                   14244:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14245:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14246:                 while (my $configline=<$config>) {
                   14247:                     chomp($configline);
                   14248:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14249:                     $loncaparevs{$hostid}=$loncaparev;
                   14250:                 }
                   14251:                 close($config);
                   14252:             }
                   14253:         }
                   14254:     }
                   14255: }
                   14256: 
                   14257: # ----------------------------------------------------- Read serverhostID table
                   14258: {
                   14259:     sub load_serverhomeIDs {
                   14260:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14261:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14262:                 while (my $configline=<$config>) {
                   14263:                     chomp($configline);
                   14264:                     my ($name,$id)=split(/:/,$configline);
                   14265:                     $serverhomeIDs{$name}=$id;
                   14266:                 }
                   14267:                 close($config);
                   14268:             }
                   14269:         }
                   14270:     }
                   14271: }
                   14272: 
                   14273: 
1.862     albertel 14274: BEGIN {
                   14275: 
                   14276: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14277:     unless ($readit) {
                   14278: {
                   14279:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14280:     %perlvar = (%perlvar,%{$configvars});
                   14281: }
                   14282: 
                   14283: 
1.1       albertel 14284: # ------------------------------------------------------ Read spare server file
                   14285: {
1.1172.2.96  raeburn  14286:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14287: 
                   14288:     while (my $configline=<$config>) {
                   14289:        chomp($configline);
1.284     matthew  14290:        if ($configline) {
1.784     albertel 14291: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14292: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14293: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14294:        }
                   14295:     }
1.448     albertel 14296:     close($config);
1.1       albertel 14297: }
1.11      www      14298: # ------------------------------------------------------------ Read permissions
                   14299: {
1.1172.2.96  raeburn  14300:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14301: 
                   14302:     while (my $configline=<$config>) {
1.448     albertel 14303: 	chomp($configline);
                   14304: 	if ($configline) {
                   14305: 	    my ($role,$perm)=split(/ /,$configline);
                   14306: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14307: 	}
1.11      www      14308:     }
1.448     albertel 14309:     close($config);
1.11      www      14310: }
                   14311: 
                   14312: # -------------------------------------------- Read plain texts for permissions
                   14313: {
1.1172.2.96  raeburn  14314:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14315: 
                   14316:     while (my $configline=<$config>) {
1.448     albertel 14317: 	chomp($configline);
                   14318: 	if ($configline) {
1.742     raeburn  14319: 	    my ($short,@plain)=split(/:/,$configline);
                   14320:             %{$prp{$short}} = ();
                   14321: 	    if (@plain > 0) {
                   14322:                 $prp{$short}{'std'} = $plain[0];
                   14323:                 for (my $i=1; $i<@plain; $i++) {
                   14324:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14325:                 }
                   14326:             }
1.448     albertel 14327: 	}
1.135     www      14328:     }
1.448     albertel 14329:     close($config);
1.135     www      14330: }
                   14331: 
                   14332: # ---------------------------------------------------------- Read package table
                   14333: {
1.1172.2.96  raeburn  14334:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14335: 
                   14336:     while (my $configline=<$config>) {
1.483     albertel 14337: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14338: 	chomp($configline);
                   14339: 	my ($short,$plain)=split(/:/,$configline);
                   14340: 	my ($pack,$name)=split(/\&/,$short);
                   14341: 	if ($plain ne '') {
                   14342: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14343: 	    $packagetab{$short}=$plain; 
                   14344: 	}
1.11      www      14345:     }
1.448     albertel 14346:     close($config);
1.329     matthew  14347: }
                   14348: 
1.1172.2.27  raeburn  14349: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14350: 
1.1172.2.27  raeburn  14351: &load_loncaparevs();
                   14352: 
                   14353: # ------------------------------------------------------- Read serverhostID table
                   14354: 
                   14355: &load_serverhomeIDs();
1.1074    raeburn  14356: 
1.1172.2.27  raeburn  14357: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14358: {
                   14359:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14360:     if (-e $file) {
                   14361:         my $parser = HTML::LCParser->new($file);
                   14362:         while (my $token = $parser->get_token()) {
                   14363:             if ($token->[0] eq 'S') {
                   14364:                 my $item = $token->[1];
                   14365:                 my $name = $token->[2]{'name'};
                   14366:                 my $value = $token->[2]{'value'};
                   14367:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14368:                     my $release = $parser->get_text();
                   14369:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14370:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14371:                 }
                   14372:             }
                   14373:         }
                   14374:     }
1.1073    raeburn  14375: }
                   14376: 
1.1138    raeburn  14377: # ---------------------------------------------------------- Read managers table
                   14378: {
                   14379:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14380:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14381:             while (my $configline=<$config>) {
                   14382:                 chomp($configline);
                   14383:                 next if ($configline =~ /^\#/);
                   14384:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14385:                     $managerstab{$configline} = 1;
                   14386:                 }
                   14387:             }
                   14388:             close($config);
                   14389:         }
                   14390:     }
                   14391: }
                   14392: 
1.329     matthew  14393: # ------------- set up temporary directory
                   14394: {
1.1117    foxr     14395:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14396: 
1.11      www      14397: }
                   14398: 
1.1172.2.104  raeburn  14399: # ------------- set default texengine (domain default overrides this)
                   14400: {
                   14401:     $deftex = LONCAPA::texengine();
                   14402: }
                   14403: 
1.1172.2.114  raeburn  14404: # ------------- set default minimum length for passwords for internal auth users
                   14405: {
                   14406:     $passwdmin = LONCAPA::passwd_min();
                   14407: }
                   14408: 
1.794     albertel 14409: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14410: 				'compress_threshold'=> 20_000,
                   14411:  			        });
1.185     www      14412: 
1.281     www      14413: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14414: $dumpcount=0;
1.958     www      14415: $locknum=0;
1.22      www      14416: 
1.163     harris41 14417: &logtouch();
1.672     albertel 14418: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14419: $readit=1;
1.564     albertel 14420:     {
                   14421: 	use integer;
                   14422: 	my $test=(2**32)+1;
1.568     albertel 14423: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14424: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14425:     }
1.195     www      14426: }
1.1       albertel 14427: }
1.179     www      14428: 
1.1       albertel 14429: 1;
1.191     harris41 14430: __END__
                   14431: 
1.243     albertel 14432: =pod
                   14433: 
1.191     harris41 14434: =head1 NAME
                   14435: 
1.243     albertel 14436: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14437: 
                   14438: =head1 SYNOPSIS
                   14439: 
1.243     albertel 14440: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14441: 
                   14442:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14443: 
1.243     albertel 14444: Common parameters:
                   14445: 
                   14446: =over 4
                   14447: 
                   14448: =item *
                   14449: 
                   14450: $uname : an internal username (if $cname expecting a course Id specifically)
                   14451: 
                   14452: =item *
                   14453: 
                   14454: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14455: 
                   14456: =item *
                   14457: 
                   14458: $symb : a resource instance identifier
                   14459: 
                   14460: =item *
                   14461: 
                   14462: $namespace : the name of a .db file that contains the data needed or
                   14463: being set.
                   14464: 
                   14465: =back
                   14466: 
1.394     bowersj2 14467: =head1 OVERVIEW
1.191     harris41 14468: 
1.394     bowersj2 14469: lonnet provides subroutines which interact with the
                   14470: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14471: about classes, users, and resources.
1.243     albertel 14472: 
                   14473: For many of these objects you can also use this to store data about
                   14474: them or modify them in various ways.
1.191     harris41 14475: 
1.394     bowersj2 14476: =head2 Symbs
1.191     harris41 14477: 
1.394     bowersj2 14478: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14479: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14480: map, the resource number of the resource in the map, and the URL of
                   14481: the resource itself. The latter is somewhat redundant, but might help
                   14482: if maps change.
                   14483: 
                   14484: An example is
                   14485: 
                   14486:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14487: 
                   14488: The respective map entry is
                   14489: 
                   14490:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14491:   title="Problem 2">
                   14492:  </resource>
                   14493: 
                   14494: Symbs are used by the random number generator, as well as to store and
                   14495: restore data specific to a certain instance of for example a problem.
                   14496: 
                   14497: =head2 Storing And Retrieving Data
                   14498: 
                   14499: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14500: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14501: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14502: is is the non-critical message twin of cstore. These functions are for
                   14503: handlers to store a perl hash to a user's permanent data space in an
                   14504: easy manner, and to retrieve it again on another call. It is expected
                   14505: that a handler would use this once at the beginning to retrieve data,
                   14506: and then again once at the end to send only the new data back.
                   14507: 
                   14508: The data is stored in the user's data directory on the user's
                   14509: homeserver under the ID of the course.
                   14510: 
                   14511: The hash that is returned by restore will have all of the previous
                   14512: value for all of the elements of the hash.
                   14513: 
                   14514: Example:
                   14515: 
                   14516:  #creating a hash
                   14517:  my %hash;
                   14518:  $hash{'foo'}='bar';
                   14519: 
                   14520:  #storing it
                   14521:  &Apache::lonnet::cstore(\%hash);
                   14522: 
                   14523:  #changing a value
                   14524:  $hash{'foo'}='notbar';
                   14525: 
                   14526:  #adding a new value
                   14527:  $hash{'bar'}='foo';
                   14528:  &Apache::lonnet::cstore(\%hash);
                   14529: 
                   14530:  #retrieving the hash
                   14531:  my %history=&Apache::lonnet::restore();
                   14532: 
                   14533:  #print the hash
                   14534:  foreach my $key (sort(keys(%history))) {
                   14535:    print("\%history{$key} = $history{$key}");
                   14536:  }
                   14537: 
                   14538: Will print out:
1.191     harris41 14539: 
1.394     bowersj2 14540:  %history{1:foo} = bar
                   14541:  %history{1:keys} = foo:timestamp
                   14542:  %history{1:timestamp} = 990455579
                   14543:  %history{2:bar} = foo
                   14544:  %history{2:foo} = notbar
                   14545:  %history{2:keys} = foo:bar:timestamp
                   14546:  %history{2:timestamp} = 990455580
                   14547:  %history{bar} = foo
                   14548:  %history{foo} = notbar
                   14549:  %history{timestamp} = 990455580
                   14550:  %history{version} = 2
                   14551: 
                   14552: Note that the special hash entries C<keys>, C<version> and
                   14553: C<timestamp> were added to the hash. C<version> will be equal to the
                   14554: total number of versions of the data that have been stored. The
                   14555: C<timestamp> attribute will be the UNIX time the hash was
                   14556: stored. C<keys> is available in every historical section to list which
                   14557: keys were added or changed at a specific historical revision of a
                   14558: hash.
                   14559: 
                   14560: B<Warning>: do not store the hash that restore returns directly. This
                   14561: will cause a mess since it will restore the historical keys as if the
                   14562: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14563: 
1.394     bowersj2 14564: Calling convention:
1.191     harris41 14565: 
1.1172.2.27  raeburn  14566:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14567:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14568: 
1.394     bowersj2 14569: For more detailed information, see lonnet specific documentation.
1.191     harris41 14570: 
1.394     bowersj2 14571: =head1 RETURN MESSAGES
1.191     harris41 14572: 
1.394     bowersj2 14573: =over 4
1.191     harris41 14574: 
1.394     bowersj2 14575: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14576: 
1.394     bowersj2 14577: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14578: when the connection is brought back up
1.191     harris41 14579: 
1.394     bowersj2 14580: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14581: for later delivery
1.191     harris41 14582: 
1.967     bisitz   14583: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14584: 
1.394     bowersj2 14585: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14586: that was requested
1.191     harris41 14587: 
1.243     albertel 14588: =back
1.191     harris41 14589: 
1.243     albertel 14590: =head1 PUBLIC SUBROUTINES
1.191     harris41 14591: 
1.243     albertel 14592: =head2 Session Environment Functions
1.191     harris41 14593: 
1.243     albertel 14594: =over 4
1.191     harris41 14595: 
1.394     bowersj2 14596: =item * 
                   14597: X<appenv()>
1.949     raeburn  14598: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14599: the user envirnoment file, and will be restored for each access this
1.620     albertel 14600: user makes during this session, also modifies the %env for the current
1.949     raeburn  14601: process. Optional rolesarrayref - if defined contains a reference to an array
                   14602: of roles which are exempt from the restriction on modifying user.role entries 
                   14603: in the user's environment.db and in %env.    
1.191     harris41 14604: 
                   14605: =item *
1.394     bowersj2 14606: X<delenv()>
1.987     raeburn  14607: B<delenv($delthis,$regexp)>: removes all items from the session
                   14608: environment file that begin with $delthis. If the 
                   14609: optional second arg - $regexp - is true, $delthis is treated as a 
                   14610: regular expression, otherwise \Q$delthis\E is used. 
                   14611: The values are also deleted from the current processes %env.
1.191     harris41 14612: 
1.795     albertel 14613: =item * get_env_multiple($name) 
                   14614: 
                   14615: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14616: values may be defined and end up as an array ref.
                   14617: 
                   14618: returns an array of values
                   14619: 
1.243     albertel 14620: =back
                   14621: 
                   14622: =head2 User Information
1.191     harris41 14623: 
1.243     albertel 14624: =over 4
1.191     harris41 14625: 
                   14626: =item *
1.394     bowersj2 14627: X<queryauthenticate()>
                   14628: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14629: authentication scheme
                   14630: 
                   14631: =item *
1.394     bowersj2 14632: X<authenticate()>
1.1073    raeburn  14633: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14634: authenticate user from domain's lib servers (first use the current
                   14635: one). C<$upass> should be the users password.
1.1073    raeburn  14636: $checkdefauth is optional (value is 1 if a check should be made to
                   14637:    authenticate user using default authentication method, and allow
                   14638:    account creation if username does not have account in the domain).
                   14639: $clientcancheckhost is optional (value is 1 if checking whether the
                   14640:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14641: 
                   14642: =item *
1.394     bowersj2 14643: X<homeserver()>
                   14644: B<homeserver($uname,$udom)>: find the server which has
                   14645: the user's directory and files (there must be only one), this caches
                   14646: the answer, and also caches if there is a borken connection.
1.191     harris41 14647: 
                   14648: =item *
1.394     bowersj2 14649: X<idget()>
                   14650: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14651: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14652: username, and only 1 username per ID in a specific domain) (returns
                   14653: hash: id=>name,id=>name)
1.191     harris41 14654: 
                   14655: =item *
1.394     bowersj2 14656: X<idrget()>
                   14657: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14658: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14659: 
                   14660: =item *
1.394     bowersj2 14661: X<idput()>
                   14662: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14663: 
                   14664: =item *
1.394     bowersj2 14665: X<rolesinit()>
1.1169    droeschl 14666: B<rolesinit($udom,$username)>: get user privileges.
                   14667: returns user role, first access and timer interval hashes
1.243     albertel 14668: 
                   14669: =item *
1.1171    droeschl 14670: X<privileged()>
                   14671: B<privileged($username,$domain)>: returns a true if user has a
                   14672: privileged and active role (i.e. su or dc), false otherwise.
                   14673: 
                   14674: =item *
1.551     albertel 14675: X<getsection()>
                   14676: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14677: course $cname, return section name/number or '' for "not in course"
                   14678: and '-1' for "no section"
                   14679: 
                   14680: =item *
1.394     bowersj2 14681: X<userenvironment()>
                   14682: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14683: passed in @what from the requested user's environment, returns a hash
                   14684: 
1.858     raeburn  14685: =item * 
                   14686: X<userlog_query()>
1.859     albertel 14687: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14688: activity.log file. %filters defines filters applied when parsing the
                   14689: log file. These can be start or end timestamps, or the type of action
                   14690: - log to look for Login or Logout events, check for Checkin or
                   14691: Checkout, role for role selection. The response is in the form
                   14692: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14693: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14694: 
1.243     albertel 14695: =back
                   14696: 
                   14697: =head2 User Roles
                   14698: 
                   14699: =over 4
                   14700: 
                   14701: =item *
                   14702: 
1.1172.2.65  raeburn  14703: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14704: returns codes for allowed actions.
                   14705: 
                   14706: The first argument is required, all others are optional.
                   14707: 
                   14708: $priv is the privilege being checked.
                   14709: $uri contains additional information about what is being checked for access (e.g.,
                   14710: URL, course ID etc.).
                   14711: $symb is the unique resource instance identifier in a course; if needed,
                   14712: but not provided, it will be retrieved via a call to &symbread().
                   14713: $role is the role for which a priv is being checked (only used if priv is evb).
                   14714: $clientip is the user's IP address (only used when checking for access to portfolio
                   14715: files).
                   14716: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14717: prevents recursive calls to &allowed.
                   14718: 
1.243     albertel 14719:  F: full access
                   14720:  U,I,K: authentication modes (cxx only)
                   14721:  '': forbidden
                   14722:  1: user needs to choose course
                   14723:  2: browse allowed
1.766     albertel 14724:  A: passphrase authentication needed
1.1172.2.65  raeburn  14725:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14726: 
                   14727: =item *
                   14728: 
1.1172.2.13  raeburn  14729: constructaccess($url,$setpriv) : check for access to construction space URL
                   14730: 
                   14731: See if the owner domain and name in the URL match those in the
                   14732: expected environment.  If so, return three element list
                   14733: ($ownername,$ownerdomain,$ownerhome).
                   14734: 
                   14735: Otherwise return the null string.
                   14736: 
                   14737: If second argument 'setpriv' is true, it assigns the privileges,
                   14738: and returns the same three element list, unless the owner has
                   14739: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14740: in which case the null string is returned.
                   14741: 
                   14742: =item *
                   14743: 
1.1172.2.84  raeburn  14744: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14745: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14746: for system, domain, and course level. $uname and $udom are optional (current
                   14747: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14748: 
                   14749: =item *
                   14750: 
1.988     raeburn  14751: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14752: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14753: $type is Course (default) or Community.
1.988     raeburn  14754: If $forcedefault evaluates to true, text returned will be default 
                   14755: text for $type. Otherwise, if this is a course, the text returned 
                   14756: will be a custom name for the role (if defined in the course's 
                   14757: environment).  If no custom name is defined the default is returned.
                   14758:    
1.832     raeburn  14759: =item *
                   14760: 
1.1172.2.23  raeburn  14761: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14762: All arguments are optional. Returns a hash of a roles, either for
                   14763: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14764: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14765: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14766: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14767: For each key, value is set to colon-separated start and end times for
                   14768: the role.  If no username and domain are specified, will default to
1.934     raeburn  14769: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14770: of role statuses (active, future or previous), roles 
                   14771: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14772: to restrict the list of roles reported. If no array ref is 
                   14773: provided for types, will default to return only active roles.
1.834     albertel 14774: 
1.1172.2.13  raeburn  14775: =item *
                   14776: 
                   14777: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14778: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14779: 
                   14780: Additional optional arguments are: $type (if role checking is to be restricted
                   14781: to certain user status types -- previous (expired roles), active (currently
                   14782: available roles) or future (roles available in the future), and
                   14783: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14784: have active Domain Coordinator role in course's domain or in additional
                   14785: domains (specified in 'Domains to check for privileged users' in course
                   14786: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14787: 
                   14788: =item *
                   14789: 
                   14790: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14791: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14792: $possdomains and $possroles are optional array refs -- to domains to check and
                   14793: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14794: users' roles.db to check for a dc or su role in any domain. This can be
                   14795: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14796: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14797: this then allows &privileged_by_domain() to be used, which caches the identity
                   14798: of privileged users, eliminating the need for repeated calls to &dump().
                   14799: 
                   14800: =item *
                   14801: 
                   14802: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14803: where the outer hash keys are domains specified in the $possdomains array ref,
                   14804: next inner hash keys are privileged roles specified in the $roles array ref,
                   14805: and the innermost hash contains key = value pairs for username:domain = end:start
                   14806: for active or future "privileged" users with that role in that domain. To avoid
                   14807: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14808: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14809: 
1.243     albertel 14810: =back
                   14811: 
                   14812: =head2 User Modification
                   14813: 
                   14814: =over 4
                   14815: 
                   14816: =item *
                   14817: 
1.957     raeburn  14818: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14819: user for the level given by URL.  Optional start and end dates (leave empty
                   14820: string or zero for "no date")
1.191     harris41 14821: 
                   14822: =item *
                   14823: 
1.243     albertel 14824: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14825: change a users, password, possible return values are: ok,
                   14826: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14827: refused
1.191     harris41 14828: 
                   14829: =item *
                   14830: 
1.243     albertel 14831: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14832: 
                   14833: =item *
                   14834: 
1.1058    raeburn  14835: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14836:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14837: 
                   14838: will update user information (firstname,middlename,lastname,generation,
                   14839: permanentemail), and if forceid is true, student/employee ID also.
                   14840: A user's institutional affiliation(s) can also be updated.
                   14841: User information fields will not be overwritten with empty entries 
                   14842: unless the field is included in the $candelete array reference.
                   14843: This array is included when a single user is modified via "Manage Users",
                   14844: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14845: 
                   14846: =item *
                   14847: 
1.286     matthew  14848: modifystudent
                   14849: 
1.957     raeburn  14850: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14851: The course id is resolved based on the current user's environment.  
                   14852: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14853: associated with a course.
                   14854: 
1.297     matthew  14855: This call is essentially a wrapper for lonnet::modifyuser and
                   14856: lonnet::modify_student_enrollment
1.286     matthew  14857: 
                   14858: Inputs: 
                   14859: 
                   14860: =over 4
                   14861: 
1.957     raeburn  14862: =item B<$udom> Student's loncapa domain
1.286     matthew  14863: 
1.957     raeburn  14864: =item B<$uname> Student's loncapa login name
1.286     matthew  14865: 
1.964     bisitz   14866: =item B<$uid> Student/Employee ID
1.286     matthew  14867: 
1.957     raeburn  14868: =item B<$umode> Student's authentication mode
1.286     matthew  14869: 
1.957     raeburn  14870: =item B<$upass> Student's password
1.286     matthew  14871: 
1.957     raeburn  14872: =item B<$first> Student's first name
1.286     matthew  14873: 
1.957     raeburn  14874: =item B<$middle> Student's middle name
1.286     matthew  14875: 
1.957     raeburn  14876: =item B<$last> Student's last name
1.286     matthew  14877: 
1.957     raeburn  14878: =item B<$gene> Student's generation
1.286     matthew  14879: 
1.957     raeburn  14880: =item B<$usec> Student's section in course
1.286     matthew  14881: 
                   14882: =item B<$end> Unix time of the roles expiration
                   14883: 
                   14884: =item B<$start> Unix time of the roles start date
                   14885: 
                   14886: =item B<$forceid> If defined, allow $uid to be changed
                   14887: 
                   14888: =item B<$desiredhome> server to use as home server for student
                   14889: 
1.957     raeburn  14890: =item B<$email> Student's permanent e-mail address
                   14891: 
                   14892: =item B<$type> Type of enrollment (auto or manual)
                   14893: 
1.963     raeburn  14894: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14895: 
                   14896: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14897: 
1.963     raeburn  14898: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14899: 
1.963     raeburn  14900: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14901: 
1.1172.2.19  raeburn  14902: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14903: 
                   14904: =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  14905: 
1.286     matthew  14906: =back
1.297     matthew  14907: 
                   14908: =item *
                   14909: 
                   14910: modify_student_enrollment
                   14911: 
1.1172.2.31  raeburn  14912: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14913: 'role.request.course' must be defined for this function to proceed.
                   14914: 
                   14915: Inputs:
                   14916: 
                   14917: =over 4
                   14918: 
1.1172.2.31  raeburn  14919: =item $udom, student's domain
1.297     matthew  14920: 
1.1172.2.31  raeburn  14921: =item $uname, student's name
1.297     matthew  14922: 
1.1172.2.31  raeburn  14923: =item $uid, student's user id
1.297     matthew  14924: 
1.1172.2.31  raeburn  14925: =item $first, student's first name
1.297     matthew  14926: 
                   14927: =item $middle
                   14928: 
                   14929: =item $last
                   14930: 
                   14931: =item $gene
                   14932: 
                   14933: =item $usec
                   14934: 
                   14935: =item $end
                   14936: 
                   14937: =item $start
                   14938: 
1.957     raeburn  14939: =item $type
                   14940: 
                   14941: =item $locktype
                   14942: 
                   14943: =item $cid
                   14944: 
                   14945: =item $selfenroll
                   14946: 
                   14947: =item $context
                   14948: 
1.1172.2.19  raeburn  14949: =item $credits, number of credits student will earn from this class
                   14950: 
1.1172.2.76  raeburn  14951: =item $instsec, institutional course section code for student
                   14952: 
1.297     matthew  14953: =back
                   14954: 
1.191     harris41 14955: 
                   14956: =item *
                   14957: 
1.243     albertel 14958: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14959: custom role; give a custom role to a user for the level given by URL.  Specify
                   14960: name and domain of role author, and role name
1.191     harris41 14961: 
                   14962: =item *
                   14963: 
1.243     albertel 14964: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14965: 
                   14966: =item *
                   14967: 
1.243     albertel 14968: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14969: 
                   14970: =back
                   14971: 
                   14972: =head2 Course Infomation
                   14973: 
                   14974: =over 4
1.191     harris41 14975: 
                   14976: =item *
                   14977: 
1.1118    foxr     14978: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14979: specified course id, including all environment settings for the
                   14980: course, the description of the course will be in the hash under the
                   14981: key 'description'
1.191     harris41 14982: 
1.1118    foxr     14983: $options is an optional parameter that if supplied is a hash reference that controls
                   14984: what how this function works.  It has the following key/values:
                   14985: 
                   14986: =over 4
                   14987: 
                   14988: =item freshen_cache
                   14989: 
                   14990: If defined, and the environment cache for the course is valid, it is 
                   14991: returned in the returned hash.
                   14992: 
                   14993: =item one_time
                   14994: 
                   14995: If defined, the last cache time is set to _now_
                   14996: 
                   14997: =item user
                   14998: 
                   14999: If defined, the supplied username is used instead of the current user.
                   15000: 
                   15001: 
                   15002: =back
                   15003: 
1.191     harris41 15004: =item *
                   15005: 
1.624     albertel 15006: resdata($name,$domain,$type,@which) : request for current parameter
                   15007: setting for a specific $type, where $type is either 'course' or 'user',
                   15008: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15009: answers for 10 minutes.
1.243     albertel 15010: 
1.877     foxr     15011: =item *
                   15012: 
                   15013: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15014: data base, returning a hash that is keyed by the resource name and has
                   15015: values that are the resource value.  I believe that the timestamps and
                   15016: versions are also returned.
                   15017: 
1.1172.2.31  raeburn  15018: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15019: supplemental content area. This routine caches the number of files for
                   15020: 10 minutes.
                   15021: 
1.243     albertel 15022: =back
                   15023: 
                   15024: =head2 Course Modification
                   15025: 
                   15026: =over 4
1.191     harris41 15027: 
                   15028: =item *
                   15029: 
1.243     albertel 15030: writecoursepref($courseid,%prefs) : write preferences (environment
                   15031: database) for a course
1.191     harris41 15032: 
                   15033: =item *
                   15034: 
1.1011    raeburn  15035: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15036: 
                   15037: =item *
                   15038: 
1.1038    raeburn  15039: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15040: 
1.1167    droeschl 15041: =item *
                   15042: 
                   15043: is_course($courseid), is_course($cdom, $cnum)
                   15044: 
                   15045: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15046: two component version $cdom, $cnum. It checks if the specified course exists.
                   15047: 
                   15048: Returns:
                   15049:     undef if the course doesn't exist, otherwise
                   15050:     in scalar context the combined courseid.
                   15051:     in list context the two components of the course identifier, domain and 
                   15052:     courseid.    
                   15053: 
1.243     albertel 15054: =back
                   15055: 
1.1172.2.109  raeburn  15056: =head2 Bubblesheet Configuration
                   15057: 
                   15058: =over 4
                   15059: 
                   15060: =item *
                   15061: 
                   15062: get_scantron_config($which)
                   15063: 
                   15064: $which - the name of the configuration to parse from the file.
                   15065: 
                   15066: Parses and returns the bubblesheet configuration line selected as a
                   15067: hash of configuration file fields.
                   15068: 
                   15069: 
                   15070: Returns:
                   15071:     If the named configuration is not in the file, an empty
                   15072:     hash is returned.
                   15073: 
                   15074:     a hash with the fields
                   15075:       name         - internal name for the this configuration setup
                   15076:       description  - text to display to operator that describes this config
                   15077:       CODElocation - if 0 or the string 'none'
                   15078:                           - no CODE exists for this config
                   15079:                      if -1 || the string 'letter'
                   15080:                           - a CODE exists for this config and is
                   15081:                             a string of letters
                   15082:                      Unsupported value (but planned for future support)
                   15083:                           if a positive integer
                   15084:                                - The CODE exists as the first n items from
                   15085:                                  the question section of the form
                   15086:                           if the string 'number'
                   15087:                                - The CODE exists for this config and is
                   15088:                                  a string of numbers
                   15089:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15090:                      the CODE starts
                   15091:       CODElength  - length of the CODE
                   15092:       IDstart     - column where the student/employee ID starts
                   15093:       IDlength    - length of the student/employee ID info
                   15094:       Qstart      - column where the information from the bubbled
                   15095:                     'questions' start
                   15096:       Qlength     - number of columns comprising a single bubble line from
                   15097:                     the sheet. (usually either 1 or 10)
                   15098:       Qon         - either a single character representing the character used
                   15099:                     to signal a bubble was chosen in the positional setup, or
                   15100:                     the string 'letter' if the letter of the chosen bubble is
                   15101:                     in the final, or 'number' if a number representing the
                   15102:                     chosen bubble is in the file (1->A 0->J)
                   15103:       Qoff        - the character used to represent that a bubble was
                   15104:                     left blank
                   15105:       PaperID     - if the scanning process generates a unique number for each
                   15106:                     sheet scanned the column that this ID number starts in
                   15107:       PaperIDlength - number of columns that comprise the unique ID number
                   15108:                       for the sheet of paper
                   15109:       FirstName   - column that the first name starts in
                   15110:       FirstNameLength - number of columns that the first name spans
                   15111:       LastName    - column that the last name starts in
                   15112:       LastNameLength - number of columns that the last name spans
                   15113:       BubblesPerRow - number of bubbles available in each row used to
                   15114:                       bubble an answer. (If not specified, 10 assumed).
                   15115: 
                   15116: 
                   15117: =item *
                   15118: 
                   15119: get_scantronformat_file($cdom)
                   15120: 
                   15121: $cdom - the course's domain (optional); if not supplied, uses
                   15122: domain for current $env{'request.course.id'}.
                   15123: 
                   15124: Returns an array containing lines from the scantron format file for
                   15125: the domain of the course.
                   15126: 
                   15127: If a url for a custom.tab file is listed in domain's configuration.db,
                   15128: lines are from this file.
                   15129: 
                   15130: Otherwise, if a default.tab has been published in RES space by the
                   15131: domainconfig user, lines are from this file.
                   15132: 
                   15133: Otherwise, fall back to getting lines from the legacy file on the
                   15134: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15135: 
                   15136: =back
                   15137: 
1.243     albertel 15138: =head2 Resource Subroutines
                   15139: 
                   15140: =over 4
1.191     harris41 15141: 
                   15142: =item *
                   15143: 
1.243     albertel 15144: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15145: 
                   15146: =item *
                   15147: 
1.243     albertel 15148: repcopy($filename) : subscribes to the requested file, and attempts to
                   15149: replicate from the owning library server, Might return
1.607     raeburn  15150: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15151: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15152: resource. Expects the local filesystem pathname
                   15153: (/home/httpd/html/res/....)
                   15154: 
                   15155: =back
                   15156: 
                   15157: =head2 Resource Information
                   15158: 
                   15159: =over 4
1.191     harris41 15160: 
                   15161: =item *
                   15162: 
1.1172.2.28  raeburn  15163: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15164: and returns the value of a variety of different possible values,
                   15165: $varname should be a request string, and the other parameters can be
                   15166: used to specify who and what one is asking about. Ordinarily, $cid 
                   15167: does not need to be specified, as it is retrived from 
                   15168: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15169: within lonuserstate::loadmap() when initializing a course, before
                   15170: $env{'request.course.id'} has been set, so it needs to be provided
                   15171: in that one case.
1.243     albertel 15172: 
                   15173: Possible values for $varname are environment.lastname (or other item
                   15174: from the envirnment hash), user.name (or someother aspect about the
                   15175: user), resource.0.maxtries (or some other part and parameter of a
                   15176: resource)
1.204     albertel 15177: 
                   15178: =item *
                   15179: 
1.243     albertel 15180: directcondval($number) : get current value of a condition; reads from a state
                   15181: string
1.204     albertel 15182: 
                   15183: =item *
                   15184: 
1.243     albertel 15185: condval($condidx) : value of condition index based on state
1.204     albertel 15186: 
                   15187: =item *
                   15188: 
1.243     albertel 15189: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15190: resource's metadata, $what should be either a specific key, or either
                   15191: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15192: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15193: 
                   15194: this function automatically caches all requests
1.191     harris41 15195: 
                   15196: =item *
                   15197: 
1.243     albertel 15198: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15199: network of library servers; returns file handle of where SQL and regex results
                   15200: will be stored for query
1.191     harris41 15201: 
                   15202: =item *
                   15203: 
1.1172.2.66  raeburn  15204: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15205: return symbolic list entry (all arguments optional).
                   15206: 
                   15207: Args: filename is the filename (including path) for the file for which a symb
                   15208: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15209: to check access status if more than one resource was found in the bighash
                   15210: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15211: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15212: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15213: cause possible symbs to be checked to determine if they are subject to content
                   15214: blocking, if so they will not be included as possible symbs; possibles is a
                   15215: ref to a hash, which, as a side effect, will be populated with all possible
                   15216: symbs (content blocking not tested).
                   15217: 
1.243     albertel 15218: returns the data handle
1.191     harris41 15219: 
                   15220: =item *
                   15221: 
1.1172.2.17  raeburn  15222: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15223: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15224: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15225: on failure, user must be in a course, as it assumes the existence of
                   15226: the course initial hash, and uses $env('request.course.id'}.  The third
                   15227: arg is an optional reference to a scalar.  If this arg is passed in the
                   15228: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15229: encrypted; otherwise it will be null.
1.243     albertel 15230: 
1.191     harris41 15231: =item *
                   15232: 
1.243     albertel 15233: symbclean($symb) : removes versions numbers from a symb, returns the
                   15234: cleaned symb
1.191     harris41 15235: 
                   15236: =item *
                   15237: 
1.243     albertel 15238: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15239: course map, user must be in a course for it to work.
1.191     harris41 15240: 
                   15241: =item *
                   15242: 
1.243     albertel 15243: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15244: 
                   15245: =item *
                   15246: 
1.243     albertel 15247: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15248: a random seed, all arguments are optional, if they aren't sent it uses the
                   15249: environment to derive them. Note: if symb isn't sent and it can't get one
                   15250: from &symbread it will use the current time as its return value
1.191     harris41 15251: 
                   15252: =item *
                   15253: 
1.243     albertel 15254: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15255: unfakeable, receipt
1.191     harris41 15256: 
                   15257: =item *
                   15258: 
1.620     albertel 15259: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15260: 
                   15261: =item *
                   15262: 
1.243     albertel 15263: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15264: 
                   15265: =item *
                   15266: 
1.243     albertel 15267: 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 15268: 
                   15269: =item *
                   15270: 
1.243     albertel 15271: 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 15272: 
                   15273: =item *
                   15274: 
1.243     albertel 15275: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15276: 
                   15277: =item *
                   15278: 
1.243     albertel 15279: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15280: forcing spreadsheet to reevaluate the resource scores next time.
                   15281: 
1.1172.2.13  raeburn  15282: =item *
                   15283: 
                   15284: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15285: when viewing in course context.
                   15286: 
                   15287:  input: six args -- filename (decluttered), course number, course domain,
                   15288:                     url, symb (if registered) and group (if this is a
                   15289:                     group item -- e.g., bulletin board, group page etc.).
                   15290: 
                   15291:  output: array of five scalars --
                   15292:          $cfile -- url for file editing if editable on current server
                   15293:          $home -- homeserver of resource (i.e., for author if published,
                   15294:                                           or course if uploaded.).
                   15295:          $switchserver --  1 if server switch will be needed.
                   15296:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15297:          $forceview -- 1 if icon/link should be to go to view mode
                   15298: 
                   15299: =item *
                   15300: 
                   15301: is_course_upload($file,$cnum,$cdom)
                   15302: 
                   15303: Used in course context to determine if current file was uploaded to
                   15304: the course (i.e., would be found in /userfiles/docs on the course's
                   15305: homeserver.
                   15306: 
                   15307:   input: 3 args -- filename (decluttered), course number and course domain.
                   15308:   output: boolean -- 1 if file was uploaded.
                   15309: 
1.243     albertel 15310: =back
                   15311: 
                   15312: =head2 Storing/Retreiving Data
                   15313: 
                   15314: =over 4
1.191     harris41 15315: 
                   15316: =item *
                   15317: 
1.1172.2.64  raeburn  15318: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15319: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15320: the remaining args aren't required and if they aren't passed or are '' they will
                   15321: be derived from the env (with the exception of $laststore, which is an
                   15322: optional arg used when a user's submission is stored in grading).
                   15323: $laststore is $version=$timestamp, where $version is the most recent version
                   15324: number retrieved for the corresponding $symb in the $namespace db file, and
                   15325: $timestamp is the timestamp for that transaction (UNIX time).
                   15326: $laststore is currently only passed when cstore() is called by
                   15327: structuretags::finalize_storage().
1.191     harris41 15328: 
                   15329: =item *
                   15330: 
1.1172.2.64  raeburn  15331: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15332: but uses critical subroutine
1.191     harris41 15333: 
                   15334: =item *
                   15335: 
1.243     albertel 15336: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15337: all args are optional
1.191     harris41 15338: 
                   15339: =item *
                   15340: 
1.717     albertel 15341: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15342: dumps the complete (or key matching regexp) namespace into a hash
                   15343: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15344: normally &store()ed into
                   15345: 
                   15346: $range should be either an integer '100' (give me the first 100
                   15347:                                            matching records)
                   15348:               or be  two integers sperated by a - with no spaces
                   15349:                  '30-50' (give me the 30th through the 50th matching
                   15350:                           records)
                   15351: 
                   15352: 
                   15353: =item *
                   15354: 
1.1172.2.59  raeburn  15355: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15356: replaces a &store() version of data with a replacement set of data
                   15357: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15358: reference. If $tolog is true, the transaction is logged in the courselog
                   15359: with an action=PUTSTORE.
1.717     albertel 15360: 
                   15361: =item *
                   15362: 
1.243     albertel 15363: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15364: works very similar to store/cstore, but all data is stored in a
                   15365: temporary location and can be reset using tmpreset, $storehash should
                   15366: be a hash reference, returns nothing on success
1.191     harris41 15367: 
                   15368: =item *
                   15369: 
1.243     albertel 15370: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15371: similar to restore, but all data is stored in a temporary location and
                   15372: can be reset using tmpreset. Returns a hash of values on success,
                   15373: error string otherwise.
1.191     harris41 15374: 
                   15375: =item *
                   15376: 
1.243     albertel 15377: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15378: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15379: 
                   15380: =item *
                   15381: 
1.243     albertel 15382: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15383: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15384: 
                   15385: =item *
                   15386: 
1.243     albertel 15387: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15388: namesp ($udom and $uname are optional)
1.191     harris41 15389: 
                   15390: =item *
                   15391: 
1.702     albertel 15392: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15393: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15394: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15395: 
1.702     albertel 15396: $range should be either an integer '100' (give me the first 100
                   15397:                                            matching records)
                   15398:               or be  two integers sperated by a - with no spaces
                   15399:                  '30-50' (give me the 30th through the 50th matching
                   15400:                           records)
1.449     matthew  15401: =item *
                   15402: 
                   15403: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15404: $store can be a scalar, an array reference, or if the amount to be 
                   15405: incremented is > 1, a hash reference.
                   15406: 
                   15407: ($udom and $uname are optional)
1.191     harris41 15408: 
                   15409: =item *
                   15410: 
1.243     albertel 15411: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15412: ($udom and $uname are optional)
1.191     harris41 15413: 
                   15414: =item *
                   15415: 
1.243     albertel 15416: cput($namespace,$storehash,$udom,$uname) : critical put
                   15417: ($udom and $uname are optional)
1.191     harris41 15418: 
                   15419: =item *
                   15420: 
1.748     albertel 15421: newput($namespace,$storehash,$udom,$uname) :
                   15422: 
                   15423: Attempts to store the items in the $storehash, but only if they don't
                   15424: currently exist, if this succeeds you can be certain that you have 
                   15425: successfully created a new key value pair in the $namespace db.
                   15426: 
                   15427: 
                   15428: Args:
                   15429:  $namespace: name of database to store values to
                   15430:  $storehash: hashref to store to the db
                   15431:  $udom: (optional) domain of user containing the db
                   15432:  $uname: (optional) name of user caontaining the db
                   15433: 
                   15434: Returns:
                   15435:  'ok' -> succeeded in storing all keys of $storehash
                   15436:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15437:                         least <key> already existed in the db (other
                   15438:                         requested keys may also already exist)
1.967     bisitz   15439:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15440:  'con_lost' -> unable to contact request server
                   15441:  'refused' -> action was not allowed by remote machine
                   15442: 
                   15443: 
                   15444: =item *
                   15445: 
1.243     albertel 15446: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15447: reference filled in from namesp (encrypts the return communication)
                   15448: ($udom and $uname are optional)
1.191     harris41 15449: 
                   15450: =item *
                   15451: 
1.243     albertel 15452: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15453: critical subroutine
                   15454: 
1.806     raeburn  15455: =item *
                   15456: 
1.860     raeburn  15457: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15458: array reference filled in from namespace found in domain level on either
                   15459: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15460: 
                   15461: =item *
                   15462: 
1.860     raeburn  15463: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15464: domain level either on specified domain server ($uhome) or primary domain 
                   15465: server ($udom and $uhome are optional)
1.806     raeburn  15466: 
1.943     raeburn  15467: =item * 
                   15468: 
1.1172.2.35  raeburn  15469: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15470: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15471: the target domain.
                   15472: 
                   15473: May also include additional key => value pairs for the following groups:
                   15474: 
                   15475: =over
                   15476: 
                   15477: =item
                   15478: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15479: 
                   15480: =over
                   15481: 
                   15482: =item defaultquota, authorquota
                   15483: 
                   15484: =back
                   15485: 
                   15486: =item
                   15487: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15488: portfolio for users).
                   15489: 
                   15490: =over
                   15491: 
                   15492: =item
                   15493: aboutme, blog, webdav, portfolio
                   15494: 
                   15495: =back
                   15496: 
                   15497: =item
                   15498: requestcourses: ability to request courses, and how requests are processed.
                   15499: 
                   15500: =over
                   15501: 
                   15502: =item
1.1172.2.37  raeburn  15503: official, unofficial, community, textbook
1.1172.2.35  raeburn  15504: 
                   15505: =back
                   15506: 
                   15507: =item
                   15508: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15509: 
                   15510: =over
                   15511: 
                   15512: =item
1.1172.2.44  raeburn  15513: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15514: 
                   15515: =back
                   15516: 
                   15517: =item
                   15518: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15519: for course's uploaded content.
                   15520: 
                   15521: =over
                   15522: 
                   15523: =item
1.1172.2.68  raeburn  15524: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15525: communityquota, textbookquota
1.1172.2.35  raeburn  15526: 
                   15527: =back
                   15528: 
                   15529: =item
                   15530: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15531: on your servers.
                   15532: 
                   15533: =over
                   15534: 
                   15535: =item
                   15536: remotesessions, hostedsessions
                   15537: 
                   15538: =back
                   15539: 
                   15540: =back
                   15541: 
                   15542: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15543: utility to create a configuration.db file on a domain's primary library server
                   15544: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15545: -- corresponding values are authentication type (internal, krb4, krb5,
                   15546: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15547: will be available. Values are retrieved from cache (if current), unless the
                   15548: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15549: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15550: 
                   15551: Typical usage:
1.943     raeburn  15552: 
1.1172.2.35  raeburn  15553: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15554: 
1.243     albertel 15555: =back
                   15556: 
                   15557: =head2 Network Status Functions
                   15558: 
                   15559: =over 4
1.191     harris41 15560: 
                   15561: =item *
                   15562: 
1.1137    raeburn  15563: dirlist() : return directory list based on URI (first arg).
                   15564: 
                   15565: Inputs: 1 required, 5 optional.
                   15566: 
                   15567: =over
                   15568: 
                   15569: =item 
                   15570: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15571: 
                   15572: =item
                   15573: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15574: 
                   15575: =item
                   15576: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15577: 
                   15578: =item
                   15579: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15580: 
                   15581: =item
                   15582: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15583: 
                   15584: =item 
                   15585: $alternateRoot - path to prepend in place of path from $uri.
                   15586: 
                   15587: =back
                   15588: 
                   15589: Returns: Array of up to two items.
                   15590: 
                   15591: =over
                   15592: 
                   15593: a reference to an array of files/subdirectories
                   15594: 
                   15595: =over
                   15596: 
                   15597: Each element in the array of files/subdirectories is a & separated list of
                   15598: item name and the result of running stat on the item.  If dirlist was requested
                   15599: for a file instead of a directory, the item name will be ''. For a directory 
                   15600: listing, if the item is a metadata file, the element will end &N&M 
                   15601: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15602: default copyright set (1).  
                   15603: 
                   15604: =back
                   15605: 
                   15606: a scalar containing error condition (if encountered).
                   15607: 
                   15608: =over
                   15609: 
                   15610: =item 
                   15611: no_host (no homeserver identified for $username:$domain).
                   15612: 
                   15613: =item 
                   15614: no_such_host (server contacted for listing not identified as valid host).
                   15615: 
                   15616: =item 
                   15617: con_lost (connection to remote server failed).
                   15618: 
                   15619: =item 
                   15620: refused (invalid $username:$domain received on lond side).
                   15621: 
                   15622: =item 
                   15623: no_such_dir (directory at specified path on lond side does not exist). 
                   15624: 
                   15625: =item 
                   15626: empty (directory at specified path on lond side is empty).
                   15627: 
                   15628: =over
                   15629: 
                   15630: This is currently not encountered because the &ls3, &ls2, 
                   15631: &ls (_handler) routines on the lond side do not filter out
                   15632: . and .. from a directory listing. 
                   15633: 
                   15634: =back
                   15635: 
                   15636: =back
                   15637: 
                   15638: =back
1.191     harris41 15639: 
                   15640: =item *
                   15641: 
1.243     albertel 15642: spareserver() : find server with least workload from spare.tab
                   15643: 
1.986     foxr     15644: 
                   15645: =item *
                   15646: 
                   15647: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15648: if there is no corresponding loncapa host.
                   15649: 
1.243     albertel 15650: =back
                   15651: 
1.986     foxr     15652: 
1.243     albertel 15653: =head2 Apache Request
                   15654: 
                   15655: =over 4
1.191     harris41 15656: 
                   15657: =item *
                   15658: 
1.243     albertel 15659: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15660: localhost, posts hash
                   15661: 
                   15662: =back
                   15663: 
                   15664: =head2 Data to String to Data
                   15665: 
                   15666: =over 4
1.191     harris41 15667: 
                   15668: =item *
                   15669: 
1.243     albertel 15670: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15671: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15672: 
                   15673: =item *
                   15674: 
1.243     albertel 15675: hashref2str($hashref) : convert a hashref into a string complete with
                   15676: escaping and '=' and '&' separators, supports elements that are
                   15677: arrayrefs and hashrefs
1.191     harris41 15678: 
                   15679: =item *
                   15680: 
1.243     albertel 15681: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15682: with escaping and '&' separators, supports elements that are arrayrefs
                   15683: and hashrefs
1.191     harris41 15684: 
                   15685: =item *
                   15686: 
1.243     albertel 15687: str2hash($string) : convert string to hash using unescaping and
                   15688: splitting on '=' and '&', supports elements that are arrayrefs and
                   15689: hashrefs
1.191     harris41 15690: 
                   15691: =item *
                   15692: 
1.243     albertel 15693: str2array($string) : convert string to hash using unescaping and
                   15694: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15695: 
                   15696: =back
                   15697: 
                   15698: =head2 Logging Routines
                   15699: 
                   15700: 
                   15701: These routines allow one to make log messages in the lonnet.log and
                   15702: lonnet.perm logfiles.
1.191     harris41 15703: 
1.1119    foxr     15704: =over 4
                   15705: 
1.191     harris41 15706: =item *
                   15707: 
1.243     albertel 15708: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15709: 
                   15710: =item *
                   15711: 
1.243     albertel 15712: logthis() : append message to the normal lonnet.log file, it gets
                   15713: preiodically rolled over and deleted.
1.191     harris41 15714: 
                   15715: =item *
                   15716: 
1.243     albertel 15717: logperm() : append a permanent message to lonnet.perm.log, this log
                   15718: file never gets deleted by any automated portion of the system, only
                   15719: messages of critical importance should go in here.
                   15720: 
1.1119    foxr     15721: 
1.243     albertel 15722: =back
                   15723: 
                   15724: =head2 General File Helper Routines
                   15725: 
                   15726: =over 4
1.191     harris41 15727: 
                   15728: =item *
                   15729: 
1.481     raeburn  15730: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15731: (a) files in /uploaded
                   15732:   (i) If a local copy of the file exists - 
                   15733:       compares modification date of local copy with last-modified date for 
                   15734:       definitive version stored on home server for course. If local copy is 
                   15735:       stale, requests a new version from the home server and stores it. 
                   15736:       If the original has been removed from the home server, then local copy 
                   15737:       is unlinked.
                   15738:   (ii) If local copy does not exist -
                   15739:       requests the file from the home server and stores it. 
                   15740:   
                   15741:   If $caller is 'uploadrep':  
                   15742:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15743:     for request for files originally uploaded via DOCS. 
                   15744:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15745:   
                   15746:   Otherwise:
                   15747:      This indicates a call from the content generation phase of the request.
                   15748:      -  returns the entire contents of the file or -1.
                   15749:      
                   15750: (b) files in /res
                   15751:    - returns the entire contents of a file or -1; 
                   15752:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15753: 
1.712     albertel 15754: 
                   15755: =item *
                   15756: 
                   15757: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15758:                   reference
                   15759: 
                   15760: returns either a stat() list of data about the file or an empty list
                   15761: if the file doesn't exist or couldn't find out about it (connection
                   15762: problems or user unknown)
                   15763: 
1.191     harris41 15764: =item *
                   15765: 
1.243     albertel 15766: filelocation($dir,$file) : returns file system location of a file
                   15767: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15768: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15769: and a file of ../bob will become /a/bob)
1.191     harris41 15770: 
                   15771: =item *
                   15772: 
                   15773: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15774: filelocation except for hrefs
                   15775: 
                   15776: =item *
                   15777: 
1.1172.2.49  raeburn  15778: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15779: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15780: 
1.243     albertel 15781: =back
                   15782: 
1.608     albertel 15783: =head2 Usererfile file routines (/uploaded*)
                   15784: 
                   15785: =over 4
                   15786: 
                   15787: =item *
                   15788: 
                   15789: userfileupload(): main rotine for putting a file in a user or course's
                   15790:                   filespace, arguments are,
                   15791: 
1.620     albertel 15792:  formname - required - this is the name of the element in $env where the
1.608     albertel 15793:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15794:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15795:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15796:  context - if coursedoc, store the file in the course of the active role
                   15797:              of the current user; 
                   15798:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15799:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15800:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15801:          if undefined, it will be placed in "unknown"
                   15802: 
                   15803:  (This routine calls clean_filename() to remove any dangerous
                   15804:  characters from the filename, and then calls finuserfileupload() to
                   15805:  complete the transaction)
                   15806: 
                   15807:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15808:  and /adm/notfound.html if unsuccessful
                   15809: 
                   15810: =item *
                   15811: 
                   15812: clean_filename(): routine for cleaing a filename up for storage in
                   15813:                  userfile space, argument is:
                   15814: 
                   15815:  filename - proposed filename
                   15816: 
                   15817: returns: the new clean filename
                   15818: 
                   15819: =item *
                   15820: 
1.1090    raeburn  15821: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15822: userspace, probably shouldn't be called directly
                   15823: 
                   15824:   docuname: username or courseid of destination for the file
                   15825:   docudom: domain of user/course of destination for the file
                   15826:   formname: same as for userfileupload()
1.1090    raeburn  15827:   fname: filename (including subdirectories) for the file
                   15828:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15829:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15830:   allfiles: reference to hash used to store objects found by parser
                   15831:   codebase: reference to hash used for codebases of java objects found by parser
                   15832:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15833:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15834:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15835:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15836:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15837:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15838:   mimetype: reference to scalar to accommodate mime type determined
                   15839:             from File::MMagic if $parser = parse.
1.608     albertel 15840: 
                   15841:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15842:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15843:  was 'overwrite').
                   15844:  
1.608     albertel 15845: 
                   15846: =item *
                   15847: 
                   15848: renameuserfile(): renames an existing userfile to a new name
                   15849: 
                   15850:   Args:
                   15851:    docuname: username or courseid of destination for the file
                   15852:    docudom: domain of user/course of destination for the file
                   15853:    old: current file name (including any subdirs under userfiles)
                   15854:    new: desired file name (including any subdirs under userfiles)
                   15855: 
                   15856: =item *
                   15857: 
                   15858: mkdiruserfile(): creates a directory is a userfiles dir
                   15859: 
                   15860:   Args:
                   15861:    docuname: username or courseid of destination for the file
                   15862:    docudom: domain of user/course of destination for the file
                   15863:    dir: dir to create (including any subdirs under userfiles)
                   15864: 
                   15865: =item *
                   15866: 
                   15867: removeuserfile(): removes a file that exists in userfiles
                   15868: 
                   15869:   Args:
                   15870:    docuname: username or courseid of destination for the file
                   15871:    docudom: domain of user/course of destination for the file
                   15872:    fname: filname to delete (including any subdirs under userfiles)
                   15873: 
                   15874: =item *
                   15875: 
                   15876: removeuploadedurl(): convience function for removeuserfile()
                   15877: 
                   15878:   Args:
                   15879:    url:  a full /uploaded/... url to delete
                   15880: 
1.747     albertel 15881: =item * 
                   15882: 
                   15883: get_portfile_permissions():
                   15884:   Args:
                   15885:     domain: domain of user or course contain the portfolio files
                   15886:     user: name of user or num of course contain the portfolio files
                   15887:   Returns:
                   15888:     hashref of a dump of the proper file_permissions.db
                   15889:    
                   15890: 
                   15891: =item * 
                   15892: 
                   15893: get_access_controls():
                   15894: 
                   15895: Args:
                   15896:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15897:   group: (optional) the group you want the files associated with
                   15898:   file: (optional) the file you want access info on
                   15899: 
                   15900: Returns:
1.749     raeburn  15901:     a hash (keys are file names) of hashes containing
                   15902:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15903:         values are XML containing access control settings (see below) 
1.747     albertel 15904: 
                   15905: Internal notes:
                   15906: 
1.749     raeburn  15907:  access controls are stored in file_permissions.db as key=value pairs.
                   15908:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15909:         where scope -> public,guest,course,group,domains or users.
                   15910:               end -> UNIX time for end of access (0 -> no end date)
                   15911:               start -> UNIX time for start of access
                   15912: 
                   15913:     value -> XML description of access control
                   15914:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15915:             <start></start>
                   15916:             <end></end>
                   15917: 
                   15918:             <password></password>  for scope type = guest
                   15919: 
                   15920:             <domain></domain>     for scope type = course or group
                   15921:             <number></number>
                   15922:             <roles id="">
                   15923:              <role></role>
                   15924:              <access></access>
                   15925:              <section></section>
                   15926:              <group></group>
                   15927:             </roles>
                   15928: 
                   15929:             <dom></dom>         for scope type = domains
                   15930: 
                   15931:             <users>             for scope type = users
                   15932:              <user>
                   15933:               <uname></uname>
                   15934:               <udom></udom>
                   15935:              </user>
                   15936:             </users>
                   15937:            </scope> 
                   15938:               
                   15939:  Access data is also aggregated for each file in an additional key=value pair:
                   15940:  key -> path to file/file_name\0accesscontrol 
                   15941:  value -> reference to hash
                   15942:           hash contains key = value pairs
                   15943:           where key = uniqueID:scope_end_start
                   15944:                 value = UNIX time record was last updated
                   15945: 
                   15946:           Used to improve speed of look-ups of access controls for each file.  
                   15947:  
                   15948:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15949: 
1.1172.2.13  raeburn  15950: =item *
                   15951: 
1.749     raeburn  15952: modify_access_controls():
                   15953: 
                   15954: Modifies access controls for a portfolio file
                   15955: Args
                   15956: 1. file name
                   15957: 2. reference to hash of required changes,
                   15958: 3. domain
                   15959: 4. username
                   15960:   where domain,username are the domain of the portfolio owner 
                   15961:   (either a user or a course) 
                   15962: 
                   15963: Returns:
                   15964: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15965: 2. result of deletions ('ok' or 'error', with error message).
                   15966: 3. reference to hash of any new or updated access controls.
                   15967: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15968:    key = integer (inbound ID)
1.1172.2.13  raeburn  15969:    value = uniqueID
                   15970: 
                   15971: =item *
                   15972: 
                   15973: get_timebased_id():
                   15974: 
                   15975: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15976: course via the Course Editor (e.g., folders, composite pages,
                   15977: group bulletin boards).
                   15978: 
                   15979: Args: (first three required; six others optional)
                   15980: 
                   15981: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15982:    docssequence, or name of group
                   15983: 
                   15984: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15985:    e.g., num, boardids
                   15986: 
                   15987: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15988:    file will be named nohist_namespace.db
                   15989: 
                   15990: 4. cdom: domain of course; default is current course domain from %env
                   15991: 
                   15992: 5. cnum: course number; default is current course number from %env
                   15993: 
                   15994: 6. idtype: set to concat if an additional digit is to be appended to the
                   15995:    unix timestamp to form the suffix, if the plain timestamp is already
                   15996:    in use.  Default is to not do this, but simply increment the unix
                   15997:    timestamp by 1 until a unique key is obtained.
                   15998: 
                   15999: 7. who: holder of locking key; defaults to user:domain for user.
                   16000: 
                   16001: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16002:    retrying); default is 3.
                   16003: 
                   16004: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16005: 
                   16006: Returns:
                   16007: 
                   16008: 1. suffix obtained (numeric)
                   16009: 
                   16010: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16011: 
                   16012: 3. error: contains (localized) error message if an error occurred.
                   16013: 
1.747     albertel 16014: 
1.608     albertel 16015: =back
                   16016: 
1.243     albertel 16017: =head2 HTTP Helper Routines
                   16018: 
                   16019: =over 4
                   16020: 
1.191     harris41 16021: =item *
                   16022: 
                   16023: escape() : unpack non-word characters into CGI-compatible hex codes
                   16024: 
                   16025: =item *
                   16026: 
                   16027: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16028: 
1.243     albertel 16029: =back
                   16030: 
                   16031: =head1 PRIVATE SUBROUTINES
                   16032: 
                   16033: =head2 Underlying communication routines (Shouldn't call)
                   16034: 
                   16035: =over 4
                   16036: 
                   16037: =item *
                   16038: 
                   16039: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16040: 
                   16041: =item *
                   16042: 
                   16043: reply() : uses subreply to send a message to remote machine, logs all failures
                   16044: 
                   16045: =item *
                   16046: 
                   16047: critical() : passes a critical message to another server; if cannot
                   16048: get through then place message in connection buffer directory and
                   16049: returns con_delayed, if incapable of saving message, returns
                   16050: con_failed
                   16051: 
                   16052: =item *
                   16053: 
                   16054: reconlonc() : tries to reconnect lonc client processes.
                   16055: 
                   16056: =back
                   16057: 
                   16058: =head2 Resource Access Logging
                   16059: 
                   16060: =over 4
                   16061: 
                   16062: =item *
                   16063: 
                   16064: flushcourselogs() : flush (save) buffer logs and access logs
                   16065: 
                   16066: =item *
                   16067: 
                   16068: courselog($what) : save message for course in hash
                   16069: 
                   16070: =item *
                   16071: 
                   16072: courseacclog($what) : save message for course using &courselog().  Perform
                   16073: special processing for specific resource types (problems, exams, quizzes, etc).
                   16074: 
1.191     harris41 16075: =item *
                   16076: 
                   16077: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16078: as a PerlChildExitHandler
1.243     albertel 16079: 
                   16080: =back
                   16081: 
                   16082: =head2 Other
                   16083: 
                   16084: =over 4
                   16085: 
                   16086: =item *
                   16087: 
                   16088: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16089: 
                   16090: =back
                   16091: 
                   16092: =cut
1.877     foxr     16093: 

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