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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1182  ! foxr        4: # $Id: lonnet.pm,v 1.1181 2012/07/21 21:20:12 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;
                     77: 
1.1182  ! foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.871     albertel   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1       albertel  116: # --------------------------------------------------------------------- Logging
1.729     www       117: {
                    118:     my $logid;
                    119:     sub instructor_log {
1.957     raeburn   120: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if (($cnum eq '') || ($cdom eq '')) {
                    122:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    123:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    124:         }
1.729     www       125: 	$logid++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       128: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       129: 				    { $id => {
                    130: 					'exe_uname' => $env{'user.name'},
                    131: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   132: 					'exe_time'  => $now,
1.730     www       133: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134: 					'delflag'   => $delflag,
                    135: 					'logentry'  => $storehash,
                    136: 					'uname'     => $uname,
                    137: 					'udom'      => $udom,
                    138: 				    }
1.957     raeburn   139: 				  },$cdom,$cnum);
1.729     www       140:     }
                    141: }
1.1       albertel  142: 
1.163     harris41  143: sub logtouch {
                    144:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  145:     unless (-e "$execdir/logs/lonnet.log") {	
                    146: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  147: 	close $fh;
                    148:     }
                    149:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    150:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    151: }
                    152: 
1.1       albertel  153: sub logthis {
                    154:     my $message=shift;
                    155:     my $execdir=$perlvar{'lonDaemons'};
                    156:     my $now=time;
                    157:     my $local=localtime($now);
1.448     albertel  158:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      159: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    160: 	print $fh $logstring;
1.448     albertel  161: 	close($fh);
                    162:     }
1.1       albertel  163:     return 1;
                    164: }
                    165: 
                    166: sub logperm {
                    167:     my $message=shift;
                    168:     my $execdir=$perlvar{'lonDaemons'};
                    169:     my $now=time;
                    170:     my $local=localtime($now);
1.448     albertel  171:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    172: 	print $fh "$now:$message:$local\n";
                    173: 	close($fh);
                    174:     }
1.1       albertel  175:     return 1;
                    176: }
                    177: 
1.850     albertel  178: sub create_connection {
1.853     albertel  179:     my ($hostname,$lonid) = @_;
1.851     albertel  180:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  181: 				     Type    => SOCK_STREAM,
                    182: 				     Timeout => 10);
                    183:     return 0 if (!$client);
1.890     albertel  184:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  185:     my $result = <$client>;
                    186:     chomp($result);
                    187:     return 1 if ($result eq 'done');
                    188:     return 0;
                    189: }
                    190: 
1.983     raeburn   191: sub get_server_timezone {
                    192:     my ($cnum,$cdom) = @_;
                    193:     my $home=&homeserver($cnum,$cdom);
                    194:     if ($home ne 'no_host') {
                    195:         my $cachetime = 24*3600;
                    196:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    197:         if (defined($cached)) {
                    198:             return $timezone;
                    199:         } else {
                    200:             my $timezone = &reply('servertimezone',$home);
                    201:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    202:         }
                    203:     }
                    204: }
1.850     albertel  205: 
1.1106    raeburn   206: sub get_server_distarch {
                    207:     my ($lonhost,$ignore_cache) = @_;
                    208:     if (defined($lonhost)) {
                    209:         if (!defined(&hostname($lonhost))) {
                    210:             return;
                    211:         }
                    212:         my $cachetime = 12*3600;
                    213:         if (!$ignore_cache) {
                    214:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    215:             if (defined($cached)) {
                    216:                 return $distarch;
                    217:             }
                    218:         }
                    219:         my $rep = &reply('serverdistarch',$lonhost);
                    220:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    221:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    222:                 $rep eq '') {
                    223:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    224:         }
                    225:     }
                    226:     return;
                    227: }
                    228: 
1.993     raeburn   229: sub get_server_loncaparev {
1.1073    raeburn   230:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   231:     if (defined($lonhost)) {
                    232:         if (!defined(&hostname($lonhost))) {
                    233:             undef($lonhost);
                    234:         }
                    235:     }
                    236:     if (!defined($lonhost)) {
                    237:         if (defined(&domain($dom,'primary'))) {
                    238:             $lonhost=&domain($dom,'primary');
                    239:             if ($lonhost eq 'no_host') {
                    240:                 undef($lonhost);
                    241:             }
                    242:         }
                    243:     }
                    244:     if (defined($lonhost)) {
1.1073    raeburn   245:         my $cachetime = 12*3600;
                    246:         if (!$ignore_cache) {
                    247:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    248:             if (defined($cached)) {
                    249:                 return $loncaparev;
                    250:             }
                    251:         }
                    252:         my ($answer,$loncaparev);
                    253:         my @ids=&current_machine_ids();
                    254:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    255:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   256:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   257:                 $loncaparev = $1;
                    258:             }
                    259:         } else {
                    260:             $answer = &reply('serverloncaparev',$lonhost);
                    261:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    262:                 if ($caller eq 'loncron') {
                    263:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   264:                     $ua->timeout(4);
1.1073    raeburn   265:                     my $protocol = $protocol{$lonhost};
                    266:                     $protocol = 'http' if ($protocol ne 'https');
                    267:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    268:                     my $request=new HTTP::Request('GET',$url);
                    269:                     my $response=$ua->request($request);
                    270:                     unless ($response->is_error()) {
                    271:                         my $content = $response->content;
1.1081    raeburn   272:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   273:                             $loncaparev = $1;
                    274:                         }
                    275:                     }
                    276:                 } else {
                    277:                     $loncaparev = $loncaparevs{$lonhost};
                    278:                 }
1.1081    raeburn   279:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   280:                 $loncaparev = $1;
                    281:             }
1.993     raeburn   282:         }
1.1073    raeburn   283:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   284:     }
                    285: }
                    286: 
1.1074    raeburn   287: sub get_server_homeID {
                    288:     my ($hostname,$ignore_cache,$caller) = @_;
                    289:     unless ($ignore_cache) {
                    290:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    291:         if (defined($cached)) {
                    292:             return $serverhomeID;
                    293:         }
                    294:     }
                    295:     my $cachetime = 12*3600;
                    296:     my $serverhomeID;
                    297:     if ($caller eq 'loncron') { 
                    298:         my @machine_ids = &machine_ids($hostname);
                    299:         foreach my $id (@machine_ids) {
                    300:             my $response = &reply('serverhomeID',$id);
                    301:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    302:                 $serverhomeID = $response;
                    303:                 last;
                    304:             }
                    305:         }
                    306:         if ($serverhomeID eq '') {
                    307:             $serverhomeID = $machine_ids[-1];
                    308:         }
                    309:     } else {
                    310:         $serverhomeID = $serverhomeIDs{$hostname};
                    311:     }
                    312:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    313: }
                    314: 
1.1121    raeburn   315: sub get_remote_globals {
                    316:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   317:     my ($result,%returnhash,%whatneeded);
                    318:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   319:         foreach my $what (sort(keys(%{$whathash}))) {
                    320:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   321:             my ($response,$cached);
1.1121    raeburn   322:             unless ($ignore_cache) {
1.1125    raeburn   323:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   324:             }
                    325:             if (defined($cached)) {
1.1125    raeburn   326:                 $returnhash{$what} = $response;
1.1121    raeburn   327:             } else {
1.1125    raeburn   328:                 $whatneeded{$what} = 1;
1.1121    raeburn   329:             }
                    330:         }
1.1125    raeburn   331:         if (keys(%whatneeded) == 0) {
                    332:             $result = 'ok';
                    333:         } else {
1.1121    raeburn   334:             my $requested = &freeze_escape(\%whatneeded);
                    335:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   336:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    337:                 ($rep eq 'unknown_cmd')) {
                    338:                 $result = $rep;
                    339:             } else {
                    340:                 $result = 'ok';
1.1121    raeburn   341:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   342:                 foreach my $item (@pairs) {
                    343:                     my ($key,$value)=split(/=/,$item,2);
                    344:                     my $what = &unescape($key);
                    345:                     my $hashid = $lonhost.'-'.$what;
                    346:                     $returnhash{$what}=&thaw_unescape($value);
                    347:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   348:                 }
                    349:             }
                    350:         }
                    351:     }
1.1125    raeburn   352:     return ($result,\%returnhash);
1.1121    raeburn   353: }
                    354: 
1.1124    raeburn   355: sub remote_devalidate_cache {
                    356:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   357:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   358:     return $response;
                    359: }
                    360: 
1.1       albertel  361: # -------------------------------------------------- Non-critical communication
                    362: sub subreply {
                    363:     my ($cmd,$server)=@_;
1.838     albertel  364:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      365:     #
                    366:     #  With loncnew process trimming, there's a timing hole between lonc server
                    367:     #  process exit and the master server picking up the listen on the AF_UNIX
                    368:     #  socket.  In that time interval, a lock file will exist:
                    369: 
                    370:     my $lockfile=$peerfile.".lock";
                    371:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    372: 	sleep(1);
                    373:     }
                    374:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      375:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      376:     #
1.550     foxr      377:     #   We'll give the connection a few tries before abandoning it.  If
                    378:     #   connection is not possible, we'll con_lost back to the client.
                    379:     #   
                    380:     my $client;
                    381:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    382: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    383: 				      Type    => SOCK_STREAM,
                    384: 				      Timeout => 10);
1.869     albertel  385: 	if ($client) {
1.550     foxr      386: 	    last;		# Connected!
1.850     albertel  387: 	} else {
1.853     albertel  388: 	    &create_connection(&hostname($server),$server);
1.550     foxr      389: 	}
1.850     albertel  390:         sleep(1);		# Try again later if failed connection.
1.550     foxr      391:     }
                    392:     my $answer;
                    393:     if ($client) {
1.704     albertel  394: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      395: 	$answer=<$client>;
                    396: 	if (!$answer) { $answer="con_lost"; }
                    397: 	chomp($answer);
                    398:     } else {
                    399: 	$answer = 'con_lost';	# Failed connection.
                    400:     }
1.1       albertel  401:     return $answer;
                    402: }
                    403: 
                    404: sub reply {
                    405:     my ($cmd,$server)=@_;
1.838     albertel  406:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  407:     my $answer=subreply($cmd,$server);
1.65      www       408:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  409:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       410:                 " $cmd to $server returned $answer</font>");
                    411:     }
1.1       albertel  412:     return $answer;
                    413: }
                    414: 
                    415: # ----------------------------------------------------------- Send USR1 to lonc
                    416: 
                    417: sub reconlonc {
1.891     albertel  418:     my ($lonid) = @_;
                    419:     my $hostname = &hostname($lonid);
                    420:     if ($lonid) {
                    421: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    422: 	if ($hostname && -e $peerfile) {
                    423: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    424: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    425: 					     Type    => SOCK_STREAM,
                    426: 					     Timeout => 10);
                    427: 	    if ($client) {
                    428: 		print $client ("reset_retries\n");
                    429: 		my $answer=<$client>;
                    430: 		#reset just this one.
                    431: 	    }
                    432: 	}
                    433: 	return;
                    434:     }
                    435: 
1.836     www       436:     &logthis("Trying to reconnect lonc");
1.1       albertel  437:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  438:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  439: 	my $loncpid=<$fh>;
                    440:         chomp($loncpid);
                    441:         if (kill 0 => $loncpid) {
                    442: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    443:             kill USR1 => $loncpid;
                    444:             sleep 1;
1.836     www       445:          } else {
1.12      www       446: 	    &logthis(
1.672     albertel  447:                "<font color=\"blue\">WARNING:".
1.12      www       448:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  449:         }
                    450:     } else {
1.836     www       451: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  452:     }
                    453: }
                    454: 
                    455: # ------------------------------------------------------ Critical communication
1.12      www       456: 
1.1       albertel  457: sub critical {
                    458:     my ($cmd,$server)=@_;
1.838     albertel  459:     unless (&hostname($server)) {
1.672     albertel  460:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       461:                " Critical message to unknown server ($server)</font>");
                    462:         return 'no_such_host';
                    463:     }
1.1       albertel  464:     my $answer=reply($cmd,$server);
                    465:     if ($answer eq 'con_lost') {
                    466: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  467: 	my $answer=reply($cmd,$server);
1.1       albertel  468:         if ($answer eq 'con_lost') {
                    469:             my $now=time;
                    470:             my $middlename=$cmd;
1.5       www       471:             $middlename=substr($middlename,0,16);
1.1       albertel  472:             $middlename=~s/\W//g;
                    473:             my $dfilename=
1.305     www       474:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    475:             $dumpcount++;
1.1       albertel  476:             {
1.448     albertel  477: 		my $dfh;
                    478: 		if (open($dfh,">$dfilename")) {
                    479: 		    print $dfh "$cmd\n"; 
                    480: 		    close($dfh);
                    481: 		}
1.1       albertel  482:             }
                    483:             sleep 2;
                    484:             my $wcmd='';
                    485:             {
1.448     albertel  486: 		my $dfh;
                    487: 		if (open($dfh,"<$dfilename")) {
                    488: 		    $wcmd=<$dfh>; 
                    489: 		    close($dfh);
                    490: 		}
1.1       albertel  491:             }
                    492:             chomp($wcmd);
1.7       www       493:             if ($wcmd eq $cmd) {
1.672     albertel  494: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       495:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  496:                 &logperm("D:$server:$cmd");
                    497: 	        return 'con_delayed';
                    498:             } else {
1.672     albertel  499:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       500:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  501:                 &logperm("F:$server:$cmd");
                    502:                 return 'con_failed';
                    503:             }
                    504:         }
                    505:     }
                    506:     return $answer;
1.405     albertel  507: }
                    508: 
1.755     albertel  509: # ------------------------------------------- check if return value is an error
                    510: 
                    511: sub error {
                    512:     my ($result) = @_;
1.756     albertel  513:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  514: 	if ($2 == 2) { return undef; }
                    515: 	return $1;
                    516:     }
                    517:     return undef;
                    518: }
                    519: 
1.783     albertel  520: sub convert_and_load_session_env {
                    521:     my ($lonidsdir,$handle)=@_;
                    522:     my @profile;
                    523:     {
1.917     albertel  524: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    525: 	if (!$opened) {
1.915     albertel  526: 	    return 0;
                    527: 	}
1.783     albertel  528: 	flock($idf,LOCK_SH);
                    529: 	@profile=<$idf>;
                    530: 	close($idf);
                    531:     }
                    532:     my %temp_env;
                    533:     foreach my $line (@profile) {
1.786     albertel  534: 	if ($line !~ m/=/) {
                    535: 	    return 0;
                    536: 	}
1.783     albertel  537: 	chomp($line);
                    538: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    539: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    540:     }
                    541:     unlink("$lonidsdir/$handle.id");
                    542:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    543: 	    0640)) {
                    544: 	%disk_env = %temp_env;
                    545: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    546: 	untie(%disk_env);
                    547:     }
1.786     albertel  548:     return 1;
1.783     albertel  549: }
                    550: 
1.374     www       551: # ------------------------------------------- Transfer profile into environment
1.780     albertel  552: my $env_loaded;
                    553: sub transfer_profile_to_env {
1.788     albertel  554:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    555:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       556: 
1.720     albertel  557:     if (!defined($lonidsdir)) {
                    558: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    559:     }
                    560:     if (!defined($handle)) {
                    561:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    562:     }
                    563: 
1.786     albertel  564:     my $convert;
                    565:     {
1.917     albertel  566:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    567: 	if (!$opened) {
1.915     albertel  568: 	    return;
                    569: 	}
1.786     albertel  570: 	flock($idf,LOCK_SH);
                    571: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    572: 		&GDBM_READER(),0640)) {
                    573: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    574: 	    untie(%disk_env);
                    575: 	} else {
                    576: 	    $convert = 1;
                    577: 	}
                    578:     }
                    579:     if ($convert) {
                    580: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    581: 	    &logthis("Failed to load session, or convert session.");
                    582: 	}
1.374     www       583:     }
1.783     albertel  584: 
1.786     albertel  585:     my %remove;
1.783     albertel  586:     while ( my $envname = each(%env) ) {
1.433     matthew   587:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    588:             if ($time < time-300) {
1.783     albertel  589:                 $remove{$key}++;
1.433     matthew   590:             }
                    591:         }
                    592:     }
1.783     albertel  593: 
1.619     albertel  594:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  595:     $env_loaded=1;
1.783     albertel  596:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   597:         &delenv($expired_key);
1.374     www       598:     }
1.1       albertel  599: }
                    600: 
1.916     albertel  601: # ---------------------------------------------------- Check for valid session 
                    602: sub check_for_valid_session {
1.1155    raeburn   603:     my ($r,$name) = @_;
1.916     albertel  604:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   605:     if ($name eq '') {
                    606:         $name = 'lonID';
                    607:     }
                    608:     my $lonid=$cookies{$name};
1.916     albertel  609:     return undef if (!$lonid);
                    610: 
                    611:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   612:     my $lonidsdir;
                    613:     if ($name eq 'lonDAV') {
                    614:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    615:     } else {
                    616:         $lonidsdir=$r->dir_config('lonIDsDir');
                    617:     }
1.916     albertel  618:     return undef if (!-e "$lonidsdir/$handle.id");
                    619: 
1.917     albertel  620:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    621:     return undef if (!$opened);
1.916     albertel  622: 
                    623:     flock($idf,LOCK_SH);
                    624:     my %disk_env;
                    625:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    626: 	    &GDBM_READER(),0640)) {
                    627: 	return undef;	
                    628:     }
                    629: 
                    630:     if (!defined($disk_env{'user.name'})
                    631: 	|| !defined($disk_env{'user.domain'})) {
                    632: 	return undef;
                    633:     }
                    634:     return $handle;
                    635: }
                    636: 
1.830     albertel  637: sub timed_flock {
                    638:     my ($file,$lock_type) = @_;
                    639:     my $failed=0;
                    640:     eval {
                    641: 	local $SIG{__DIE__}='DEFAULT';
                    642: 	local $SIG{ALRM}=sub {
                    643: 	    $failed=1;
                    644: 	    die("failed lock");
                    645: 	};
                    646: 	alarm(13);
                    647: 	flock($file,$lock_type);
                    648: 	alarm(0);
                    649:     };
                    650:     if ($failed) {
                    651: 	return undef;
                    652:     } else {
                    653: 	return 1;
                    654:     }
                    655: }
                    656: 
1.5       www       657: # ---------------------------------------------------------- Append Environment
                    658: 
                    659: sub appenv {
1.949     raeburn   660:     my ($newenv,$roles) = @_;
                    661:     if (ref($newenv) eq 'HASH') {
                    662:         foreach my $key (keys(%{$newenv})) {
                    663:             my $refused = 0;
                    664: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    665:                 $refused = 1;
                    666:                 if (ref($roles) eq 'ARRAY') {
                    667:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    668:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    669:                         $refused = 0;
                    670:                     }
                    671:                 }
                    672:             }
                    673:             if ($refused) {
                    674:                 &logthis("<font color=\"blue\">WARNING: ".
                    675:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    676:                          .'</font>');
                    677: 	        delete($newenv->{$key});
                    678:             } else {
                    679:                 $env{$key}=$newenv->{$key};
                    680:             }
                    681:         }
                    682:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    683:         if ($opened
                    684: 	    && &timed_flock($env_file,LOCK_EX)
                    685: 	    &&
                    686: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    687: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    688: 	    while (my ($key,$value) = each(%{$newenv})) {
                    689: 	        $disk_env{$key} = $value;
                    690: 	    }
                    691: 	    untie(%disk_env);
1.35      www       692:         }
1.191     harris41  693:     }
1.56      www       694:     return 'ok';
                    695: }
                    696: # ----------------------------------------------------- Delete from Environment
                    697: 
                    698: sub delenv {
1.1104    raeburn   699:     my ($delthis,$regexp,$roles) = @_;
                    700:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    701:         my $refused = 1;
                    702:         if (ref($roles) eq 'ARRAY') {
                    703:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    704:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    705:                 $refused = 0;
                    706:             }
                    707:         }
                    708:         if ($refused) {
                    709:             &logthis("<font color=\"blue\">WARNING: ".
                    710:                      "Attempt to delete from environment ".$delthis);
                    711:             return 'error';
                    712:         }
1.56      www       713:     }
1.917     albertel  714:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    715:     if ($opened
1.915     albertel  716: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  717: 	&&
                    718: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    719: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  720: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   721: 	    if ($regexp) {
                    722:                 if ($key=~/^$delthis/) {
                    723:                     delete($env{$key});
                    724:                     delete($disk_env{$key});
                    725:                 } 
                    726:             } else {
                    727:                 if ($key=~/^\Q$delthis\E/) {
                    728: 		    delete($env{$key});
                    729: 		    delete($disk_env{$key});
                    730: 	        }
                    731:             }
1.448     albertel  732: 	}
1.783     albertel  733: 	untie(%disk_env);
1.5       www       734:     }
                    735:     return 'ok';
1.369     albertel  736: }
                    737: 
1.790     albertel  738: sub get_env_multiple {
                    739:     my ($name) = @_;
                    740:     my @values;
                    741:     if (defined($env{$name})) {
                    742:         # exists is it an array
                    743:         if (ref($env{$name})) {
                    744:             @values=@{ $env{$name} };
                    745:         } else {
                    746:             $values[0]=$env{$name};
                    747:         }
                    748:     }
                    749:     return(@values);
                    750: }
                    751: 
1.958     www       752: # ------------------------------------------------------------------- Locking
                    753: 
                    754: sub set_lock {
                    755:     my ($text)=@_;
                    756:     $locknum++;
                    757:     my $id=$$.'-'.$locknum;
                    758:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    759:              'session.lock.'.$id => $text});
                    760:     return $id;
                    761: }
                    762: 
                    763: sub get_locks {
                    764:     my $num=0;
                    765:     my %texts=();
                    766:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    767:        if ($lock=~/\w/) {
                    768:           $num++;
                    769:           $texts{$lock}=$env{'session.lock.'.$lock};
                    770:        }
                    771:    }
                    772:    return ($num,%texts);
                    773: }
                    774: 
                    775: sub remove_lock {
                    776:     my ($id)=@_;
                    777:     my $newlocks='';
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if (($lock=~/\w/) && ($lock ne $id)) {
                    780:           $newlocks.=','.$lock;
                    781:        }
                    782:     }
                    783:     &appenv({'session.locks' => $newlocks});
                    784:     &delenv('session.lock.'.$id);
                    785: }
                    786: 
                    787: sub remove_all_locks {
                    788:     my $activelocks=$env{'session.locks'};
                    789:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    790:        if ($lock=~/\w/) {
                    791:           &remove_lock($lock);
                    792:        }
                    793:     }
                    794: }
                    795: 
                    796: 
1.369     albertel  797: # ------------------------------------------ Find out current server userload
                    798: sub userload {
                    799:     my $numusers=0;
                    800:     {
                    801: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    802: 	my $filename;
                    803: 	my $curtime=time;
                    804: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  805: 	    next if ($filename eq '.' || $filename eq '..');
                    806: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  807: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  808: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  809: 	}
                    810: 	closedir(LONIDS);
                    811:     }
                    812:     my $userloadpercent=0;
                    813:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    814:     if ($maxuserload) {
1.371     albertel  815: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  816:     }
1.372     albertel  817:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  818:     return $userloadpercent;
1.283     www       819: }
                    820: 
1.1       albertel  821: # ------------------------------ Find server with least workload from spare.tab
1.11      www       822: 
1.1       albertel  823: sub spareserver {
1.1083    raeburn   824:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  825:     my $spare_server;
1.370     albertel  826:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  827:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    828:                                                      :  $userloadpercent;
1.1083    raeburn   829:     my ($uint_dom,$remotesessions);
                    830:     if (($udom ne '') && (&domain($udom) ne '')) {
                    831:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    832:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    833:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    834:         $remotesessions = $udomdefaults{'remotesessions'};
                    835:     }
1.1123    raeburn   836:     my $spareshash = &this_host_spares($udom);
                    837:     if (ref($spareshash) eq 'HASH') {
                    838:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    839:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    840:                 if ($uint_dom) {
                    841:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    842:                                                  $try_server));
                    843:                 }
                    844: 	        ($spare_server, $lowest_load) =
                    845: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    846:             }
1.1083    raeburn   847:         }
1.784     albertel  848: 
1.1123    raeburn   849:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    850: 
                    851:         if (!$found_server) {
                    852:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    853: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    854:                     if ($uint_dom) {
                    855:                         next unless (&spare_can_host($udom,$uint_dom,
                    856:                                                      $remotesessions,$try_server));
                    857:                     }
                    858: 	            ($spare_server, $lowest_load) =
                    859: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    860:                 }
                    861: 	    }
                    862:         }
1.784     albertel  863:     }
                    864: 
                    865:     if (!$want_server_name) {
1.968     raeburn   866:         my $protocol = 'http';
                    867:         if ($protocol{$spare_server} eq 'https') {
                    868:             $protocol = $protocol{$spare_server};
                    869:         }
1.1001    raeburn   870:         if (defined($spare_server)) {
                    871:             my $hostname = &hostname($spare_server);
1.1083    raeburn   872:             if (defined($hostname)) {
1.1001    raeburn   873: 	        $spare_server = $protocol.'://'.$hostname;
                    874:             }
                    875:         }
1.784     albertel  876:     }
                    877:     return $spare_server;
                    878: }
                    879: 
                    880: sub compare_server_load {
                    881:     my ($try_server, $spare_server, $lowest_load) = @_;
                    882: 
                    883:     my $loadans     = &reply('load',    $try_server);
                    884:     my $userloadans = &reply('userload',$try_server);
                    885: 
                    886:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   887: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  888:     }
                    889: 
                    890:     my $load;
                    891:     if ($loadans =~ /\d/) {
                    892: 	if ($userloadans =~ /\d/) {
                    893: 	    #both are numbers, pick the bigger one
                    894: 	    $load = ($loadans > $userloadans) ? $loadans 
                    895: 		                              : $userloadans;
1.411     albertel  896: 	} else {
1.784     albertel  897: 	    $load = $loadans;
1.411     albertel  898: 	}
1.784     albertel  899:     } else {
                    900: 	$load = $userloadans;
                    901:     }
                    902: 
                    903:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    904: 	$spare_server = $try_server;
                    905: 	$lowest_load  = $load;
1.370     albertel  906:     }
1.784     albertel  907:     return ($spare_server,$lowest_load);
1.202     matthew   908: }
1.914     albertel  909: 
                    910: # --------------------------- ask offload servers if user already has a session
                    911: sub find_existing_session {
                    912:     my ($udom,$uname) = @_;
1.1123    raeburn   913:     my $spareshash = &this_host_spares($udom);
                    914:     if (ref($spareshash) eq 'HASH') {
                    915:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    916:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    917:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    918:             }
                    919:         }
                    920:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    921:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    922:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    923:             }
                    924:         }
1.914     albertel  925:     }
                    926:     return;
                    927: }
                    928: 
                    929: # -------------------------------- ask if server already has a session for user
                    930: sub has_user_session {
                    931:     my ($lonid,$udom,$uname) = @_;
                    932:     my $result = &reply(join(':','userhassession',
                    933: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    934:     return 1 if ($result eq 'ok');
                    935: 
                    936:     return 0;
                    937: }
                    938: 
1.1076    raeburn   939: # --------- determine least loaded server in a user's domain which allows login
                    940: 
                    941: sub choose_server {
1.1115    raeburn   942:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   943:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   944:     my %servers = &get_servers($udom);
1.1076    raeburn   945:     my $lowest_load = 30000;
1.1151    raeburn   946:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   947:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   948:         my $loginvia;
                    949:         if ($checkloginvia) {
                    950:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   951:             if ($loginvia) {
                    952:                 my ($server,$path) = split(/:/,$loginvia);
                    953:                 ($login_host, $lowest_load) =
                    954:                     &compare_server_load($server, $login_host, $lowest_load);
                    955:                 if ($login_host eq $server) {
                    956:                     $portal_path = $path;
1.1151    raeburn   957:                     $isredirect = 1;
1.1116    raeburn   958:                 }
                    959:             } else {
                    960:                 ($login_host, $lowest_load) =
                    961:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    962:                 if ($login_host eq $lonhost) {
                    963:                     $portal_path = '';
1.1151    raeburn   964:                     $isredirect = ''; 
1.1116    raeburn   965:                 }
                    966:             }
                    967:         } else {
1.1076    raeburn   968:             ($login_host, $lowest_load) =
1.1116    raeburn   969:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   970:         }
                    971:     }
                    972:     if ($login_host ne '') {
1.1116    raeburn   973:         $hostname = &hostname($login_host);
1.1076    raeburn   974:     }
1.1151    raeburn   975:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   976: }
                    977: 
1.202     matthew   978: # --------------------------------------------- Try to change a user's password
                    979: 
                    980: sub changepass {
1.799     raeburn   981:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   982:     $currentpass = &escape($currentpass);
                    983:     $newpass     = &escape($newpass);
1.1030    raeburn   984:     my $lonhost = $perlvar{'lonHostID'};
                    985:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   986: 		       $server);
                    987:     if (! $answer) {
                    988: 	&logthis("No reply on password change request to $server ".
                    989: 		 "by $uname in domain $udom.");
                    990:     } elsif ($answer =~ "^ok") {
                    991:         &logthis("$uname in $udom successfully changed their password ".
                    992: 		 "on $server.");
                    993:     } elsif ($answer =~ "^pwchange_failure") {
                    994: 	&logthis("$uname in $udom was unable to change their password ".
                    995: 		 "on $server.  The action was blocked by either lcpasswd ".
                    996: 		 "or pwchange");
                    997:     } elsif ($answer =~ "^non_authorized") {
                    998:         &logthis("$uname in $udom did not get their password correct when ".
                    999: 		 "attempting to change it on $server.");
                   1000:     } elsif ($answer =~ "^auth_mode_error") {
                   1001:         &logthis("$uname in $udom attempted to change their password despite ".
                   1002: 		 "not being locally or internally authenticated on $server.");
                   1003:     } elsif ($answer =~ "^unknown_user") {
                   1004:         &logthis("$uname in $udom attempted to change their password ".
                   1005: 		 "on $server but were unable to because $server is not ".
                   1006: 		 "their home server.");
                   1007:     } elsif ($answer =~ "^refused") {
                   1008: 	&logthis("$server refused to change $uname in $udom password because ".
                   1009: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1010:     } elsif ($answer =~ "invalid_client") {
                   1011:         &logthis("$server refused to change $uname in $udom password because ".
                   1012:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1013:     }
                   1014:     return $answer;
1.1       albertel 1015: }
                   1016: 
1.169     harris41 1017: # ----------------------- Try to determine user's current authentication scheme
                   1018: 
                   1019: sub queryauthenticate {
                   1020:     my ($uname,$udom)=@_;
1.456     albertel 1021:     my $uhome=&homeserver($uname,$udom);
                   1022:     if (!$uhome) {
                   1023: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1024: 	return 'no_host';
                   1025:     }
                   1026:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1027:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1028: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1029:     }
1.456     albertel 1030:     return $answer;
1.169     harris41 1031: }
                   1032: 
1.1       albertel 1033: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1034: 
1.1       albertel 1035: sub authenticate {
1.1073    raeburn  1036:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1037:     $upass=&escape($upass);
                   1038:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1039:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1040:     my $newhome;
1.836     www      1041:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1042: # Maybe the machine was offline and only re-appeared again recently?
                   1043:         &reconlonc();
                   1044: # One more
1.952     raeburn  1045: 	$uhome=&homeserver($uname,$udom,1);
                   1046:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1047:             if (defined(&domain($udom,'primary'))) {
                   1048:                 $newhome=&domain($udom,'primary');
                   1049:             }
                   1050:             if ($newhome ne '') {
                   1051:                 $uhome = $newhome;
                   1052:             }
                   1053:         }
1.836     www      1054: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1055: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1056: 	    return 'no_host';
                   1057:         }
1.1       albertel 1058:     }
1.1073    raeburn  1059:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1060:     if ($answer eq 'authorized') {
1.952     raeburn  1061:         if ($newhome) {
                   1062:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1063:             return 'no_account_on_host'; 
                   1064:         } else {
                   1065:             &logthis("User $uname at $udom authorized by $uhome");
                   1066:             return $uhome;
                   1067:         }
1.471     albertel 1068:     }
                   1069:     if ($answer eq 'non_authorized') {
                   1070: 	&logthis("User $uname at $udom rejected by $uhome");
                   1071: 	return 'no_host'; 
1.9       www      1072:     }
1.471     albertel 1073:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1074:     return 'no_host';
                   1075: }
                   1076: 
1.1073    raeburn  1077: sub can_host_session {
1.1074    raeburn  1078:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1079:     my $canhost = 1;
1.1074    raeburn  1080:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1081:     if (ref($remotesessions) eq 'HASH') {
                   1082:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1083:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1084:                 $canhost = 0;
                   1085:             } else {
                   1086:                 $canhost = 1;
                   1087:             }
                   1088:         }
                   1089:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1090:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1091:                 $canhost = 1;
                   1092:             } else {
                   1093:                 $canhost = 0;
                   1094:             }
                   1095:         }
                   1096:         if ($canhost) {
                   1097:             if ($remotesessions->{'version'} ne '') {
                   1098:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1099:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1100:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1101:                         my $major = $1;
                   1102:                         my $minor = $2;
                   1103:                         if (($major < $reqmajor ) ||
                   1104:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1105:                             $canhost = 0;
                   1106:                         }
                   1107:                     } else {
                   1108:                         $canhost = 0;
                   1109:                     }
                   1110:                 }
                   1111:             }
                   1112:         }
                   1113:     }
                   1114:     if ($canhost) {
                   1115:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1116:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1117:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1118:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1119:                 if (($uint_dom ne '') && 
                   1120:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1121:                     $canhost = 0;
                   1122:                 } else {
                   1123:                     $canhost = 1;
                   1124:                 }
                   1125:             }
                   1126:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1127:                 if (($uint_dom ne '') && 
                   1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1129:                     $canhost = 1;
                   1130:                 } else {
                   1131:                     $canhost = 0;
                   1132:                 }
                   1133:             }
                   1134:         }
                   1135:     }
                   1136:     return $canhost;
                   1137: }
                   1138: 
1.1083    raeburn  1139: sub spare_can_host {
                   1140:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1141:     my $canhost=1;
                   1142:     my @intdoms;
                   1143:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1144:     if (ref($internet_names) eq 'ARRAY') {
                   1145:         @intdoms = @{$internet_names};
                   1146:     }
                   1147:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1148:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1149:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1150:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1151:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1152:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1153:                                      $remotesessions,
                   1154:                                      $defdomdefaults{'hostedsessions'});
                   1155:     }
                   1156:     return $canhost;
                   1157: }
                   1158: 
1.1123    raeburn  1159: sub this_host_spares {
                   1160:     my ($dom) = @_;
1.1126    raeburn  1161:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1162:     my @hosts = &current_machine_ids();
                   1163:     foreach my $lonhost (@hosts) {
                   1164:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1165:             $dom_in_use = $dom;
                   1166:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1167:             last;
                   1168:         }
                   1169:     }
1.1126    raeburn  1170:     if ($dom_in_use ne '') {
                   1171:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1172:     }
                   1173:     if (ref($result) ne 'HASH') {
                   1174:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1175:         $dom_in_use = &host_domain($lonhost_in_use);
                   1176:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1177:         if (ref($result) ne 'HASH') {
                   1178:             $result = \%spareid;
                   1179:         }
                   1180:     }
                   1181:     return $result;
                   1182: }
                   1183: 
                   1184: sub spares_for_offload  {
                   1185:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1186:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1187:     if (defined($cached)) {
                   1188:         return $result;
                   1189:     } else {
1.1126    raeburn  1190:         my $cachetime = 60*60*24;
                   1191:         my %domconfig =
                   1192:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1193:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1194:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1195:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1196:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1197:                 }
                   1198:             }
                   1199:         }
                   1200:     }
1.1126    raeburn  1201:     return;
1.1123    raeburn  1202: }
                   1203: 
1.1129    raeburn  1204: sub get_lonbalancer_config {
                   1205:     my ($servers) = @_;
                   1206:     my ($currbalancer,$currtargets);
                   1207:     if (ref($servers) eq 'HASH') {
                   1208:         foreach my $server (keys(%{$servers})) {
                   1209:             my %what = (
                   1210:                          spareid => 1,
                   1211:                          perlvar => 1,
                   1212:                        );
                   1213:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1214:             if ($result eq 'ok') {
                   1215:                 if (ref($returnhash) eq 'HASH') {
                   1216:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1217:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1218:                             $currbalancer = $server;
                   1219:                             $currtargets = {};
                   1220:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1221:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1222:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1223:                                 }
                   1224:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1225:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1226:                                 }
                   1227:                             }
                   1228:                             last;
                   1229:                         }
                   1230:                     }
                   1231:                 }
                   1232:             }
                   1233:         }
                   1234:     }
                   1235:     return ($currbalancer,$currtargets);
                   1236: }
                   1237: 
                   1238: sub check_loadbalancing {
                   1239:     my ($uname,$udom) = @_;
                   1240:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1241:         $offloadto,$otherserver);
                   1242:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1243:     my @hosts = &current_machine_ids();
1.1129    raeburn  1244:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1245:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1246:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1247:     my $serverhomedom = &host_domain($lonhost);
                   1248: 
                   1249:     my $cachetime = 60*60*24;
                   1250: 
                   1251:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1252:         $dom_in_use = $udom;
                   1253:         $homeintdom = 1;
                   1254:     } else {
                   1255:         $dom_in_use = $serverhomedom;
                   1256:     }
                   1257:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1258:     unless (defined($cached)) {
                   1259:         my %domconfig =
                   1260:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1261:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1262:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1263:         }
                   1264:     }
                   1265:     if (ref($result) eq 'HASH') {
                   1266:         my $currbalancer = $result->{'lonhost'};
                   1267:         my $currtargets = $result->{'targets'};
                   1268:         my $currrules = $result->{'rules'};
                   1269:         if ($currbalancer ne '') {
                   1270:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1271:                 $is_balancer = 1;
                   1272:             }
                   1273:         }
                   1274:         if ($is_balancer) {
                   1275:             if (ref($currrules) eq 'HASH') {
                   1276:                 if ($homeintdom) {
                   1277:                     if ($uname ne '') {
                   1278:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1279:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1280:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1281:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1282:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1283:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1284:                             }
                   1285:                         }
                   1286:                         if ($rule_in_effect eq '') {
                   1287:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1288:                             if ($userenv{'inststatus'} ne '') {
                   1289:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1290:                                 my ($othertitle,$usertypes,$types) =
                   1291:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1292:                                 if (ref($types) eq 'ARRAY') {
                   1293:                                     foreach my $type (@{$types}) {
                   1294:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1295:                                             if (exists($currrules->{$type})) {
                   1296:                                                 $rule_in_effect = $currrules->{$type};
                   1297:                                             }
                   1298:                                         }
                   1299:                                     }
                   1300:                                 }
                   1301:                             } else {
                   1302:                                 if (exists($currrules->{'default'})) {
                   1303:                                     $rule_in_effect = $currrules->{'default'};
                   1304:                                 }
                   1305:                             }
                   1306:                         }
                   1307:                     } else {
                   1308:                         if (exists($currrules->{'default'})) {
                   1309:                             $rule_in_effect = $currrules->{'default'};
                   1310:                         }
                   1311:                     }
                   1312:                 } else {
                   1313:                     if ($currrules->{'_LC_external'} ne '') {
                   1314:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1315:                     }
                   1316:                 }
                   1317:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1318:                                                        $uname,$udom);
                   1319:             }
                   1320:         }
                   1321:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1322:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1323:         unless (defined($cached)) {
                   1324:             my %domconfig =
                   1325:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1326:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1327:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1328:             }
                   1329:         }
                   1330:         if (ref($result) eq 'HASH') {
                   1331:             my $currbalancer = $result->{'lonhost'};
                   1332:             my $currtargets = $result->{'targets'};
                   1333:             my $currrules = $result->{'rules'};
                   1334: 
                   1335:             if ($currbalancer eq $lonhost) {
                   1336:                 $is_balancer = 1;
                   1337:                 if (ref($currrules) eq 'HASH') {
                   1338:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1339:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1340:                     }
                   1341:                 }
                   1342:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1343:                                                        $uname,$udom);
                   1344:             }
                   1345:         } else {
                   1346:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1347:                 $is_balancer = 1;
                   1348:                 $offloadto = &this_host_spares($dom_in_use);
                   1349:             }
                   1350:         }
                   1351:     } else {
                   1352:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1353:             $is_balancer = 1;
                   1354:             $offloadto = &this_host_spares($dom_in_use);
                   1355:         }
                   1356:     }
1.1176    raeburn  1357:     if ($is_balancer) {
                   1358:         my $lowest_load = 30000;
                   1359:         if (ref($offloadto) eq 'HASH') {
                   1360:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1361:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1362:                     ($otherserver,$lowest_load) =
                   1363:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1364:                 }
1.1129    raeburn  1365:             }
1.1176    raeburn  1366:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1367: 
1.1176    raeburn  1368:             if (!$found_server) {
                   1369:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1370:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1371:                         ($otherserver,$lowest_load) =
                   1372:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1373:                     }
                   1374:                 }
                   1375:             }
                   1376:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1377:             if (@{$offloadto} == 1) {
                   1378:                 $otherserver = $offloadto->[0];
                   1379:             } elsif (@{$offloadto} > 1) {
                   1380:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1381:                     ($otherserver,$lowest_load) =
                   1382:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1383:                 }
                   1384:             }
                   1385:         }
1.1176    raeburn  1386:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1387:             $is_balancer = 0;
                   1388:             if ($uname ne '' && $udom ne '') {
                   1389:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1390:                     
                   1391:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1392:                              'user.loadbalcheck.time' => time});
                   1393:                 }
1.1129    raeburn  1394:             }
                   1395:         }
                   1396:     }
                   1397:     return ($is_balancer,$otherserver);
                   1398: }
                   1399: 
                   1400: sub get_loadbalancer_targets {
                   1401:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1402:     my $offloadto;
1.1175    raeburn  1403:     if ($rule_in_effect eq 'none') {
                   1404:         return [$perlvar{'lonHostID'}];
                   1405:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1406:         $offloadto = $currtargets;
                   1407:     } else {
                   1408:         if ($rule_in_effect eq 'homeserver') {
                   1409:             my $homeserver = &homeserver($uname,$udom);
                   1410:             if ($homeserver ne 'no_host') {
                   1411:                 $offloadto = [$homeserver];
                   1412:             }
                   1413:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1414:             my %domconfig =
                   1415:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1416:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1417:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1418:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1419:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1420:                     }
                   1421:                 }
                   1422:             } else {
1.1178    raeburn  1423:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1424:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1425:                 if (&hostname($remotebalancer) ne '') {
                   1426:                     $offloadto = [$remotebalancer];
                   1427:                 }
                   1428:             }
                   1429:         } elsif (&hostname($rule_in_effect) ne '') {
                   1430:             $offloadto = [$rule_in_effect];
                   1431:         }
                   1432:     }
                   1433:     return $offloadto;
                   1434: }
                   1435: 
1.1127    raeburn  1436: sub internet_dom_servers {
                   1437:     my ($dom) = @_;
                   1438:     my (%uniqservers,%servers);
                   1439:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1440:     my @machinedoms = &machine_domains($primaryserver);
                   1441:     foreach my $mdom (@machinedoms) {
                   1442:         my %currservers = %servers;
                   1443:         my %server = &get_servers($mdom);
                   1444:         %servers = (%currservers,%server);
                   1445:     }
                   1446:     my %by_hostname;
                   1447:     foreach my $id (keys(%servers)) {
                   1448:         push(@{$by_hostname{$servers{$id}}},$id);
                   1449:     }
                   1450:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1451:         if (@{$by_hostname{$hostname}} > 1) {
                   1452:             my $match = 0;
                   1453:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1454:                 if (&host_domain($id) eq $dom) {
                   1455:                     $uniqservers{$id} = $hostname;
                   1456:                     $match = 1;
                   1457:                 }
                   1458:             }
                   1459:             unless ($match) {
                   1460:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1461:             }
                   1462:         } else {
                   1463:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1464:         }
                   1465:     }
                   1466:     return %uniqservers;
                   1467: }
                   1468: 
1.1       albertel 1469: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1470: 
1.599     albertel 1471: my %homecache;
1.1       albertel 1472: sub homeserver {
1.230     stredwic 1473:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1474:     my $index="$uname:$udom";
1.426     albertel 1475: 
1.599     albertel 1476:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1477: 
                   1478:     my %servers = &get_servers($udom,'library');
                   1479:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1480:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1481: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1482: 
                   1483: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1484: 	if ($answer eq 'found') {
                   1485: 	    delete($badServerCache{$tryserver}); 
                   1486: 	    return $homecache{$index}=$tryserver;
                   1487: 	} elsif ($answer eq 'no_host') {
                   1488: 	    $badServerCache{$tryserver}=1;
                   1489: 	}
1.1       albertel 1490:     }    
                   1491:     return 'no_host';
1.70      www      1492: }
                   1493: 
                   1494: # ------------------------------------- Find the usernames behind a list of IDs
                   1495: 
                   1496: sub idget {
                   1497:     my ($udom,@ids)=@_;
                   1498:     my %returnhash=();
                   1499:     
1.841     albertel 1500:     my %servers = &get_servers($udom,'library');
                   1501:     foreach my $tryserver (keys(%servers)) {
                   1502: 	my $idlist=join('&',@ids);
                   1503: 	$idlist=~tr/A-Z/a-z/; 
                   1504: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1505: 	my @answer=();
                   1506: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1507: 	    @answer=split(/\&/,$reply);
                   1508: 	}                    ;
                   1509: 	my $i;
                   1510: 	for ($i=0;$i<=$#ids;$i++) {
                   1511: 	    if ($answer[$i]) {
                   1512: 		$returnhash{$ids[$i]}=$answer[$i];
                   1513: 	    } 
                   1514: 	}
                   1515:     } 
1.70      www      1516:     return %returnhash;
                   1517: }
                   1518: 
                   1519: # ------------------------------------- Find the IDs behind a list of usernames
                   1520: 
                   1521: sub idrget {
                   1522:     my ($udom,@unames)=@_;
                   1523:     my %returnhash=();
1.800     albertel 1524:     foreach my $uname (@unames) {
                   1525:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1526:     }
1.70      www      1527:     return %returnhash;
                   1528: }
                   1529: 
                   1530: # ------------------------------- Store away a list of names and associated IDs
                   1531: 
                   1532: sub idput {
                   1533:     my ($udom,%ids)=@_;
                   1534:     my %servers=();
1.800     albertel 1535:     foreach my $uname (keys(%ids)) {
                   1536: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1537:         my $uhom=&homeserver($uname,$udom);
1.70      www      1538:         if ($uhom ne 'no_host') {
1.800     albertel 1539:             my $id=&escape($ids{$uname});
1.70      www      1540:             $id=~tr/A-Z/a-z/;
1.800     albertel 1541:             my $esc_unam=&escape($uname);
1.70      www      1542: 	    if ($servers{$uhom}) {
1.800     albertel 1543: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1544:             } else {
1.800     albertel 1545:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1546:             }
                   1547:         }
1.191     harris41 1548:     }
1.800     albertel 1549:     foreach my $server (keys(%servers)) {
                   1550:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1551:     }
1.344     www      1552: }
                   1553: 
1.1023    raeburn  1554: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1555: sub dump_dom {
1.1165    droeschl 1556:     my ($namespace, $udom, $regexp) = @_;
                   1557: 
                   1558:     $udom ||= $env{'user.domain'};
                   1559: 
                   1560:     return () unless $udom;
                   1561: 
                   1562:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1563: }
                   1564: 
1.1023    raeburn  1565: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1566: 
                   1567: sub get_dom {
1.860     raeburn  1568:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1569:     my $items='';
                   1570:     foreach my $item (@$storearr) {
                   1571:         $items.=&escape($item).'&';
                   1572:     }
                   1573:     $items=~s/\&$//;
1.860     raeburn  1574:     if (!$udom) {
                   1575:         $udom=$env{'user.domain'};
                   1576:         if (defined(&domain($udom,'primary'))) {
                   1577:             $uhome=&domain($udom,'primary');
                   1578:         } else {
1.874     albertel 1579:             undef($uhome);
1.860     raeburn  1580:         }
                   1581:     } else {
                   1582:         if (!$uhome) {
                   1583:             if (defined(&domain($udom,'primary'))) {
                   1584:                 $uhome=&domain($udom,'primary');
                   1585:             }
                   1586:         }
                   1587:     }
                   1588:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1589:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1590:         my %returnhash;
1.875     albertel 1591:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1592:             return %returnhash;
                   1593:         }
1.806     raeburn  1594:         my @pairs=split(/\&/,$rep);
                   1595:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1596:             return @pairs;
                   1597:         }
                   1598:         my $i=0;
                   1599:         foreach my $item (@$storearr) {
                   1600:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1601:             $i++;
                   1602:         }
                   1603:         return %returnhash;
                   1604:     } else {
1.880     banghart 1605:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1606:     }
                   1607: }
                   1608: 
                   1609: # -------------------------------------------- put items in domain db files 
                   1610: 
                   1611: sub put_dom {
1.860     raeburn  1612:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1613:     if (!$udom) {
                   1614:         $udom=$env{'user.domain'};
                   1615:         if (defined(&domain($udom,'primary'))) {
                   1616:             $uhome=&domain($udom,'primary');
                   1617:         } else {
1.874     albertel 1618:             undef($uhome);
1.860     raeburn  1619:         }
                   1620:     } else {
                   1621:         if (!$uhome) {
                   1622:             if (defined(&domain($udom,'primary'))) {
                   1623:                 $uhome=&domain($udom,'primary');
                   1624:             }
                   1625:         }
                   1626:     } 
                   1627:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1628:         my $items='';
                   1629:         foreach my $item (keys(%$storehash)) {
                   1630:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1631:         }
                   1632:         $items=~s/\&$//;
                   1633:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1634:     } else {
1.860     raeburn  1635:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1636:     }
                   1637: }
                   1638: 
1.1023    raeburn  1639: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1640: sub newput_dom {
1.1023    raeburn  1641:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1642:     my $result;
                   1643:     if (!$udom) {
                   1644:         $udom=$env{'user.domain'};
                   1645:     }
1.1023    raeburn  1646:     if ($udom) {
                   1647:         my $uname = &get_domainconfiguser($udom);
                   1648:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1649:     }
                   1650:     return $result;
                   1651: }
                   1652: 
1.1023    raeburn  1653: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1654: sub del_dom {
1.1023    raeburn  1655:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1656:     if (ref($storearr) eq 'ARRAY') {
                   1657:         if (!$udom) {
                   1658:             $udom=$env{'user.domain'};
                   1659:         }
1.1023    raeburn  1660:         if ($udom) {
                   1661:             my $uname = &get_domainconfiguser($udom); 
                   1662:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1663:         }
                   1664:     }
                   1665: }
                   1666: 
1.1023    raeburn  1667: # ----------------------------------construct domainconfig user for a domain 
                   1668: sub get_domainconfiguser {
                   1669:     my ($udom) = @_;
                   1670:     return $udom.'-domainconfig';
                   1671: }
                   1672: 
1.837     raeburn  1673: sub retrieve_inst_usertypes {
                   1674:     my ($udom) = @_;
                   1675:     my (%returnhash,@order);
1.989     raeburn  1676:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1677:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1678:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1679:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1680:         @order = @{$domdefs{'inststatusorder'}};
                   1681:     } else {
                   1682:         if (defined(&domain($udom,'primary'))) {
                   1683:             my $uhome=&domain($udom,'primary');
                   1684:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1685:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1686:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1687:                 return (\%returnhash,\@order);
                   1688:             }
                   1689:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1690:             my @pairs=split(/\&/,$hashitems);
                   1691:             foreach my $item (@pairs) {
                   1692:                 my ($key,$value)=split(/=/,$item,2);
                   1693:                 $key = &unescape($key);
                   1694:                 next if ($key =~ /^error: 2 /);
                   1695:                 $returnhash{$key}=&thaw_unescape($value);
                   1696:             }
                   1697:             my @esc_order = split(/\&/,$orderitems);
                   1698:             foreach my $item (@esc_order) {
                   1699:                 push(@order,&unescape($item));
                   1700:             }
                   1701:         } else {
                   1702:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1703:         }
                   1704:     }
                   1705:     return (\%returnhash,\@order);
                   1706: }
                   1707: 
1.868     raeburn  1708: sub is_domainimage {
                   1709:     my ($url) = @_;
                   1710:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1711:         if (&domain($1) ne '') {
                   1712:             return '1';
                   1713:         }
                   1714:     }
                   1715:     return;
                   1716: }
                   1717: 
1.899     raeburn  1718: sub inst_directory_query {
                   1719:     my ($srch) = @_;
                   1720:     my $udom = $srch->{'srchdomain'};
                   1721:     my %results;
                   1722:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1723:     my $outcome;
1.899     raeburn  1724:     if ($homeserver ne '') {
1.904     albertel 1725: 	my $queryid=&reply("querysend:instdirsearch:".
                   1726: 			   &escape($srch->{'srchby'}).':'.
                   1727: 			   &escape($srch->{'srchterm'}).':'.
                   1728: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1729: 	my $host=&hostname($homeserver);
                   1730: 	if ($queryid !~/^\Q$host\E\_/) {
                   1731: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1732: 	    return;
                   1733: 	}
                   1734: 	my $response = &get_query_reply($queryid);
                   1735: 	my $maxtries = 5;
                   1736: 	my $tries = 1;
                   1737: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1738: 	    $response = &get_query_reply($queryid);
                   1739: 	    $tries ++;
                   1740: 	}
                   1741: 
                   1742:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1743:             if ($response eq 'unavailable') {
                   1744:                 $outcome = $response;
                   1745:             } else {
                   1746:                 $outcome = 'ok';
                   1747:                 my @matches = split(/\n/,$response);
                   1748:                 foreach my $match (@matches) {
                   1749:                     my ($key,$value) = split(/=/,$match);
                   1750:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1751:                 }
1.899     raeburn  1752:             }
                   1753:         }
                   1754:     }
1.909     raeburn  1755:     return ($outcome,%results);
1.899     raeburn  1756: }
                   1757: 
                   1758: sub usersearch {
                   1759:     my ($srch) = @_;
                   1760:     my $dom = $srch->{'srchdomain'};
                   1761:     my %results;
                   1762:     my %libserv = &all_library();
                   1763:     my $query = 'usersearch';
                   1764:     foreach my $tryserver (keys(%libserv)) {
                   1765:         if (&host_domain($tryserver) eq $dom) {
                   1766:             my $host=&hostname($tryserver);
                   1767:             my $queryid=
1.911     raeburn  1768:                 &reply("querysend:".&escape($query).':'.
                   1769:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1770:                        &escape($srch->{'srchtype'}).':'.
                   1771:                        &escape($srch->{'srchterm'}),$tryserver);
                   1772:             if ($queryid !~/^\Q$host\E\_/) {
                   1773:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1774:                 next;
1.899     raeburn  1775:             }
                   1776:             my $reply = &get_query_reply($queryid);
                   1777:             my $maxtries = 1;
                   1778:             my $tries = 1;
                   1779:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1780:                 $reply = &get_query_reply($queryid);
                   1781:                 $tries ++;
                   1782:             }
                   1783:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1784:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1785:             } else {
1.911     raeburn  1786:                 my @matches;
                   1787:                 if ($reply =~ /\n/) {
                   1788:                     @matches = split(/\n/,$reply);
                   1789:                 } else {
                   1790:                     @matches = split(/\&/,$reply);
                   1791:                 }
1.899     raeburn  1792:                 foreach my $match (@matches) {
                   1793:                     my ($uname,$udom,%userhash);
1.911     raeburn  1794:                     foreach my $entry (split(/:/,$match)) {
                   1795:                         my ($key,$value) =
                   1796:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1797:                         $userhash{$key} = $value;
                   1798:                         if ($key eq 'username') {
                   1799:                             $uname = $value;
                   1800:                         } elsif ($key eq 'domain') {
                   1801:                             $udom = $value;
1.911     raeburn  1802:                         }
1.899     raeburn  1803:                     }
                   1804:                     $results{$uname.':'.$udom} = \%userhash;
                   1805:                 }
                   1806:             }
                   1807:         }
                   1808:     }
                   1809:     return %results;
                   1810: }
                   1811: 
1.912     raeburn  1812: sub get_instuser {
                   1813:     my ($udom,$uname,$id) = @_;
                   1814:     my $homeserver = &domain($udom,'primary');
                   1815:     my ($outcome,%results);
                   1816:     if ($homeserver ne '') {
                   1817:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1818:                            &escape($id).':'.&escape($udom),$homeserver);
                   1819:         my $host=&hostname($homeserver);
                   1820:         if ($queryid !~/^\Q$host\E\_/) {
                   1821:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1822:             return;
                   1823:         }
                   1824:         my $response = &get_query_reply($queryid);
                   1825:         my $maxtries = 5;
                   1826:         my $tries = 1;
                   1827:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1828:             $response = &get_query_reply($queryid);
                   1829:             $tries ++;
                   1830:         }
                   1831:         if (!&error($response) && $response ne 'refused') {
                   1832:             if ($response eq 'unavailable') {
                   1833:                 $outcome = $response;
                   1834:             } else {
                   1835:                 $outcome = 'ok';
                   1836:                 my @matches = split(/\n/,$response);
                   1837:                 foreach my $match (@matches) {
                   1838:                     my ($key,$value) = split(/=/,$match);
                   1839:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1840:                 }
                   1841:             }
                   1842:         }
                   1843:     }
                   1844:     my %userinfo;
                   1845:     if (ref($results{$uname}) eq 'HASH') {
                   1846:         %userinfo = %{$results{$uname}};
                   1847:     } 
                   1848:     return ($outcome,%userinfo);
                   1849: }
                   1850: 
                   1851: sub inst_rulecheck {
1.923     raeburn  1852:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1853:     my %returnhash;
                   1854:     if ($udom ne '') {
                   1855:         if (ref($rules) eq 'ARRAY') {
                   1856:             @{$rules} = map {&escape($_);} (@{$rules});
                   1857:             my $rulestr = join(':',@{$rules});
                   1858:             my $homeserver=&domain($udom,'primary');
                   1859:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1860:                 my $response;
                   1861:                 if ($item eq 'username') {                
                   1862:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1863:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1864:                                               $homeserver));
1.923     raeburn  1865:                 } elsif ($item eq 'id') {
                   1866:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1867:                                               ':'.&escape($id).':'.$rulestr,
                   1868:                                               $homeserver));
1.945     raeburn  1869:                 } elsif ($item eq 'selfcreate') {
                   1870:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1871:                                                &escape($udom).':'.&escape($uname).
                   1872:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1873:                 }
1.912     raeburn  1874:                 if ($response ne 'refused') {
                   1875:                     my @pairs=split(/\&/,$response);
                   1876:                     foreach my $item (@pairs) {
                   1877:                         my ($key,$value)=split(/=/,$item,2);
                   1878:                         $key = &unescape($key);
                   1879:                         next if ($key =~ /^error: 2 /);
                   1880:                         $returnhash{$key}=&thaw_unescape($value);
                   1881:                     }
                   1882:                 }
                   1883:             }
                   1884:         }
                   1885:     }
                   1886:     return %returnhash;
                   1887: }
                   1888: 
                   1889: sub inst_userrules {
1.923     raeburn  1890:     my ($udom,$check) = @_;
1.912     raeburn  1891:     my (%ruleshash,@ruleorder);
                   1892:     if ($udom ne '') {
                   1893:         my $homeserver=&domain($udom,'primary');
                   1894:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1895:             my $response;
                   1896:             if ($check eq 'id') {
                   1897:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1898:                                  $homeserver);
1.943     raeburn  1899:             } elsif ($check eq 'email') {
                   1900:                 $response=&reply('instemailrules:'.&escape($udom),
                   1901:                                  $homeserver);
1.923     raeburn  1902:             } else {
                   1903:                 $response=&reply('instuserrules:'.&escape($udom),
                   1904:                                  $homeserver);
                   1905:             }
1.912     raeburn  1906:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1907:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1908:                 ($response ne 'no_such_host')) {
                   1909:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1910:                 my @pairs=split(/\&/,$hashitems);
                   1911:                 foreach my $item (@pairs) {
                   1912:                     my ($key,$value)=split(/=/,$item,2);
                   1913:                     $key = &unescape($key);
                   1914:                     next if ($key =~ /^error: 2 /);
                   1915:                     $ruleshash{$key}=&thaw_unescape($value);
                   1916:                 }
                   1917:                 my @esc_order = split(/\&/,$orderitems);
                   1918:                 foreach my $item (@esc_order) {
                   1919:                     push(@ruleorder,&unescape($item));
                   1920:                 }
                   1921:             }
                   1922:         }
                   1923:     }
                   1924:     return (\%ruleshash,\@ruleorder);
                   1925: }
                   1926: 
1.976     raeburn  1927: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1928: 
                   1929: sub get_domain_defaults {
                   1930:     my ($domain) = @_;
                   1931:     my $cachetime = 60*60*24;
                   1932:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1933:     if (defined($cached)) {
                   1934:         if (ref($result) eq 'HASH') {
                   1935:             return %{$result};
                   1936:         }
                   1937:     }
                   1938:     my %domdefaults;
                   1939:     my %domconfig =
1.989     raeburn  1940:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1941:                                   'requestcourses','inststatus',
1.1073    raeburn  1942:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1943:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1944:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1945:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1946:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1947:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1948:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1949:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1950:     } else {
                   1951:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1952:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1953:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1954:     }
1.976     raeburn  1955:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1956:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1957:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1958:         } else {
                   1959:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1960:         } 
1.1177    raeburn  1961:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1962:         foreach my $item (@usertools) {
                   1963:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1964:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1965:             }
                   1966:         }
                   1967:     }
1.985     raeburn  1968:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1969:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1970:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1971:         }
                   1972:     }
1.989     raeburn  1973:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1974:         foreach my $item ('inststatustypes','inststatusorder') {
                   1975:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1976:         }
                   1977:     }
1.1047    raeburn  1978:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1979:         foreach my $item ('canuse_pdfforms') {
                   1980:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1981:         }
                   1982:     }
1.1073    raeburn  1983:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1984:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1985:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1986:         }
                   1987:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1988:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1989:         }
                   1990:     }
1.943     raeburn  1991:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1992:                                   $cachetime);
                   1993:     return %domdefaults;
                   1994: }
                   1995: 
1.344     www      1996: # --------------------------------------------------- Assign a key to a student
                   1997: 
                   1998: sub assign_access_key {
1.364     www      1999: #
                   2000: # a valid key looks like uname:udom#comments
                   2001: # comments are being appended
                   2002: #
1.498     www      2003:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2004:     $kdom=
1.620     albertel 2005:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2006:     $knum=
1.620     albertel 2007:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2008:     $cdom=
1.620     albertel 2009:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2010:     $cnum=
1.620     albertel 2011:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2012:     $udom=$env{'user.name'} unless (defined($udom));
                   2013:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2014:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2015:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2016:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2017:                                                   # assigned to this person
                   2018:                                                   # - this should not happen,
1.345     www      2019:                                                   # unless something went wrong
                   2020:                                                   # the first time around
                   2021: # ready to assign
1.364     www      2022:         $logentry=$1.'; '.$logentry;
1.496     www      2023:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2024:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2025: # key now belongs to user
1.346     www      2026: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2027:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2028:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2029:                 return 'ok';
                   2030:             } else {
                   2031:                 return 
                   2032:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2033: 	    }
                   2034:         } else {
                   2035:             return 'error: Could not assign key, try again later.';
                   2036:         }
1.364     www      2037:     } elsif (!$existing{$ckey}) {
1.345     www      2038: # the key does not exist
                   2039: 	return 'error: The key does not exist';
                   2040:     } else {
                   2041: # the key is somebody else's
                   2042: 	return 'error: The key is already in use';
                   2043:     }
1.344     www      2044: }
                   2045: 
1.364     www      2046: # ------------------------------------------ put an additional comment on a key
                   2047: 
                   2048: sub comment_access_key {
                   2049: #
                   2050: # a valid key looks like uname:udom#comments
                   2051: # comments are being appended
                   2052: #
                   2053:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2054:     $cdom=
1.620     albertel 2055:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2056:     $cnum=
1.620     albertel 2057:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2058:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2059:     if ($existing{$ckey}) {
                   2060:         $existing{$ckey}.='; '.$logentry;
                   2061: # ready to assign
1.367     www      2062:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2063:                                                  $cdom,$cnum) eq 'ok') {
                   2064: 	    return 'ok';
                   2065:         } else {
                   2066: 	    return 'error: Count not store comment.';
                   2067:         }
                   2068:     } else {
                   2069: # the key does not exist
                   2070: 	return 'error: The key does not exist';
                   2071:     }
                   2072: }
                   2073: 
1.344     www      2074: # ------------------------------------------------------ Generate a set of keys
                   2075: 
                   2076: sub generate_access_keys {
1.364     www      2077:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2078:     $cdom=
1.620     albertel 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2080:     $cnum=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2082:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2083:     unless (($cdom) && ($cnum)) { return 0; }
                   2084:     if ($number>10000) { return 0; }
                   2085:     sleep(2); # make sure don't get same seed twice
                   2086:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2087:     my $total=0;
                   2088:     for (my $i=1;$i<=$number;$i++) {
                   2089:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2090:                   sprintf("%lx",int(100000*rand)).'-'.
                   2091:                   sprintf("%lx",int(100000*rand));
                   2092:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2093:        $newkey=~s/0/h/g; # and also 0 and O
                   2094:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2095:        if ($existing{$newkey}) {
                   2096:            $i--;
                   2097:        } else {
1.364     www      2098: 	  if (&put('accesskeys',
                   2099:               { $newkey => '# generated '.localtime().
1.620     albertel 2100:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2101:                            '; '.$logentry },
                   2102: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2103:               $total++;
                   2104: 	  }
                   2105:        }
                   2106:     }
1.620     albertel 2107:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2108:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2109:     return $total;
                   2110: }
                   2111: 
                   2112: # ------------------------------------------------------- Validate an accesskey
                   2113: 
                   2114: sub validate_access_key {
                   2115:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2116:     $cdom=
1.620     albertel 2117:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2118:     $cnum=
1.620     albertel 2119:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2120:     $udom=$env{'user.domain'} unless (defined($udom));
                   2121:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2122:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2123:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2124: }
                   2125: 
                   2126: # ------------------------------------- Find the section of student in a course
1.652     albertel 2127: sub devalidate_getsection_cache {
                   2128:     my ($udom,$unam,$courseid)=@_;
                   2129:     my $hashid="$udom:$unam:$courseid";
                   2130:     &devalidate_cache_new('getsection',$hashid);
                   2131: }
1.298     matthew  2132: 
1.815     albertel 2133: sub courseid_to_courseurl {
                   2134:     my ($courseid) = @_;
                   2135:     #already url style courseid
                   2136:     return $courseid if ($courseid =~ m{^/});
                   2137: 
                   2138:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2139: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2140: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2141: 	return "/$cdom/$cnum";
                   2142:     }
                   2143: 
                   2144:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2145:     if (exists($courseinfo{'num'})) {
                   2146: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2147:     }
                   2148: 
                   2149:     return undef;
                   2150: }
                   2151: 
1.298     matthew  2152: sub getsection {
                   2153:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2154:     my $cachetime=1800;
1.551     albertel 2155: 
                   2156:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2157:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2158:     if (defined($cached)) { return $result; }
                   2159: 
1.298     matthew  2160:     my %Pending; 
                   2161:     my %Expired;
                   2162:     #
                   2163:     # Each role can either have not started yet (pending), be active, 
                   2164:     #    or have expired.
                   2165:     #
                   2166:     # If there is an active role, we are done.
                   2167:     #
                   2168:     # If there is more than one role which has not started yet, 
                   2169:     #     choose the one which will start sooner
                   2170:     # If there is one role which has not started yet, return it.
                   2171:     #
                   2172:     # If there is more than one expired role, choose the one which ended last.
                   2173:     # If there is a role which has expired, return it.
                   2174:     #
1.815     albertel 2175:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2176:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2177:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2178:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2179:         my $section=$1;
                   2180:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2181:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2182:         my $now=time;
1.548     albertel 2183:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2184:             $Expired{$end}=$section;
                   2185:             next;
                   2186:         }
1.548     albertel 2187:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2188:             $Pending{$start}=$section;
                   2189:             next;
                   2190:         }
1.599     albertel 2191:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2192:     }
                   2193:     #
                   2194:     # Presumedly there will be few matching roles from the above
                   2195:     # loop and the sorting time will be negligible.
                   2196:     if (scalar(keys(%Pending))) {
                   2197:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2198:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2199:     } 
                   2200:     if (scalar(keys(%Expired))) {
                   2201:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2202:         my $time = pop(@sorted);
1.599     albertel 2203:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2204:     }
1.599     albertel 2205:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2206: }
1.70      www      2207: 
1.599     albertel 2208: sub save_cache {
                   2209:     &purge_remembered();
1.722     albertel 2210:     #&Apache::loncommon::validate_page();
1.620     albertel 2211:     undef(%env);
1.780     albertel 2212:     undef($env_loaded);
1.599     albertel 2213: }
1.452     albertel 2214: 
1.599     albertel 2215: my $to_remember=-1;
                   2216: my %remembered;
                   2217: my %accessed;
                   2218: my $kicks=0;
                   2219: my $hits=0;
1.849     albertel 2220: sub make_key {
                   2221:     my ($name,$id) = @_;
1.872     albertel 2222:     if (length($id) > 65 
                   2223: 	&& length(&escape($id)) > 200) {
                   2224: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2225:     }
1.849     albertel 2226:     return &escape($name.':'.$id);
                   2227: }
                   2228: 
1.599     albertel 2229: sub devalidate_cache_new {
                   2230:     my ($name,$id,$debug) = @_;
                   2231:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2232:     $id=&make_key($name,$id);
1.599     albertel 2233:     $memcache->delete($id);
                   2234:     delete($remembered{$id});
                   2235:     delete($accessed{$id});
                   2236: }
                   2237: 
                   2238: sub is_cached_new {
                   2239:     my ($name,$id,$debug) = @_;
1.849     albertel 2240:     $id=&make_key($name,$id);
1.599     albertel 2241:     if (exists($remembered{$id})) {
1.1133    foxr     2242: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2243: 	$accessed{$id}=[&gettimeofday()];
                   2244: 	$hits++;
                   2245: 	return ($remembered{$id},1);
                   2246:     }
                   2247:     my $value = $memcache->get($id);
                   2248:     if (!(defined($value))) {
                   2249: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2250: 	return (undef,undef);
1.416     albertel 2251:     }
1.599     albertel 2252:     if ($value eq '__undef__') {
                   2253: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2254: 	$value=undef;
                   2255:     }
                   2256:     &make_room($id,$value,$debug);
                   2257:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2258:     return ($value,1);
                   2259: }
                   2260: 
                   2261: sub do_cache_new {
                   2262:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2263:     $id=&make_key($name,$id);
1.599     albertel 2264:     my $setvalue=$value;
                   2265:     if (!defined($setvalue)) {
                   2266: 	$setvalue='__undef__';
                   2267:     }
1.623     albertel 2268:     if (!defined($time) ) {
                   2269: 	$time=600;
                   2270:     }
1.599     albertel 2271:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2272:     my $result = $memcache->set($id,$setvalue,$time);
                   2273:     if (! $result) {
1.872     albertel 2274: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2275: 	$memcache->disconnect_all();
1.872     albertel 2276:     }
1.600     albertel 2277:     # need to make a copy of $value
1.919     albertel 2278:     &make_room($id,$value,$debug);
1.599     albertel 2279:     return $value;
                   2280: }
                   2281: 
                   2282: sub make_room {
                   2283:     my ($id,$value,$debug)=@_;
1.919     albertel 2284: 
                   2285:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2286:                                     : $value;
1.599     albertel 2287:     if ($to_remember<0) { return; }
                   2288:     $accessed{$id}=[&gettimeofday()];
                   2289:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2290:     my $to_kick;
                   2291:     my $max_time=0;
                   2292:     foreach my $other (keys(%accessed)) {
                   2293: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2294: 	    $to_kick=$other;
                   2295: 	    $max_time=&tv_interval($accessed{$other});
                   2296: 	}
                   2297:     }
                   2298:     delete($remembered{$to_kick});
                   2299:     delete($accessed{$to_kick});
                   2300:     $kicks++;
                   2301:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2302:     return;
                   2303: }
                   2304: 
1.599     albertel 2305: sub purge_remembered {
1.604     albertel 2306:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2307:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2308:     undef(%remembered);
                   2309:     undef(%accessed);
1.428     albertel 2310: }
1.70      www      2311: # ------------------------------------- Read an entry from a user's environment
                   2312: 
                   2313: sub userenvironment {
                   2314:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2315:     my $items;
                   2316:     foreach my $item (@what) {
                   2317:         $items.=&escape($item).'&';
                   2318:     }
                   2319:     $items=~s/\&$//;
1.70      www      2320:     my %returnhash=();
1.1009    raeburn  2321:     my $uhome = &homeserver($unam,$udom);
                   2322:     unless ($uhome eq 'no_host') {
                   2323:         my @answer=split(/\&/, 
                   2324:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2325:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2326:             return %returnhash;
                   2327:         }
1.1009    raeburn  2328:         my $i;
                   2329:         for ($i=0;$i<=$#what;$i++) {
                   2330: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2331:         }
1.70      www      2332:     }
                   2333:     return %returnhash;
1.1       albertel 2334: }
                   2335: 
1.617     albertel 2336: # ---------------------------------------------------------- Get a studentphoto
                   2337: sub studentphoto {
                   2338:     my ($udom,$unam,$ext) = @_;
                   2339:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2340:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2341:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2342:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2343:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2344:             } else {
                   2345:                 my ($result,$perm_reqd)=
1.707     albertel 2346: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2347:                 if ($result eq 'ok') {
                   2348:                     if (!($perm_reqd eq 'yes')) {
                   2349:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2350:                     }
                   2351:                 }
                   2352:             }
                   2353:         }
                   2354:     } else {
                   2355:         my ($result,$perm_reqd) = 
1.707     albertel 2356: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2357:         if ($result eq 'ok') {
                   2358:             if (!($perm_reqd eq 'yes')) {
                   2359:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2360:             }
                   2361:         }
                   2362:     }
                   2363:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2364: }
                   2365: 
                   2366: sub retrievestudentphoto {
                   2367:     my ($udom,$unam,$ext,$type) = @_;
                   2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2369:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2370:     if ($ret eq 'ok') {
                   2371:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2372:         if ($type eq 'thumbnail') {
                   2373:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2374:         }
                   2375:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2376:         return $tokenurl;
                   2377:     } else {
                   2378:         if ($type eq 'thumbnail') {
                   2379:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2380:         } else { 
                   2381:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2382:         }
1.617     albertel 2383:     }
                   2384: }
                   2385: 
1.263     www      2386: # -------------------------------------------------------------------- New chat
                   2387: 
                   2388: sub chatsend {
1.724     raeburn  2389:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2390:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2391:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2392:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2393:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2394: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2395: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2396: }
                   2397: 
                   2398: # ------------------------------------------ Find current version of a resource
                   2399: 
                   2400: sub getversion {
                   2401:     my $fname=&clutter(shift);
                   2402:     unless ($fname=~/^\/res\//) { return -1; }
                   2403:     return &currentversion(&filelocation('',$fname));
                   2404: }
                   2405: 
                   2406: sub currentversion {
                   2407:     my $fname=shift;
                   2408:     my $author=$fname;
                   2409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2410:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2411:     my $home=&homeserver($uname,$udom);
1.292     www      2412:     if ($home eq 'no_host') { 
                   2413:         return -1; 
                   2414:     }
1.1112    www      2415:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2416:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2417: 	return -1;
                   2418:     }
1.1112    www      2419:     return $answer;
1.263     www      2420: }
                   2421: 
1.1111    www      2422: #
                   2423: # Return special version number of resource if set by override, empty otherwise
                   2424: #
                   2425: sub usedversion {
                   2426:     my $fname=shift;
                   2427:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2428:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2429:     if ($urlversion) { return $urlversion; }
                   2430:     return '';
                   2431: }
                   2432: 
1.1       albertel 2433: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2434: 
1.1       albertel 2435: sub subscribe {
                   2436:     my $fname=shift;
1.761     raeburn  2437:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2438:     $fname=~s/[\n\r]//g;
1.1       albertel 2439:     my $author=$fname;
                   2440:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2441:     my ($udom,$uname)=split(/\//,$author);
                   2442:     my $home=homeserver($uname,$udom);
1.335     albertel 2443:     if ($home eq 'no_host') {
                   2444:         return 'not_found';
1.1       albertel 2445:     }
                   2446:     my $answer=reply("sub:$fname",$home);
1.64      www      2447:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2448: 	$answer.=' by '.$home;
                   2449:     }
1.1       albertel 2450:     return $answer;
                   2451: }
                   2452:     
1.8       www      2453: # -------------------------------------------------------------- Replicate file
                   2454: 
                   2455: sub repcopy {
                   2456:     my $filename=shift;
1.23      www      2457:     $filename=~s/\/+/\//g;
1.1142    raeburn  2458:     my $londocroot = $perlvar{'lonDocRoot'};
                   2459:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2460:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2461:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2462: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2463: 	return &repcopy_userfile($filename);
                   2464:     }
1.532     albertel 2465:     $filename=~s/[\n\r]//g;
1.8       www      2466:     my $transname="$filename.in.transfer";
1.828     www      2467: # FIXME: this should flock
1.607     raeburn  2468:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2469:     my $remoteurl=subscribe($filename);
1.64      www      2470:     if ($remoteurl =~ /^con_lost by/) {
                   2471: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2472:            return 'unavailable';
1.8       www      2473:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2474: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2475: 	   return 'not_found';
1.64      www      2476:     } elsif ($remoteurl =~ /^rejected by/) {
                   2477: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2478:            return 'forbidden';
1.20      www      2479:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2480:            return 'ok';
1.8       www      2481:     } else {
1.290     www      2482:         my $author=$filename;
                   2483:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2484:         my ($udom,$uname)=split(/\//,$author);
                   2485:         my $home=homeserver($uname,$udom);
                   2486:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2487:            my @parts=split(/\//,$filename);
                   2488:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2489:            if ($path ne "$londocroot/res") {
1.8       www      2490:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2491: 	       return 'bad_request';
1.8       www      2492:            }
                   2493:            my $count;
                   2494:            for ($count=5;$count<$#parts;$count++) {
                   2495:                $path.="/$parts[$count]";
                   2496:                if ((-e $path)!=1) {
                   2497: 		   mkdir($path,0777);
                   2498:                }
                   2499:            }
                   2500:            my $ua=new LWP::UserAgent;
                   2501:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2502:            my $response=$ua->request($request,$transname);
                   2503:            if ($response->is_error()) {
                   2504: 	       unlink($transname);
                   2505:                my $message=$response->status_line;
1.672     albertel 2506:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2507:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2508:                return 'unavailable';
1.8       www      2509:            } else {
1.16      www      2510: 	       if ($remoteurl!~/\.meta$/) {
                   2511:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2512:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2513:                   if ($mresponse->is_error()) {
                   2514: 		      unlink($filename.'.meta');
                   2515:                       &logthis(
1.672     albertel 2516:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2517:                   }
                   2518: 	       }
1.8       www      2519:                rename($transname,$filename);
1.607     raeburn  2520:                return 'ok';
1.8       www      2521:            }
1.290     www      2522:        }
1.8       www      2523:     }
1.330     www      2524: }
                   2525: 
                   2526: # ------------------------------------------------ Get server side include body
                   2527: sub ssi_body {
1.381     albertel 2528:     my ($filelink,%form)=@_;
1.606     matthew  2529:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2530:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2531:     }
1.953     www      2532:     my $output='';
                   2533:     my $response;
1.980     raeburn  2534:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2535:        ($output,$response)=&externalssi($filelink);
1.953     www      2536:     } else {
1.1004    droeschl 2537:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2538:        $filelink .= 'inhibitmenu=yes';
1.953     www      2539:        ($output,$response)=&ssi($filelink,%form);
                   2540:     }
1.778     albertel 2541:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2542:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2543:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2544:     if (wantarray) {
                   2545:         return ($output, $response);
                   2546:     } else {
                   2547:         return $output;
                   2548:     }
1.8       www      2549: }
                   2550: 
1.15      www      2551: # --------------------------------------------------------- Server Side Include
                   2552: 
1.782     albertel 2553: sub absolute_url {
                   2554:     my ($host_name) = @_;
                   2555:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2556:     if ($host_name eq '') {
                   2557: 	$host_name = $ENV{'SERVER_NAME'};
                   2558:     }
                   2559:     return $protocol.$host_name;
                   2560: }
                   2561: 
1.942     foxr     2562: #
                   2563: #   Server side include.
                   2564: # Parameters:
                   2565: #  fn     Possibly encrypted resource name/id.
                   2566: #  form   Hash that describes how the rendering should be done
                   2567: #         and other things.
1.944     foxr     2568: # Returns:
1.950     raeburn  2569: #   Scalar context: The content of the response.
                   2570: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2571: #     
1.15      www      2572: sub ssi {
                   2573: 
1.944     foxr     2574:     my ($fn,%form)=@_;
1.15      www      2575:     my $ua=new LWP::UserAgent;
1.23      www      2576:     my $request;
1.711     albertel 2577: 
                   2578:     $form{'no_update_last_known'}=1;
1.895     albertel 2579:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2580:     if (%form) {
1.782     albertel 2581:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2582:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2583:     } else {
1.782     albertel 2584:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2585:     }
                   2586: 
1.15      www      2587:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2588:     my $response= $ua->request($request);
1.1182  ! foxr     2589:     my $content = $response->content;
        !          2590: 
        !          2591: 
1.944     foxr     2592:     if (wantarray) {
1.1173    foxr     2593: 	return ($content, $response);
1.944     foxr     2594:     } else {
1.1173    foxr     2595: 	return $content;
1.942     foxr     2596:     }
1.324     www      2597: }
                   2598: 
                   2599: sub externalssi {
                   2600:     my ($url)=@_;
                   2601:     my $ua=new LWP::UserAgent;
                   2602:     my $request=new HTTP::Request('GET',$url);
                   2603:     my $response=$ua->request($request);
1.954     raeburn  2604:     if (wantarray) {
                   2605:         return ($response->content, $response);
                   2606:     } else {
                   2607:         return $response->content;
                   2608:     }
1.15      www      2609: }
1.254     www      2610: 
1.492     albertel 2611: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2612: 
                   2613: sub allowuploaded {
                   2614:     my ($srcurl,$url)=@_;
                   2615:     $url=&clutter(&declutter($url));
                   2616:     my $dir=$url;
                   2617:     $dir=~s/\/[^\/]+$//;
                   2618:     my %httpref=();
                   2619:     my $httpurl=&hreflocation('',$url);
                   2620:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2621:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2622: }
1.477     raeburn  2623: 
1.478     albertel 2624: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2625: # input: action, courseID, current domain, intended
1.637     raeburn  2626: #        path to file, source of file, instruction to parse file for objects,
                   2627: #        ref to hash for embedded objects,
                   2628: #        ref to hash for codebase of java objects.
1.1095    raeburn  2629: #        reference to scalar to accommodate mime type determined
                   2630: #          from File::MMagic if $parser = parse.
1.637     raeburn  2631: #
1.485     raeburn  2632: # output: url to file (if action was uploaddoc), 
                   2633: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2634: #
1.478     albertel 2635: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2636: # course.
1.477     raeburn  2637: #
1.478     albertel 2638: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2639: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2640: #          course's home server.
1.477     raeburn  2641: #
1.478     albertel 2642: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2643: #          be copied from $source (current location) to 
                   2644: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2645: #         and will then be copied to
                   2646: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2647: #         course's home server.
1.485     raeburn  2648: #
1.481     raeburn  2649: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2650: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2651: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2652: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2653: #         in course's home server.
1.637     raeburn  2654: #
1.477     raeburn  2655: 
                   2656: sub process_coursefile {
1.1095    raeburn  2657:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2658:         $mimetype)=@_;
1.477     raeburn  2659:     my $fetchresult;
1.638     albertel 2660:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2661:     if ($action eq 'propagate') {
1.638     albertel 2662:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2663: 			     $home);
1.481     raeburn  2664:     } else {
1.477     raeburn  2665:         my $fpath = '';
                   2666:         my $fname = $file;
1.478     albertel 2667:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2668:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2669:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2670:         if ($action eq 'copy') {
                   2671:             if ($source eq '') {
                   2672:                 $fetchresult = 'no source file';
                   2673:                 return $fetchresult;
                   2674:             } else {
                   2675:                 my $destination = $filepath.'/'.$fname;
                   2676:                 rename($source,$destination);
                   2677:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2678:                                  $home);
1.481     raeburn  2679:             }
                   2680:         } elsif ($action eq 'uploaddoc') {
                   2681:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2682:             print $fh $env{'form.'.$source};
1.481     raeburn  2683:             close($fh);
1.637     raeburn  2684:             if ($parser eq 'parse') {
1.1024    raeburn  2685:                 my $mm = new File::MMagic;
1.1095    raeburn  2686:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2687:                 if ($type eq 'text/html') {
1.1024    raeburn  2688:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2689:                     unless ($parse_result eq 'ok') {
                   2690:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2691:                     }
1.637     raeburn  2692:                 }
1.1095    raeburn  2693:                 if (ref($mimetype)) {
                   2694:                     $$mimetype = $type;
                   2695:                 } 
1.637     raeburn  2696:             }
1.477     raeburn  2697:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2698:                                  $home);
1.481     raeburn  2699:             if ($fetchresult eq 'ok') {
                   2700:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2701:             } else {
                   2702:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2703:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2704:                 return '/adm/notfound.html';
                   2705:             }
1.477     raeburn  2706:         }
                   2707:     }
1.485     raeburn  2708:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2709:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2710:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2711:     }
                   2712:     return $fetchresult;
                   2713: }
                   2714: 
1.637     raeburn  2715: sub build_filepath {
                   2716:     my ($fpath) = @_;
                   2717:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2718:     unless ($fpath eq '') {
                   2719:         my @parts=split('/',$fpath);
                   2720:         foreach my $part (@parts) {
                   2721:             $filepath.= '/'.$part;
                   2722:             if ((-e $filepath)!=1) {
                   2723:                 mkdir($filepath,0777);
                   2724:             }
                   2725:         }
                   2726:     }
                   2727:     return $filepath;
                   2728: }
                   2729: 
                   2730: sub store_edited_file {
1.638     albertel 2731:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2732:     my $file = $primary_url;
                   2733:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2734:     my $fpath = '';
                   2735:     my $fname = $file;
                   2736:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2737:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2738:     my $filepath = &build_filepath($fpath);
                   2739:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2740:     print $fh $content;
                   2741:     close($fh);
1.638     albertel 2742:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2743:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2744: 			  $home);
1.637     raeburn  2745:     if ($$fetchresult eq 'ok') {
                   2746:         return '/uploaded/'.$fpath.'/'.$fname;
                   2747:     } else {
1.638     albertel 2748:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2749: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2750:         return '/adm/notfound.html';
                   2751:     }
                   2752: }
                   2753: 
1.531     albertel 2754: sub clean_filename {
1.831     albertel 2755:     my ($fname,$args)=@_;
1.315     www      2756: # Replace Windows backslashes by forward slashes
1.257     www      2757:     $fname=~s/\\/\//g;
1.831     albertel 2758:     if (!$args->{'keep_path'}) {
                   2759:         # Get rid of everything but the actual filename
                   2760: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2761:     }
1.315     www      2762: # Replace spaces by underscores
                   2763:     $fname=~s/\s+/\_/g;
                   2764: # Replace all other weird characters by nothing
1.831     albertel 2765:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2766: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2767: # numbers
                   2768:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2769:     return $fname;
                   2770: }
1.1051    raeburn  2771: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2772: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2773: # image with the same aspect ratio as the original, but with dimensions which do 
                   2774: # not exceed $resizewidth and $resizeheight.
                   2775:  
1.984     neumanie 2776: sub resizeImage {
1.1051    raeburn  2777:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2778:     my $ima = Image::Magick->new;
                   2779:     my $resized;
                   2780:     if (-e $img_path) {
                   2781:         $ima->Read($img_path);
                   2782:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2783:             my $width = $ima->Get('width');
                   2784:             my $height = $ima->Get('height');
                   2785:             if ($width > $resizewidth) {
                   2786: 	        my $factor = $width/$resizewidth;
                   2787:                 my $newheight = $height/$factor;
                   2788:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2789:                 $resized = 1;
                   2790:             }
                   2791:         }
                   2792:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2793:             my $width = $ima->Get('width');
                   2794:             my $height = $ima->Get('height');
                   2795:             if ($height > $resizeheight) {
                   2796:                 my $factor = $height/$resizeheight;
                   2797:                 my $newwidth = $width/$factor;
                   2798:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2799:                 $resized = 1;
                   2800:             }
                   2801:         }
                   2802:         if ($resized) {
                   2803:             $ima->Write($img_path);
                   2804:         }
                   2805:     }
                   2806:     return;
1.977     amueller 2807: }
                   2808: 
1.608     albertel 2809: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2810: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2811: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2812: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2813: #                                    canceloverwrite, or ''. 
                   2814: #                   if 'coursedoc': upload to the current course
                   2815: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2816: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2817: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2818: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2819: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2820: #        $allfiles - reference to hash for embedded objects
                   2821: #        $codebase - reference to hash for codebase of java objects
                   2822: #        $desuname - username for permanent storage of uploaded file
                   2823: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2824: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2825: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2826: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2827: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2828: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2829: #                    from File::MMagic.
1.858     raeburn  2830: # 
1.686     albertel 2831: # output: url of file in userspace, or error: <message> 
                   2832: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2833: 
1.531     albertel 2834: sub userfileupload {
1.1090    raeburn  2835:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2836:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2837:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2838:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2839:     $fname=&clean_filename($fname);
1.1090    raeburn  2840:     # See if there is anything left
1.257     www      2841:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2842:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2843:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2844:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2845:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2846:         my $now = time;
1.1090    raeburn  2847:         my $filepath;
1.1095    raeburn  2848:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2849:              $filepath = 'tmp/helprequests/'.$now;
                   2850:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2851:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2852:                          '_'.$env{'user.domain'}.'/pending';
                   2853:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2854:             my ($docuname,$docudom);
                   2855:             if ($destudom) {
                   2856:                 $docudom = $destudom;
                   2857:             } else {
                   2858:                 $docudom = $env{'user.domain'};
                   2859:             }
                   2860:             if ($destuname) {
                   2861:                 $docuname = $destuname;
                   2862:             } else {
                   2863:                 $docuname = $env{'user.name'};
                   2864:             }
                   2865:             if (exists($env{'form.group'})) {
                   2866:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2867:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2868:             }
                   2869:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2870:             if ($context eq 'canceloverwrite') {
                   2871:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2872:                 if (-e  $tempfile) {
                   2873:                     my @info = stat($tempfile);
                   2874:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2875:                         unlink($tempfile);
                   2876:                     }
                   2877:                 }
                   2878:                 return;
1.523     raeburn  2879:             }
                   2880:         }
1.1090    raeburn  2881:         # Create the directory if not present
1.741     raeburn  2882:         my @parts=split(/\//,$filepath);
                   2883:         my $fullpath = $perlvar{'lonDaemons'};
                   2884:         for (my $i=0;$i<@parts;$i++) {
                   2885:             $fullpath .= '/'.$parts[$i];
                   2886:             if ((-e $fullpath)!=1) {
                   2887:                 mkdir($fullpath,0777);
                   2888:             }
                   2889:         }
                   2890:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2891:         print $fh $env{'form.'.$formname};
                   2892:         close($fh);
1.1090    raeburn  2893:         if ($context eq 'existingfile') {
                   2894:             my @info = stat($fullpath.'/'.$fname);
                   2895:             return ($fullpath.'/'.$fname,$info[9]);
                   2896:         } else {
                   2897:             return $fullpath.'/'.$fname;
                   2898:         }
1.523     raeburn  2899:     }
1.995     raeburn  2900:     if ($subdir eq 'scantron') {
                   2901:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2902:     } else {
1.995     raeburn  2903:         $fname="$subdir/$fname";
                   2904:     }
1.1090    raeburn  2905:     if ($context eq 'coursedoc') {
1.638     albertel 2906: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2907: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2908:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2909:             return &finishuserfileupload($docuname,$docudom,
                   2910: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2911: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2912:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2913:         } else {
1.620     albertel 2914:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2915:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2916: 				       $fname,$formname,$parser,
1.1095    raeburn  2917: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2918:         }
1.719     banghart 2919:     } elsif (defined($destuname)) {
                   2920:         my $docuname=$destuname;
                   2921:         my $docudom=$destudom;
1.860     raeburn  2922: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2923: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2924:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2925:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2926:     } else {
1.638     albertel 2927:         my $docuname=$env{'user.name'};
                   2928:         my $docudom=$env{'user.domain'};
1.714     raeburn  2929:         if (exists($env{'form.group'})) {
                   2930:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2931:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2932:         }
1.860     raeburn  2933: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2934: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2935:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2936:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2937:     }
1.271     www      2938: }
                   2939: 
                   2940: sub finishuserfileupload {
1.860     raeburn  2941:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2942:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2943:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2944:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2945:   
1.860     raeburn  2946:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2947:     $file=$fname;
                   2948:     if ($fname=~m|/|) {
                   2949:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2950: 	$path.=$fnamepath.'/';
                   2951:     }
1.259     www      2952:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2953:     my $count;
                   2954:     for ($count=4;$count<=$#parts;$count++) {
                   2955:         $filepath.="/$parts[$count]";
                   2956:         if ((-e $filepath)!=1) {
                   2957: 	    mkdir($filepath,0777);
                   2958:         }
                   2959:     }
1.984     neumanie 2960: 
1.258     www      2961: # Save the file
                   2962:     {
1.701     albertel 2963: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2964: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2965: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2966: 	    return '/adm/notfound.html';
                   2967: 	}
1.1090    raeburn  2968:         if ($context eq 'overwrite') {
1.1117    foxr     2969:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2970:             my $target = $filepath.'/'.$file;
                   2971:             if (-e $source) {
                   2972:                 my @info = stat($source);
                   2973:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2974:                     unless (&File::Copy::move($source,$target)) {
                   2975:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2976:                         return "Moving from $source failed";
                   2977:                     }
                   2978:                 } else {
                   2979:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2980:                 }
                   2981:             } else {
                   2982:                 return "Temporary file: $source missing";
                   2983:             }
                   2984:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2985: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2986: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2987: 	    return '/adm/notfound.html';
                   2988: 	}
1.570     albertel 2989: 	close(FH);
1.1051    raeburn  2990:         if ($resizewidth && $resizeheight) {
                   2991:             my $mm = new File::MMagic;
                   2992:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2993:             if ($mime_type =~ m{^image/}) {
                   2994: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2995:             }  
1.977     amueller 2996: 	}
1.258     www      2997:     }
1.1152    raeburn  2998:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2999:         if (ref($mimetype)) {
                   3000:             if ($$mimetype eq '') {
                   3001:                 my $mm = new File::MMagic;
                   3002:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3003:                 $$mimetype = $type;
                   3004:             }
                   3005:         }
                   3006:     }
1.637     raeburn  3007:     if ($parser eq 'parse') {
1.1152    raeburn  3008:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3009:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3010:                                                        $allfiles,$codebase);
                   3011:             unless ($parse_result eq 'ok') {
                   3012:                 &logthis('Failed to parse '.$filepath.$file.
                   3013: 	   	         ' for embedded media: '.$parse_result); 
                   3014:             }
1.637     raeburn  3015:         }
                   3016:     }
1.860     raeburn  3017:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3018:         my $input = $filepath.'/'.$file;
                   3019:         my $output = $filepath.'/'.'tn-'.$file;
                   3020:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3021:         system("convert -sample $thumbsize $input $output");
                   3022:         if (-e $filepath.'/'.'tn-'.$file) {
                   3023:             $fetchthumb  = 1; 
                   3024:         }
                   3025:     }
1.858     raeburn  3026:  
1.259     www      3027: # Notify homeserver to grep it
                   3028: #
1.984     neumanie 3029:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3030:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3031:     if ($fetchresult eq 'ok') {
1.860     raeburn  3032:         if ($fetchthumb) {
                   3033:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3034:             if ($thumbresult ne 'ok') {
                   3035:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3036:                          $docuhome.': '.$thumbresult);
                   3037:             }
                   3038:         }
1.259     www      3039: #
1.258     www      3040: # Return the URL to it
1.494     albertel 3041:         return '/uploaded/'.$path.$file;
1.263     www      3042:     } else {
1.494     albertel 3043:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3044: 		 ': '.$fetchresult);
1.263     www      3045:         return '/adm/notfound.html';
1.858     raeburn  3046:     }
1.493     albertel 3047: }
                   3048: 
1.637     raeburn  3049: sub extract_embedded_items {
1.961     raeburn  3050:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3051:     my @state = ();
1.1164    raeburn  3052:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3053:     my %javafiles = (
                   3054:                       codebase => '',
                   3055:                       code => '',
                   3056:                       archive => ''
                   3057:                     );
                   3058:     my %mediafiles = (
                   3059:                       src => '',
                   3060:                       movie => '',
                   3061:                      );
1.648     raeburn  3062:     my $p;
                   3063:     if ($content) {
                   3064:         $p = HTML::LCParser->new($content);
                   3065:     } else {
1.961     raeburn  3066:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3067:     }
1.641     albertel 3068:     while (my $t=$p->get_token()) {
1.640     albertel 3069: 	if ($t->[0] eq 'S') {
                   3070: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3071: 	    push(@state, $tagname);
1.648     raeburn  3072:             if (lc($tagname) eq 'allow') {
                   3073:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3074:             }
1.640     albertel 3075: 	    if (lc($tagname) eq 'img') {
                   3076: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3077: 	    }
1.886     albertel 3078: 	    if (lc($tagname) eq 'a') {
                   3079: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3080: 	    }
1.645     raeburn  3081:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3082:                 my $src;
1.645     raeburn  3083:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3084:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3085:                 } else {
1.1164    raeburn  3086:                     if ($attr->{'src'} ne '') {
                   3087:                         $src = $attr->{'src'};
                   3088:                         &add_filetype($allfiles,$src,'src');
                   3089:                     }
                   3090:                 }
                   3091:                 my $text = $p->get_trimmed_text();
                   3092:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3093:                     my @swfargs = split(/,/,$1);
                   3094:                     foreach my $item (@swfargs) {
                   3095:                         $item =~ s/["']//g;
                   3096:                         $item =~ s/^\s+//;
                   3097:                         $item =~ s/\s+$//;
                   3098:                     }
                   3099:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3100:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3101:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3102:                         } else {
                   3103:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3104:                         }
                   3105:                     }
1.645     raeburn  3106:                 }
                   3107:             }
                   3108:             if (lc($tagname) eq 'link') {
                   3109:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3110:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3111:                 }
                   3112:             }
1.640     albertel 3113: 	    if (lc($tagname) eq 'object' ||
                   3114: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3115: 		foreach my $item (keys(%javafiles)) {
                   3116: 		    $javafiles{$item} = '';
                   3117: 		}
1.1164    raeburn  3118:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3119:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3120:                 }
1.640     albertel 3121: 	    }
                   3122: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3123: 		my $name = lc($attr->{'name'});
                   3124: 		foreach my $item (keys(%javafiles)) {
                   3125: 		    if ($name eq $item) {
                   3126: 			$javafiles{$item} = $attr->{'value'};
                   3127: 			last;
                   3128: 		    }
                   3129: 		}
1.1164    raeburn  3130:                 my $pathfrom;
1.640     albertel 3131: 		foreach my $item (keys(%mediafiles)) {
                   3132: 		    if ($name eq $item) {
1.1164    raeburn  3133:                         $pathfrom = $attr->{'value'};
                   3134:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3135: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3136: 			last;
                   3137: 		    }
                   3138: 		}
1.1164    raeburn  3139:                 if ($name eq 'flashvars') {
                   3140:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3141:                 }
                   3142:                 if ($pathfrom ne '') {
                   3143:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3144:                                          $pathfrom);
                   3145:                 }
1.640     albertel 3146: 	    }
                   3147: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3148: 		foreach my $item (keys(%javafiles)) {
                   3149: 		    if ($attr->{$item}) {
                   3150: 			$javafiles{$item} = $attr->{$item};
                   3151: 			last;
                   3152: 		    }
                   3153: 		}
                   3154: 		foreach my $item (keys(%mediafiles)) {
                   3155: 		    if ($attr->{$item}) {
                   3156: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3157: 			last;
                   3158: 		    }
                   3159: 		}
1.1164    raeburn  3160:                 if (lc($tagname) eq 'embed') {
                   3161:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3162:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3163:                                              $attr->{'src'});
                   3164:                     }
                   3165:                 }
1.640     albertel 3166: 	    }
1.1164    raeburn  3167:             if ($t->[4] =~ m{/>$}) {
                   3168:                 pop(@state);  
                   3169:             }
1.640     albertel 3170: 	} elsif ($t->[0] eq 'E') {
                   3171: 	    my ($tagname) = ($t->[1]);
                   3172: 	    if ($javafiles{'codebase'} ne '') {
                   3173: 		$javafiles{'codebase'} .= '/';
                   3174: 	    }  
                   3175: 	    if (lc($tagname) eq 'applet' ||
                   3176: 		lc($tagname) eq 'object' ||
                   3177: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3178: 		) {
                   3179: 		foreach my $item (keys(%javafiles)) {
                   3180: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3181: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3182: 			&add_filetype($allfiles,$file,$item);
                   3183: 		    }
                   3184: 		}
                   3185: 	    } 
                   3186: 	    pop @state;
                   3187: 	}
                   3188:     }
1.1164    raeburn  3189:     foreach my $id (sort(keys(%flashvars))) {
                   3190:         if ($shockwave{$id} ne '') {
                   3191:             my @pairs = split(/\&/,$flashvars{$id});
                   3192:             foreach my $pair (@pairs) {
                   3193:                 my ($key,$value) = split(/\=/,$pair);
                   3194:                 if ($key eq 'thumb') {
                   3195:                     &add_filetype($allfiles,$value,$key);
                   3196:                 } elsif ($key eq 'content') {
                   3197:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3198:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3199:                     if ($ext ne '') {
                   3200:                         &add_filetype($allfiles,$path.$value,$ext);
                   3201:                     }
                   3202:                 }
                   3203:             }
                   3204:         }
                   3205:     }
1.637     raeburn  3206:     return 'ok';
                   3207: }
                   3208: 
1.639     albertel 3209: sub add_filetype {
                   3210:     my ($allfiles,$file,$type)=@_;
                   3211:     if (exists($allfiles->{$file})) {
                   3212: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3213: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3214: 	}
                   3215:     } else {
                   3216: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3217:     }
                   3218: }
                   3219: 
1.1164    raeburn  3220: sub embedded_dependency {
                   3221:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3222:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3223:         if (($identifier ne '') &&
                   3224:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3225:             ($pathfrom ne '')) {
                   3226:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3227:             foreach my $dep (@{$related->{$identifier}}) {
                   3228:                 &add_filetype($allfiles,$path.$dep,'object');
                   3229:             }
                   3230:         }
                   3231:     }
                   3232:     return;
                   3233: }
                   3234: 
1.493     albertel 3235: sub removeuploadedurl {
1.984     neumanie 3236:     my ($url)=@_;	
                   3237:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3238:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3239: }
                   3240: 
                   3241: sub removeuserfile {
                   3242:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3243:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3244:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3245:     if ($result eq 'ok') {	
1.798     raeburn  3246:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3247:             my $metafile = $fname.'.meta';
                   3248:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3249: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3250:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3251:             my $sqlresult = 
1.823     albertel 3252:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3253:                                         'portfolio_metadata',$group,
                   3254:                                         'delete');
1.798     raeburn  3255:         }
                   3256:     }
                   3257:     return $result;
1.257     www      3258: }
1.15      www      3259: 
1.530     albertel 3260: sub mkdiruserfile {
                   3261:     my ($docuname,$docudom,$dir)=@_;
                   3262:     my $home=&homeserver($docuname,$docudom);
                   3263:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3264: }
                   3265: 
1.531     albertel 3266: sub renameuserfile {
                   3267:     my ($docuname,$docudom,$old,$new)=@_;
                   3268:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3269:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3270:                         &escape("$old").':'.&escape("$new"),$home);
                   3271:     if ($result eq 'ok') {
                   3272:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3273:             my $oldmeta = $old.'.meta';
                   3274:             my $newmeta = $new.'.meta';
                   3275:             my $metaresult = 
                   3276:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3277: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3278:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3279:             my $sqlresult = 
1.823     albertel 3280:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3281:                                         'portfolio_metadata',$group,
                   3282:                                         'delete');
1.798     raeburn  3283:         }
                   3284:     }
                   3285:     return $result;
1.531     albertel 3286: }
                   3287: 
1.14      www      3288: # ------------------------------------------------------------------------- Log
                   3289: 
                   3290: sub log {
                   3291:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3292:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3293: }
                   3294: 
                   3295: # ------------------------------------------------------------------ Course Log
1.352     www      3296: #
                   3297: # This routine flushes several buffers of non-mission-critical nature
                   3298: #
1.157     www      3299: 
                   3300: sub flushcourselogs {
1.352     www      3301:     &logthis('Flushing log buffers');
                   3302: #
                   3303: # course logs
                   3304: # This is a log of all transactions in a course, which can be used
                   3305: # for data mining purposes
                   3306: #
                   3307: # It also collects the courseid database, which lists last transaction
                   3308: # times and course titles for all courseids
                   3309: #
                   3310:     my %courseidbuffer=();
1.921     raeburn  3311:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3312:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3313: 		          &escape($courselogs{$crsid}),
                   3314: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3315: 	    delete $courselogs{$crsid};
                   3316:         } else {
                   3317:             &logthis('Failed to flush log buffer for '.$crsid);
                   3318:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3319:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3320:                         " exceeded maximum size, deleting.</font>");
                   3321:                delete $courselogs{$crsid};
                   3322:             }
1.352     www      3323:         }
1.920     raeburn  3324:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3325:             'description' => $coursedescrbuf{$crsid},
                   3326:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3327:             'type'        => $coursetypebuf{$crsid},
                   3328:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3329:         };
1.191     harris41 3330:     }
1.352     www      3331: #
                   3332: # Write course id database (reverse lookup) to homeserver of courses 
                   3333: # Is used in pickcourse
                   3334: #
1.840     albertel 3335:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3336:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3337:                                     $courseidbuffer{$crs_home},
                   3338:                                     $crs_home,'timeonly');
1.352     www      3339:     }
                   3340: #
                   3341: # File accesses
                   3342: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3343: #
1.449     matthew  3344:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3345:         if ($entry =~ /___count$/) {
                   3346:             my ($dom,$name);
1.807     albertel 3347:             ($dom,$name,undef)=
1.811     albertel 3348: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3349:             if (! defined($dom) || $dom eq '' || 
                   3350:                 ! defined($name) || $name eq '') {
1.620     albertel 3351:                 my $cid = $env{'request.course.id'};
                   3352:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3353:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3354:             }
1.450     matthew  3355:             my $value = $accesshash{$entry};
                   3356:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3357:             my %temphash=($url => $value);
1.449     matthew  3358:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3359:             if ($result eq 'ok') {
                   3360:                 delete $accesshash{$entry};
                   3361:             }
                   3362:         } else {
1.811     albertel 3363:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3364:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3365:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3366:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3367:                 delete $accesshash{$entry};
                   3368:             }
1.185     www      3369:         }
1.191     harris41 3370:     }
1.352     www      3371: #
                   3372: # Roles
                   3373: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3374: #
1.800     albertel 3375:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3376:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3377: 	    split(/\:/,$entry);
                   3378:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3379:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3380:                 $rudom,$runame) eq 'ok') {
                   3381: 	    delete $userrolehash{$entry};
                   3382:         }
                   3383:     }
1.662     raeburn  3384: #
                   3385: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3386: #
                   3387:     my %domrolebuffer = ();
1.1000    raeburn  3388:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3389:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3390:         if ($domrolebuffer{$rudom}) {
                   3391:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3392:                       '='.&escape($domainrolehash{$entry});
                   3393:         } else {
                   3394:             $domrolebuffer{$rudom}.=&escape($entry).
                   3395:                       '='.&escape($domainrolehash{$entry});
                   3396:         }
                   3397:         delete $domainrolehash{$entry};
                   3398:     }
                   3399:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3400: 	my %servers = &get_servers($dom,'library');
                   3401: 	foreach my $tryserver (keys(%servers)) {
                   3402: 	    unless (&reply('domroleput:'.$dom.':'.
                   3403: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3404: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3405: 	    }
1.662     raeburn  3406:         }
                   3407:     }
1.186     www      3408:     $dumpcount++;
1.157     www      3409: }
                   3410: 
                   3411: sub courselog {
                   3412:     my $what=shift;
1.158     www      3413:     $what=time.':'.$what;
1.620     albertel 3414:     unless ($env{'request.course.id'}) { return ''; }
                   3415:     $coursedombuf{$env{'request.course.id'}}=
                   3416:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3417:     $coursenumbuf{$env{'request.course.id'}}=
                   3418:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3419:     $coursehombuf{$env{'request.course.id'}}=
                   3420:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3421:     $coursedescrbuf{$env{'request.course.id'}}=
                   3422:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3423:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3424:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3425:     $courseownerbuf{$env{'request.course.id'}}=
                   3426:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3427:     $coursetypebuf{$env{'request.course.id'}}=
                   3428:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3429:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3430: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3431:     } else {
1.620     albertel 3432: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3433:     }
1.620     albertel 3434:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3435: 	&flushcourselogs();
                   3436:     }
1.158     www      3437: }
                   3438: 
                   3439: sub courseacclog {
                   3440:     my $fnsymb=shift;
1.620     albertel 3441:     unless ($env{'request.course.id'}) { return ''; }
                   3442:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3443:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3444:         $what.=':POST';
1.583     matthew  3445:         # FIXME: Probably ought to escape things....
1.800     albertel 3446: 	foreach my $key (keys(%env)) {
                   3447:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3448:                 my $formitem = $1;
                   3449:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3450:                     $what.=':'.$formitem.'='.$env{$key};
                   3451:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3452:                     $what.=':'.$formitem.'='.$env{$key};
                   3453:                 }
1.158     www      3454:             }
1.191     harris41 3455:         }
1.583     matthew  3456:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3457:         # FIXME: We should not be depending on a form parameter that someone
                   3458:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3459:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3460:             $what.= ':POST';
                   3461:             # FIXME: Probably ought to escape things....
                   3462:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3463:                                  'crsdiscuss') {
1.620     albertel 3464:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3465:             }
                   3466:         }
1.158     www      3467:     }
                   3468:     &courselog($what);
1.149     www      3469: }
                   3470: 
1.185     www      3471: sub countacc {
                   3472:     my $url=&declutter(shift);
1.458     matthew  3473:     return if (! defined($url) || $url eq '');
1.620     albertel 3474:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3475: #
                   3476: # Mark that this url was used in this course
                   3477: #
1.620     albertel 3478:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3479: #
                   3480: # Increase the access count for this resource in this child process
                   3481: #
1.281     www      3482:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3483:     $accesshash{$key}++;
1.185     www      3484: }
1.349     www      3485: 
1.361     www      3486: sub linklog {
                   3487:     my ($from,$to)=@_;
                   3488:     $from=&declutter($from);
                   3489:     $to=&declutter($to);
                   3490:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3491:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3492: }
1.1160    www      3493: 
                   3494: sub statslog {
                   3495:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3496:     if ($users<2) { return; }
                   3497:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3498:             'course'       => $env{'request.course.id'},
                   3499:             'sections'     => '"all"',
                   3500:             'num_students' => $users,
                   3501:             'part'         => $part,
                   3502:             'symb'         => $symb,
                   3503:             'mean_tries'   => $av_attempts,
                   3504:             'deg_of_diff'  => $degdiff});
                   3505:     foreach my $key (keys(%dynstore)) {
                   3506:         $accesshash{$key}=$dynstore{$key};
                   3507:     }
                   3508: }
1.361     www      3509:   
1.349     www      3510: sub userrolelog {
                   3511:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3512:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3513:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3514:        $userrolehash
                   3515:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3516:                     =$tend.':'.$tstart;
1.662     raeburn  3517:     }
1.1169    droeschl 3518:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3519:        $userrolehash
                   3520:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3521:                     =$tend.':'.$tstart;
                   3522:     }
1.1169    droeschl 3523:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3524:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3525:        $domainrolehash
                   3526:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3527:                     = $tend.':'.$tstart;
                   3528:     }
1.351     www      3529: }
                   3530: 
1.957     raeburn  3531: sub courserolelog {
                   3532:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3533:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3534:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3535:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3536:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3537:         ($trole eq 'co')) {
1.957     raeburn  3538:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3539:             my $cdom = $1;
                   3540:             my $cnum = $2;
                   3541:             my $sec = $3;
                   3542:             my $namespace = 'rolelog';
                   3543:             my %storehash = (
                   3544:                                role    => $trole,
                   3545:                                start   => $tstart,
                   3546:                                end     => $tend,
                   3547:                                selfenroll => $selfenroll,
                   3548:                                context    => $context,
                   3549:                             );
                   3550:             if ($trole eq 'gr') {
                   3551:                 $namespace = 'groupslog';
                   3552:                 $storehash{'group'} = $sec;
                   3553:             } else {
                   3554:                 $storehash{'section'} = $sec;
                   3555:             }
                   3556:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3557:             if (($trole ne 'st') || ($sec ne '')) {
                   3558:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3559:             }
1.957     raeburn  3560:         }
                   3561:     }
                   3562:     return;
                   3563: }
                   3564: 
1.351     www      3565: sub get_course_adv_roles {
1.948     raeburn  3566:     my ($cid,$codes) = @_;
1.620     albertel 3567:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3568:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3569:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3570:     my %nothide=();
1.800     albertel 3571:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3572:         if ($user !~ /:/) {
                   3573: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3574:         } else {
                   3575:             $nothide{$user}=1;
                   3576:         }
1.470     www      3577:     }
1.351     www      3578:     my %returnhash=();
                   3579:     my %dumphash=
                   3580:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3581:     my $now=time;
1.997     raeburn  3582:     my %privileged;
1.1000    raeburn  3583:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3584: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3585:         if (($tstart) && ($tstart<0)) { next; }
                   3586:         if (($tend) && ($tend<$now)) { next; }
                   3587:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3588:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3589: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3590:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3591:             my %dompersonnel =
1.998     raeburn  3592:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3593:             $privileged{$domain} = {};
                   3594:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3595:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3596:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3597:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3598:                         $privileged{$udom}{$uname} = 1;
                   3599:                     }
                   3600:                 }
                   3601:             }
                   3602:         }
                   3603:         if ((exists($privileged{$domain}{$username})) && 
                   3604:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3605: 	if ($role eq 'cr') { next; }
1.948     raeburn  3606:         if ($codes) {
                   3607:             if ($section) { $role .= ':'.$section; }
                   3608:             if ($returnhash{$role}) {
                   3609:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3610:             } else {
                   3611:                 $returnhash{$role}=$username.':'.$domain;
                   3612:             }
1.351     www      3613:         } else {
1.988     raeburn  3614:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3615:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3616:             if ($returnhash{$key}) {
                   3617: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3618:             } else {
                   3619:                 $returnhash{$key}=$username.':'.$domain;
                   3620:             }
1.351     www      3621:         }
1.948     raeburn  3622:     }
1.400     www      3623:     return %returnhash;
                   3624: }
                   3625: 
                   3626: sub get_my_roles {
1.937     raeburn  3627:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3628:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3629:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3630:     my (%dumphash,%nothide);
1.1086    raeburn  3631:     if ($context eq 'userroles') {
1.1166    raeburn  3632:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3633:     } else {
                   3634:         %dumphash=
1.400     www      3635:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3636:         if ($hidepriv) {
                   3637:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3638:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3639:                 if ($user !~ /:/) {
                   3640:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3641:                 } else {
                   3642:                     $nothide{$user} = 1;
                   3643:                 }
                   3644:             }
                   3645:         }
1.858     raeburn  3646:     }
1.400     www      3647:     my %returnhash=();
                   3648:     my $now=time;
1.999     raeburn  3649:     my %privileged;
1.800     albertel 3650:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3651:         my ($role,$tend,$tstart);
                   3652:         if ($context eq 'userroles') {
1.1149    raeburn  3653:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3654: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3655:         } else {
                   3656:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3657:         }
1.400     www      3658:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3659:         my $status = 'active';
1.939     raeburn  3660:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3661:             $status = 'previous';
                   3662:         } 
                   3663:         if (($tstart) && ($now<$tstart)) {
                   3664:             $status = 'future';
                   3665:         }
                   3666:         if (ref($types) eq 'ARRAY') {
                   3667:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3668:                 next;
                   3669:             } 
                   3670:         } else {
                   3671:             if ($status ne 'active') {
                   3672:                 next;
                   3673:             }
                   3674:         }
1.867     raeburn  3675:         my ($rolecode,$username,$domain,$section,$area);
                   3676:         if ($context eq 'userroles') {
                   3677:             ($area,$rolecode) = split(/_/,$entry);
                   3678:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3679:         } else {
                   3680:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3681:         }
1.832     raeburn  3682:         if (ref($roledoms) eq 'ARRAY') {
                   3683:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3684:                 next;
                   3685:             }
                   3686:         }
                   3687:         if (ref($roles) eq 'ARRAY') {
                   3688:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3689:                 if ($role =~ /^cr\//) {
                   3690:                     if (!grep(/^cr$/,@{$roles})) {
                   3691:                         next;
                   3692:                     }
1.1104    raeburn  3693:                 } elsif ($role =~ /^gr\//) {
                   3694:                     if (!grep(/^gr$/,@{$roles})) {
                   3695:                         next;
                   3696:                     }
1.922     raeburn  3697:                 } else {
                   3698:                     next;
                   3699:                 }
1.832     raeburn  3700:             }
1.867     raeburn  3701:         }
1.937     raeburn  3702:         if ($hidepriv) {
1.999     raeburn  3703:             if ($context eq 'userroles') {
                   3704:                 if ((&privileged($username,$domain)) &&
                   3705:                     (!$nothide{$username.':'.$domain})) {
                   3706:                     next;
                   3707:                 }
                   3708:             } else {
                   3709:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3710:                     my %dompersonnel =
                   3711:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3712:                     $privileged{$domain} = {};
                   3713:                     if (keys(%dompersonnel)) {
                   3714:                         foreach my $server (keys(%dompersonnel)) {
                   3715:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3716:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3717:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3718:                                     $privileged{$udom}{$uname} = $trole;
                   3719:                                 }
                   3720:                             }
                   3721:                         }
                   3722:                     }
                   3723:                 }
                   3724:                 if (exists($privileged{$domain}{$username})) {
                   3725:                     if (!$nothide{$username.':'.$domain}) {
                   3726:                         next;
                   3727:                     }
                   3728:                 }
1.937     raeburn  3729:             }
                   3730:         }
1.933     raeburn  3731:         if ($withsec) {
                   3732:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3733:                 $tstart.':'.$tend;
                   3734:         } else {
                   3735:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3736:         }
1.832     raeburn  3737:     }
1.373     www      3738:     return %returnhash;
1.399     www      3739: }
                   3740: 
                   3741: # ----------------------------------------------------- Frontpage Announcements
                   3742: #
                   3743: #
                   3744: 
                   3745: sub postannounce {
                   3746:     my ($server,$text)=@_;
1.844     albertel 3747:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3748:     unless ($text=~/\w/) { $text=''; }
                   3749:     return &reply('setannounce:'.&escape($text),$server);
                   3750: }
                   3751: 
                   3752: sub getannounce {
1.448     albertel 3753: 
                   3754:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3755: 	my $announcement='';
1.800     albertel 3756: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3757: 	close($fh);
1.399     www      3758: 	if ($announcement=~/\w/) { 
                   3759: 	    return 
                   3760:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3761:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3762: 	} else {
                   3763: 	    return '';
                   3764: 	}
                   3765:     } else {
                   3766: 	return '';
                   3767:     }
1.351     www      3768: }
1.353     www      3769: 
                   3770: # ---------------------------------------------------------- Course ID routines
                   3771: # Deal with domain's nohist_courseid.db files
                   3772: #
                   3773: 
                   3774: sub courseidput {
1.921     raeburn  3775:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3776:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3777:     my $outcome;
                   3778:     if ($caller eq 'timeonly') {
                   3779:         my $cids = '';
                   3780:         foreach my $item (keys(%$storehash)) {
                   3781:             $cids.=&escape($item).'&';
                   3782:         }
                   3783:         $cids=~s/\&$//;
                   3784:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3785:                           $coursehome);       
                   3786:     } else {
                   3787:         my $items = '';
                   3788:         foreach my $item (keys(%$storehash)) {
                   3789:             $items.= &escape($item).'='.
                   3790:                      &freeze_escape($$storehash{$item}).'&';
                   3791:         }
                   3792:         $items=~s/\&$//;
                   3793:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3794:                           $coursehome);
1.918     raeburn  3795:     }
                   3796:     if ($outcome eq 'unknown_cmd') {
                   3797:         my $what;
                   3798:         foreach my $cid (keys(%$storehash)) {
                   3799:             $what .= &escape($cid).'=';
1.921     raeburn  3800:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3801:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3802:             }
                   3803:             $what =~ s/\:$/&/;
                   3804:         }
                   3805:         $what =~ s/\&$//;  
                   3806:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3807:     } else {
                   3808:         return $outcome;
                   3809:     }
1.353     www      3810: }
                   3811: 
                   3812: sub courseiddump {
1.921     raeburn  3813:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3814:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3815:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3816:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3817:     my $as_hash = 1;
                   3818:     my %returnhash;
                   3819:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3820:     my %libserv = &all_library();
                   3821:     foreach my $tryserver (keys(%libserv)) {
                   3822:         if ( (  $hostidflag == 1 
                   3823: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3824: 	     || (!defined($hostidflag)) ) {
                   3825: 
1.918     raeburn  3826: 	    if (($domfilter eq '') ||
                   3827: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 3828:                 my $rep;
                   3829:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   3830:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   3831:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   3832:                                 &escape($descfilter), &escape($instcodefilter), 
                   3833:                                 &escape($ownerfilter), &escape($coursefilter),
                   3834:                                 &escape($typefilter), &escape($regexp_ok), 
                   3835:                                 $as_hash, &escape($selfenrollonly), 
                   3836:                                 &escape($catfilter), $showhidden, $caller, 
                   3837:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   3838:                                 &escape($createdbefore), &escape($createdafter), 
                   3839:                                 &escape($creationcontext), $domcloner)));
                   3840:                 } else {
                   3841:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3842:                              $sincefilter.':'.&escape($descfilter).':'.
                   3843:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   3844:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   3845:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   3846:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   3847:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   3848:                              &escape($cc_clone).':'.$cloneonly.':'.
                   3849:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   3850:                              &escape($creationcontext).':'.$domcloner,
                   3851:                              $tryserver);
                   3852:                 }
                   3853:                      
1.918     raeburn  3854:                 my @pairs=split(/\&/,$rep);
                   3855:                 foreach my $item (@pairs) {
                   3856:                     my ($key,$value)=split(/\=/,$item,2);
                   3857:                     $key = &unescape($key);
                   3858:                     next if ($key =~ /^error: 2 /);
                   3859:                     my $result = &thaw_unescape($value);
                   3860:                     if (ref($result) eq 'HASH') {
                   3861:                         $returnhash{$key}=$result;
                   3862:                     } else {
1.921     raeburn  3863:                         my @responses = split(/:/,$value);
                   3864:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3865:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3866:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3867:                         }
1.1008    raeburn  3868:                     }
1.353     www      3869:                 }
                   3870:             }
                   3871:         }
                   3872:     }
                   3873:     return %returnhash;
                   3874: }
                   3875: 
1.1055    raeburn  3876: sub courselastaccess {
                   3877:     my ($cdom,$cnum,$hostidref) = @_;
                   3878:     my %returnhash;
                   3879:     if ($cdom && $cnum) {
                   3880:         my $chome = &homeserver($cnum,$cdom);
                   3881:         if ($chome ne 'no_host') {
                   3882:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3883:             &extract_lastaccess(\%returnhash,$rep);
                   3884:         }
                   3885:     } else {
                   3886:         if (!$cdom) { $cdom=''; }
                   3887:         my %libserv = &all_library();
                   3888:         foreach my $tryserver (keys(%libserv)) {
                   3889:             if (ref($hostidref) eq 'ARRAY') {
                   3890:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3891:             } 
                   3892:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3893:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3894:                 &extract_lastaccess(\%returnhash,$rep);
                   3895:             }
                   3896:         }
                   3897:     }
                   3898:     return %returnhash;
                   3899: }
                   3900: 
                   3901: sub extract_lastaccess {
                   3902:     my ($returnhash,$rep) = @_;
                   3903:     if (ref($returnhash) eq 'HASH') {
                   3904:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3905:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3906:                  $rep eq '') {
                   3907:             my @pairs=split(/\&/,$rep);
                   3908:             foreach my $item (@pairs) {
                   3909:                 my ($key,$value)=split(/\=/,$item,2);
                   3910:                 $key = &unescape($key);
                   3911:                 next if ($key =~ /^error: 2 /);
                   3912:                 $returnhash->{$key} = &thaw_unescape($value);
                   3913:             }
                   3914:         }
                   3915:     }
                   3916:     return;
                   3917: }
                   3918: 
1.658     raeburn  3919: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3920: 
                   3921: sub dcmailput {
1.685     raeburn  3922:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3923:     my $status = &Apache::lonnet::critical(
1.740     www      3924:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3925:        &escape($message),$server);
1.662     raeburn  3926:     return $status;
                   3927: }
                   3928: 
1.658     raeburn  3929: sub dcmaildump {
                   3930:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3931:     my %returnhash=();
1.846     albertel 3932: 
                   3933:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3934:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3935:                                                          &escape($enddate).':';
                   3936: 	my @esc_senders=map { &escape($_)} @$senders;
                   3937: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3938: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3939:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3940:             if (($key) && ($value)) {
                   3941:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3942:             }
                   3943:         }
                   3944:     }
                   3945:     return %returnhash;
                   3946: }
1.662     raeburn  3947: # ---------------------------------------------------------- Domain roles
                   3948: 
                   3949: sub get_domain_roles {
                   3950:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3951:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3952:         $startdate = '.';
                   3953:     }
1.1018    raeburn  3954:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3955:         $enddate = '.';
                   3956:     }
1.922     raeburn  3957:     my $rolelist;
                   3958:     if (ref($roles) eq 'ARRAY') {
                   3959:         $rolelist = join(':',@{$roles});
                   3960:     }
1.662     raeburn  3961:     my %personnel = ();
1.841     albertel 3962: 
                   3963:     my %servers = &get_servers($dom,'library');
                   3964:     foreach my $tryserver (keys(%servers)) {
                   3965: 	%{$personnel{$tryserver}}=();
                   3966: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3967: 					    &escape($startdate).':'.
                   3968: 					    &escape($enddate).':'.
                   3969: 					    &escape($rolelist), $tryserver))) {
                   3970: 	    my ($key,$value) = split(/\=/,$line,2);
                   3971: 	    if (($key) && ($value)) {
                   3972: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3973: 	    }
                   3974: 	}
1.662     raeburn  3975:     }
                   3976:     return %personnel;
                   3977: }
1.658     raeburn  3978: 
1.1057    www      3979: # ----------------------------------------------------------- Interval timing 
1.149     www      3980: 
1.1153    www      3981: {
                   3982: # Caches needed for speedup of navmaps
                   3983: # We don't want to cache this for very long at all (5 seconds at most)
                   3984: # 
                   3985: # The user for whom we cache
                   3986: my $cachedkey='';
                   3987: # The cached times for this user
                   3988: my %cachedtimes=();
                   3989: # When this was last done
                   3990: my $cachedtime=();
                   3991: 
                   3992: sub load_all_first_access {
1.1154    raeburn  3993:     my ($uname,$udom)=@_;
1.1156    www      3994:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  3995:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  3996:         return;
                   3997:     }
                   3998:     $cachedtime=time;
                   3999:     $cachedkey=$uname.':'.$udom;
                   4000:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4001: }
                   4002: 
1.504     albertel 4003: sub get_first_access {
1.1162    raeburn  4004:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4005:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4006:     if ($argsymb) { $symb=$argsymb; }
                   4007:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4008:     if ($argmap) { $map = $argmap; }
1.926     albertel 4009:     if ($type eq 'course') {
                   4010: 	$res='course';
                   4011:     } elsif ($type eq 'map') {
1.588     albertel 4012: 	$res=&symbread($map);
                   4013:     } else {
                   4014: 	$res=$symb;
                   4015:     }
1.1153    www      4016:     &load_all_first_access($uname,$udom);
                   4017:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4018: }
                   4019: 
                   4020: sub set_first_access {
1.1162    raeburn  4021:     my ($type,$interval)=@_;
1.790     albertel 4022:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4023:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4024:     if ($type eq 'course') {
                   4025: 	$res='course';
                   4026:     } elsif ($type eq 'map') {
1.588     albertel 4027: 	$res=&symbread($map);
                   4028:     } else {
                   4029: 	$res=$symb;
                   4030:     }
1.1153    www      4031:     $cachedkey='';
1.1162    raeburn  4032:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4033:     if (!$firstaccess) {
1.1162    raeburn  4034:         my $start = time;
                   4035: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4036:                           $udom,$uname);
                   4037:         if ($putres eq 'ok') {
                   4038:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4039:                  $udom,$uname); 
                   4040:             &appenv(
                   4041:                      {
                   4042:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4043:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4044:                      }
                   4045:                   );
                   4046:         }
                   4047:         return $putres;
1.505     albertel 4048:     }
                   4049:     return 'already_set';
1.504     albertel 4050: }
1.1153    www      4051: }
1.110     www      4052: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4053: 
                   4054: sub expirespread {
                   4055:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4056:     my $cid=$env{'request.course.id'}; 
1.110     www      4057:     if ($cid) {
                   4058:        my $now=time;
                   4059:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4060:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4061:                             $env{'course.'.$cid.'.num'}.
1.110     www      4062: 	        	    ':nohist_expirationdates:'.
                   4063:                             &escape($key).'='.$now,
1.620     albertel 4064:                             $env{'course.'.$cid.'.home'})
1.110     www      4065:     }
                   4066:     return 'ok';
1.14      www      4067: }
                   4068: 
1.109     www      4069: # ----------------------------------------------------- Devalidate Spreadsheets
                   4070: 
                   4071: sub devalidate {
1.325     www      4072:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4073:     my $cid=$env{'request.course.id'}; 
1.109     www      4074:     if ($cid) {
1.391     matthew  4075:         # delete the stored spreadsheets for
                   4076:         # - the student level sheet of this user in course's homespace
                   4077:         # - the assessment level sheet for this resource 
                   4078:         #   for this user in user's homespace
1.553     albertel 4079: 	# - current conditional state info
1.325     www      4080: 	my $key=$uname.':'.$udom.':';
1.109     www      4081:         my $status=
1.299     matthew  4082: 	    &del('nohist_calculatedsheets',
1.391     matthew  4083: 		 [$key.'studentcalc:'],
1.620     albertel 4084: 		 $env{'course.'.$cid.'.domain'},
                   4085: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4086: 		.' '.
                   4087: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4088: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4089:         unless ($status eq 'ok ok') {
                   4090:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4091:                     $uname.' at '.$udom.' for '.
1.109     www      4092: 		    $symb.': '.$status);
1.133     albertel 4093:         }
1.553     albertel 4094: 	&delenv('user.state.'.$cid);
1.109     www      4095:     }
                   4096: }
                   4097: 
1.265     albertel 4098: sub get_scalar {
                   4099:     my ($string,$end) = @_;
                   4100:     my $value;
                   4101:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4102: 	$value = $1;
                   4103:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4104: 	$value = $1;
                   4105:     }
                   4106:     return &unescape($value);
                   4107: }
                   4108: 
                   4109: sub array2str {
                   4110:   my (@array) = @_;
                   4111:   my $result=&arrayref2str(\@array);
                   4112:   $result=~s/^__ARRAY_REF__//;
                   4113:   $result=~s/__END_ARRAY_REF__$//;
                   4114:   return $result;
                   4115: }
                   4116: 
1.204     albertel 4117: sub arrayref2str {
                   4118:   my ($arrayref) = @_;
1.265     albertel 4119:   my $result='__ARRAY_REF__';
1.204     albertel 4120:   foreach my $elem (@$arrayref) {
1.265     albertel 4121:     if(ref($elem) eq 'ARRAY') {
                   4122:       $result.=&arrayref2str($elem).'&';
                   4123:     } elsif(ref($elem) eq 'HASH') {
                   4124:       $result.=&hashref2str($elem).'&';
                   4125:     } elsif(ref($elem)) {
                   4126:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4127:     } else {
                   4128:       $result.=&escape($elem).'&';
                   4129:     }
                   4130:   }
                   4131:   $result=~s/\&$//;
1.265     albertel 4132:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4133:   return $result;
                   4134: }
                   4135: 
1.168     albertel 4136: sub hash2str {
1.204     albertel 4137:   my (%hash) = @_;
                   4138:   my $result=&hashref2str(\%hash);
1.265     albertel 4139:   $result=~s/^__HASH_REF__//;
                   4140:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4141:   return $result;
                   4142: }
                   4143: 
                   4144: sub hashref2str {
                   4145:   my ($hashref)=@_;
1.265     albertel 4146:   my $result='__HASH_REF__';
1.800     albertel 4147:   foreach my $key (sort(keys(%$hashref))) {
                   4148:     if (ref($key) eq 'ARRAY') {
                   4149:       $result.=&arrayref2str($key).'=';
                   4150:     } elsif (ref($key) eq 'HASH') {
                   4151:       $result.=&hashref2str($key).'=';
                   4152:     } elsif (ref($key)) {
1.265     albertel 4153:       $result.='=';
1.800     albertel 4154:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4155:     } else {
1.1132    raeburn  4156: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4157:     }
                   4158: 
1.800     albertel 4159:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4160:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4161:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4162:       $result.=&hashref2str($hashref->{$key}).'&';
                   4163:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4164:        $result.='&';
1.800     albertel 4165:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4166:     } else {
1.800     albertel 4167:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4168:     }
                   4169:   }
1.168     albertel 4170:   $result=~s/\&$//;
1.265     albertel 4171:   $result .= '__END_HASH_REF__';
1.168     albertel 4172:   return $result;
                   4173: }
                   4174: 
                   4175: sub str2hash {
1.265     albertel 4176:     my ($string)=@_;
                   4177:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4178:     return %$hash;
                   4179: }
                   4180: 
                   4181: sub str2hashref {
1.168     albertel 4182:   my ($string) = @_;
1.265     albertel 4183: 
                   4184:   my %hash;
                   4185: 
                   4186:   if($string !~ /^__HASH_REF__/) {
                   4187:       if (! ($string eq '' || !defined($string))) {
                   4188: 	  $hash{'error'}='Not hash reference';
                   4189:       }
                   4190:       return (\%hash, $string);
                   4191:   }
                   4192: 
                   4193:   $string =~ s/^__HASH_REF__//;
                   4194: 
                   4195:   while($string !~ /^__END_HASH_REF__/) {
                   4196:       #key
                   4197:       my $key='';
                   4198:       if($string =~ /^__HASH_REF__/) {
                   4199:           ($key, $string)=&str2hashref($string);
                   4200:           if(defined($key->{'error'})) {
                   4201:               $hash{'error'}='Bad data';
                   4202:               return (\%hash, $string);
                   4203:           }
                   4204:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4205:           ($key, $string)=&str2arrayref($string);
                   4206:           if($key->[0] eq 'Array reference error') {
                   4207:               $hash{'error'}='Bad data';
                   4208:               return (\%hash, $string);
                   4209:           }
                   4210:       } else {
                   4211:           $string =~ s/^(.*?)=//;
1.267     albertel 4212: 	  $key=&unescape($1);
1.265     albertel 4213:       }
                   4214:       $string =~ s/^=//;
                   4215: 
                   4216:       #value
                   4217:       my $value='';
                   4218:       if($string =~ /^__HASH_REF__/) {
                   4219:           ($value, $string)=&str2hashref($string);
                   4220:           if(defined($value->{'error'})) {
                   4221:               $hash{'error'}='Bad data';
                   4222:               return (\%hash, $string);
                   4223:           }
                   4224:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4225:           ($value, $string)=&str2arrayref($string);
                   4226:           if($value->[0] eq 'Array reference error') {
                   4227:               $hash{'error'}='Bad data';
                   4228:               return (\%hash, $string);
                   4229:           }
                   4230:       } else {
                   4231: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4232:       }
                   4233:       $string =~ s/^&//;
                   4234: 
                   4235:       $hash{$key}=$value;
1.204     albertel 4236:   }
1.265     albertel 4237: 
                   4238:   $string =~ s/^__END_HASH_REF__//;
                   4239: 
                   4240:   return (\%hash, $string);
1.204     albertel 4241: }
                   4242: 
                   4243: sub str2array {
1.265     albertel 4244:     my ($string)=@_;
                   4245:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4246:     return @$array;
                   4247: }
                   4248: 
                   4249: sub str2arrayref {
1.204     albertel 4250:   my ($string) = @_;
1.265     albertel 4251:   my @array;
                   4252: 
                   4253:   if($string !~ /^__ARRAY_REF__/) {
                   4254:       if (! ($string eq '' || !defined($string))) {
                   4255: 	  $array[0]='Array reference error';
                   4256:       }
                   4257:       return (\@array, $string);
                   4258:   }
                   4259: 
                   4260:   $string =~ s/^__ARRAY_REF__//;
                   4261: 
                   4262:   while($string !~ /^__END_ARRAY_REF__/) {
                   4263:       my $value='';
                   4264:       if($string =~ /^__HASH_REF__/) {
                   4265:           ($value, $string)=&str2hashref($string);
                   4266:           if(defined($value->{'error'})) {
                   4267:               $array[0] ='Array reference error';
                   4268:               return (\@array, $string);
                   4269:           }
                   4270:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4271:           ($value, $string)=&str2arrayref($string);
                   4272:           if($value->[0] eq 'Array reference error') {
                   4273:               $array[0] ='Array reference error';
                   4274:               return (\@array, $string);
                   4275:           }
                   4276:       } else {
                   4277: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4278:       }
                   4279:       $string =~ s/^&//;
                   4280: 
                   4281:       push(@array, $value);
1.191     harris41 4282:   }
1.265     albertel 4283: 
                   4284:   $string =~ s/^__END_ARRAY_REF__//;
                   4285: 
                   4286:   return (\@array, $string);
1.168     albertel 4287: }
                   4288: 
1.167     albertel 4289: # -------------------------------------------------------------------Temp Store
                   4290: 
1.168     albertel 4291: sub tmpreset {
                   4292:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4293:   if (!$symb) {
                   4294:     $symb=&symbread();
1.620     albertel 4295:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4296:   }
                   4297:   $symb=escape($symb);
                   4298: 
1.620     albertel 4299:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4300:   $namespace=~s/\//\_/g;
                   4301:   $namespace=~s/\W//g;
                   4302: 
1.620     albertel 4303:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4304:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4305:   if ($domain eq 'public' && $stuname eq 'public') {
                   4306:       $stuname=$ENV{'REMOTE_ADDR'};
                   4307:   }
1.1117    foxr     4308:   my $path=LONCAPA::tempdir();
1.168     albertel 4309:   my %hash;
                   4310:   if (tie(%hash,'GDBM_File',
                   4311: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4312: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4313:     foreach my $key (keys(%hash)) {
1.180     albertel 4314:       if ($key=~ /:$symb/) {
1.168     albertel 4315: 	delete($hash{$key});
                   4316:       }
                   4317:     }
                   4318:   }
                   4319: }
                   4320: 
1.167     albertel 4321: sub tmpstore {
1.168     albertel 4322:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4323: 
                   4324:   if (!$symb) {
                   4325:     $symb=&symbread();
1.620     albertel 4326:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4327:   }
                   4328:   $symb=escape($symb);
                   4329: 
                   4330:   if (!$namespace) {
                   4331:     # I don't think we would ever want to store this for a course.
                   4332:     # it seems this will only be used if we don't have a course.
1.620     albertel 4333:     #$namespace=$env{'request.course.id'};
1.168     albertel 4334:     #if (!$namespace) {
1.620     albertel 4335:       $namespace=$env{'request.state'};
1.168     albertel 4336:     #}
                   4337:   }
                   4338:   $namespace=~s/\//\_/g;
                   4339:   $namespace=~s/\W//g;
1.620     albertel 4340:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4341:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4342:   if ($domain eq 'public' && $stuname eq 'public') {
                   4343:       $stuname=$ENV{'REMOTE_ADDR'};
                   4344:   }
1.168     albertel 4345:   my $now=time;
                   4346:   my %hash;
1.1117    foxr     4347:   my $path=LONCAPA::tempdir();
1.168     albertel 4348:   if (tie(%hash,'GDBM_File',
                   4349: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4350: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4351:     $hash{"version:$symb"}++;
                   4352:     my $version=$hash{"version:$symb"};
                   4353:     my $allkeys=''; 
                   4354:     foreach my $key (keys(%$storehash)) {
                   4355:       $allkeys.=$key.':';
1.591     albertel 4356:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4357:     }
                   4358:     $hash{"$version:$symb:timestamp"}=$now;
                   4359:     $allkeys.='timestamp';
                   4360:     $hash{"$version:keys:$symb"}=$allkeys;
                   4361:     if (untie(%hash)) {
                   4362:       return 'ok';
                   4363:     } else {
                   4364:       return "error:$!";
                   4365:     }
                   4366:   } else {
                   4367:     return "error:$!";
                   4368:   }
                   4369: }
1.167     albertel 4370: 
1.168     albertel 4371: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4372: 
1.168     albertel 4373: sub tmprestore {
                   4374:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4375: 
1.168     albertel 4376:   if (!$symb) {
                   4377:     $symb=&symbread();
1.620     albertel 4378:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4379:   }
                   4380:   $symb=escape($symb);
                   4381: 
1.620     albertel 4382:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4383: 
1.620     albertel 4384:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4385:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4386:   if ($domain eq 'public' && $stuname eq 'public') {
                   4387:       $stuname=$ENV{'REMOTE_ADDR'};
                   4388:   }
1.168     albertel 4389:   my %returnhash;
                   4390:   $namespace=~s/\//\_/g;
                   4391:   $namespace=~s/\W//g;
                   4392:   my %hash;
1.1117    foxr     4393:   my $path=LONCAPA::tempdir();
1.168     albertel 4394:   if (tie(%hash,'GDBM_File',
                   4395: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4396: 	  &GDBM_READER(),0640)) {
1.168     albertel 4397:     my $version=$hash{"version:$symb"};
                   4398:     $returnhash{'version'}=$version;
                   4399:     my $scope;
                   4400:     for ($scope=1;$scope<=$version;$scope++) {
                   4401:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4402:       my @keys=split(/:/,$vkeys);
                   4403:       my $key;
                   4404:       $returnhash{"$scope:keys"}=$vkeys;
                   4405:       foreach $key (@keys) {
1.591     albertel 4406: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4407: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4408:       }
                   4409:     }
1.168     albertel 4410:     if (!(untie(%hash))) {
                   4411:       return "error:$!";
                   4412:     }
                   4413:   } else {
                   4414:     return "error:$!";
                   4415:   }
                   4416:   return %returnhash;
1.167     albertel 4417: }
                   4418: 
1.9       www      4419: # ----------------------------------------------------------------------- Store
                   4420: 
                   4421: sub store {
1.124     www      4422:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4423:     my $home='';
                   4424: 
1.168     albertel 4425:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4426: 
1.213     www      4427:     $symb=&symbclean($symb);
1.122     albertel 4428:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4429: 
1.620     albertel 4430:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4431:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4432: 
                   4433:     &devalidate($symb,$stuname,$domain);
1.109     www      4434: 
                   4435:     $symb=escape($symb);
1.187     www      4436:     if (!$namespace) { 
1.620     albertel 4437:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4438:           return ''; 
                   4439:        } 
                   4440:     }
1.620     albertel 4441:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4442: 
                   4443:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4444:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4445: 
1.12      www      4446:     my $namevalue='';
1.800     albertel 4447:     foreach my $key (keys(%$storehash)) {
                   4448:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4449:     }
1.12      www      4450:     $namevalue=~s/\&$//;
1.187     www      4451:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4452:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4453: }
                   4454: 
1.47      www      4455: # -------------------------------------------------------------- Critical Store
                   4456: 
                   4457: sub cstore {
1.124     www      4458:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4459:     my $home='';
                   4460: 
1.168     albertel 4461:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4462: 
1.213     www      4463:     $symb=&symbclean($symb);
1.122     albertel 4464:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4465: 
1.620     albertel 4466:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4467:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4468: 
                   4469:     &devalidate($symb,$stuname,$domain);
1.109     www      4470: 
                   4471:     $symb=escape($symb);
1.187     www      4472:     if (!$namespace) { 
1.620     albertel 4473:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4474:           return ''; 
                   4475:        } 
                   4476:     }
1.620     albertel 4477:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4478: 
                   4479:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4480:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4481: 
1.47      www      4482:     my $namevalue='';
1.800     albertel 4483:     foreach my $key (keys(%$storehash)) {
                   4484:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4485:     }
1.47      www      4486:     $namevalue=~s/\&$//;
1.187     www      4487:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4488:     return critical
                   4489:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4490: }
                   4491: 
1.9       www      4492: # --------------------------------------------------------------------- Restore
                   4493: 
                   4494: sub restore {
1.124     www      4495:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4496:     my $home='';
                   4497: 
1.168     albertel 4498:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4499: 
1.122     albertel 4500:     if (!$symb) {
                   4501:       unless ($symb=escape(&symbread())) { return ''; }
                   4502:     } else {
1.213     www      4503:       $symb=&escape(&symbclean($symb));
1.122     albertel 4504:     }
1.188     www      4505:     if (!$namespace) { 
1.620     albertel 4506:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4507:           return ''; 
                   4508:        } 
                   4509:     }
1.620     albertel 4510:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4511:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4512:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4513:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4514: 
1.12      www      4515:     my %returnhash=();
1.800     albertel 4516:     foreach my $line (split(/\&/,$answer)) {
                   4517: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4518:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4519:     }
1.75      www      4520:     my $version;
                   4521:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4522:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4523:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4524:        }
1.75      www      4525:     }
1.13      www      4526:     return %returnhash;
1.34      www      4527: }
                   4528: 
                   4529: # ---------------------------------------------------------- Course Description
1.1118    foxr     4530: #
                   4531: #  
1.34      www      4532: 
                   4533: sub coursedescription {
1.731     albertel 4534:     my ($courseid,$args)=@_;
1.34      www      4535:     $courseid=~s/^\///;
1.49      www      4536:     $courseid=~s/\_/\//g;
1.34      www      4537:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4538:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4539:     my $normalid=$cdomain.'_'.$cnum;
                   4540:     # need to always cache even if we get errors otherwise we keep 
                   4541:     # trying and trying and trying to get the course description.
                   4542:     my %envhash=();
                   4543:     my %returnhash=();
1.731     albertel 4544:     
                   4545:     my $expiretime=600;
                   4546:     if ($env{'request.course.id'} eq $normalid) {
                   4547: 	$expiretime=120;
                   4548:     }
                   4549: 
                   4550:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4551:     if (!$args->{'freshen_cache'}
                   4552: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4553: 	foreach my $key (keys(%env)) {
                   4554: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4555: 	    my ($setting) = $1;
                   4556: 	    $returnhash{$setting} = $env{$key};
                   4557: 	}
                   4558: 	return %returnhash;
                   4559:     }
                   4560: 
1.1118    foxr     4561:     # get the data again
                   4562: 
1.731     albertel 4563:     if (!$args->{'one_time'}) {
                   4564: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4565:     }
1.811     albertel 4566: 
1.34      www      4567:     if ($chome ne 'no_host') {
1.302     albertel 4568:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4569:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4570: 	   my $username = $env{'user.name'}; # Defult username
                   4571: 	   if(defined $args->{'user'}) {
                   4572: 	       $username = $args->{'user'};
                   4573: 	   }
1.129     albertel 4574:            $returnhash{'home'}= $chome;
                   4575: 	   $returnhash{'domain'} = $cdomain;
                   4576: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4577:            if (!defined($returnhash{'type'})) {
                   4578:                $returnhash{'type'} = 'Course';
                   4579:            }
1.130     albertel 4580:            while (my ($name,$value) = each %returnhash) {
1.53      www      4581:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4582:            }
1.270     www      4583:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4584:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4585: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4586:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4587:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4588:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4589:        }
                   4590:     }
1.731     albertel 4591:     if (!$args->{'one_time'}) {
1.949     raeburn  4592: 	&appenv(\%envhash);
1.731     albertel 4593:     }
1.302     albertel 4594:     return %returnhash;
1.461     www      4595: }
                   4596: 
1.1080    raeburn  4597: sub update_released_required {
                   4598:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4599:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4600:         $cid = $env{'request.course.id'};
                   4601:         $cdom = $env{'course.'.$cid.'.domain'};
                   4602:         $cnum = $env{'course.'.$cid.'.num'};
                   4603:         $chome = $env{'course.'.$cid.'.home'};
                   4604:     }
                   4605:     if ($needsrelease) {
                   4606:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4607:         my $needsupdate;
                   4608:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4609:             $needsupdate = 1;
                   4610:         } else {
                   4611:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4612:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4613:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4614:                 $needsupdate = 1;
                   4615:             }
                   4616:         }
                   4617:         if ($needsupdate) {
                   4618:             my %needshash = (
                   4619:                              'internal.releaserequired' => $needsrelease,
                   4620:                             );
                   4621:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4622:             if ($putresult eq 'ok') {
                   4623:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4624:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4625:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4626:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4627:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4628:                 }
                   4629:             }
                   4630:         }
                   4631:     }
                   4632:     return;
                   4633: }
                   4634: 
1.461     www      4635: # -------------------------------------------------See if a user is privileged
                   4636: 
                   4637: sub privileged {
                   4638:     my ($username,$domain)=@_;
1.1170    droeschl 4639: 
                   4640:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4641:     my $now = time;
                   4642: 
                   4643:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4644:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4645:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4646:                 return 1 unless ($tend && $tend < $now) 
                   4647:                     or ($tstart && $tstart > $now);
                   4648:             }
1.461     www      4649: 	}
1.1170    droeschl 4650: 
1.461     www      4651:     return 0;
1.9       www      4652: }
1.1       albertel 4653: 
1.103     harris41 4654: # -------------------------------------------------------- Get user privileges
1.11      www      4655: 
                   4656: sub rolesinit {
1.1169    droeschl 4657:     my ($domain, $username) = @_;
                   4658:     my %userroles = ('user.login.time' => time);
                   4659:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4660: 
                   4661:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4662:     # also, blocking can be triggered by an activating timer
                   4663:     # it's saved in the user's %env.
                   4664:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4665:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4666:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4667:         %timerintchk, %timerintenv);
                   4668: 
1.1162    raeburn  4669:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4670:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4671:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4672:     }
1.1169    droeschl 4673: 
1.1162    raeburn  4674:     foreach my $key (keys(%timerinterval)) {
                   4675:         my ($cid,$rest) = split(/\0/,$key);
                   4676:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4677:     }
1.1169    droeschl 4678: 
1.11      www      4679:     my %allroles=();
1.1162    raeburn  4680:     my %allgroups=();
1.11      www      4681: 
1.1169    droeschl 4682:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4683:         my $role = $rolesdump{$area};
                   4684:         $area =~ s/\_\w\w$//;
                   4685: 
                   4686:         my ($trole, $tend, $tstart, $group_privs);
                   4687: 
                   4688:         if ($role =~ /^cr/) {
                   4689:         # Custom role, defined by a user 
                   4690:         # e.g., user.role.cr/msu/smith/mynewrole
                   4691:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4692:                 $trole = $1;
                   4693:                 ($tend, $tstart) = split('_', $2);
                   4694:             } else {
                   4695:                 $trole = $role;
                   4696:             }
                   4697:         } elsif ($role =~ m|^gr/|) {
                   4698:         # Role of member in a group, defined within a course/community
                   4699:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4700:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4701:             next if $tstart eq '-1';
                   4702:             ($trole, $group_privs) = split(/\//, $trole);
                   4703:             $group_privs = &unescape($group_privs);
                   4704:         } else {
                   4705:         # Just a normal role, defined in roles.tab
                   4706:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4707:         }
                   4708: 
                   4709:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4710:                  $username);
                   4711:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4712: 
                   4713:         # role expired or not available yet?
                   4714:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4715:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4716: 
                   4717:         next if $area eq '' or $trole eq '';
                   4718: 
                   4719:         my $spec = "$trole.$area";
                   4720:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4721: 
                   4722:         if ($trole =~ /^cr\//) {
                   4723:         # Custom role, defined by a user
                   4724:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4725:         } elsif ($trole eq 'gr') {
                   4726:         # Role of a member in a group, defined within a course/community
                   4727:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4728:             next;
                   4729:         } else {
                   4730:         # Normal role, defined in roles.tab
                   4731:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4732:         }
                   4733: 
                   4734:         my $cid = $tdomain.'_'.$trest;
                   4735:         unless ($firstaccchk{$cid}) {
                   4736:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4737:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4738:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4739:                         $coursetimerstarts{$cid}{$item}; 
                   4740:                 }
                   4741:             }
                   4742:             $firstaccchk{$cid} = 1;
                   4743:         }
                   4744:         unless ($timerintchk{$cid}) {
                   4745:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4746:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4747:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4748:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4749:                 }
1.12      www      4750:             }
1.1169    droeschl 4751:             $timerintchk{$cid} = 1;
1.191     harris41 4752:         }
1.11      www      4753:     }
1.1169    droeschl 4754: 
                   4755:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4756:         \%allroles, \%allgroups);
                   4757:     $env{'user.adv'} = $userroles{'user.adv'};
                   4758: 
1.1162    raeburn  4759:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4760: }
                   4761: 
1.567     raeburn  4762: sub set_arearole {
                   4763:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4764: # log the associated role with the area
                   4765:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4766:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4767: }
                   4768: 
                   4769: sub custom_roleprivs {
                   4770:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4771:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4772:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4773:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4774:         my ($rdummy,$roledef)=
                   4775:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4776:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4777:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4778:             if (defined($syspriv)) {
1.1043    raeburn  4779:                 if ($trest =~ /^$match_community$/) {
                   4780:                     $syspriv =~ s/bre\&S//; 
                   4781:                 }
1.567     raeburn  4782:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4783:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4784:             }
                   4785:             if ($tdomain ne '') {
                   4786:                 if (defined($dompriv)) {
                   4787:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4788:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4789:                 }
                   4790:                 if (($trest ne '') && (defined($coursepriv))) {
                   4791:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4792:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4793:                 }
                   4794:             }
                   4795:         }
                   4796:     }
                   4797: }
                   4798: 
1.678     raeburn  4799: sub group_roleprivs {
                   4800:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4801:     my $access = 1;
                   4802:     my $now = time;
                   4803:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4804:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4805:     if ($access) {
1.811     albertel 4806:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4807:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4808:     }
                   4809: }
1.567     raeburn  4810: 
                   4811: sub standard_roleprivs {
                   4812:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4813:     if (defined($pr{$trole.':s'})) {
                   4814:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4815:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4816:     }
                   4817:     if ($tdomain ne '') {
                   4818:         if (defined($pr{$trole.':d'})) {
                   4819:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4820:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4821:         }
                   4822:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4823:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4824:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4825:         }
                   4826:     }
                   4827: }
                   4828: 
                   4829: sub set_userprivs {
1.1064    raeburn  4830:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4831:     my $author=0;
                   4832:     my $adv=0;
1.678     raeburn  4833:     my %grouproles = ();
                   4834:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4835:         my @groupkeys; 
1.1000    raeburn  4836:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4837:             push(@groupkeys,$role);
                   4838:         }
                   4839:         if (ref($groups_roles) eq 'HASH') {
                   4840:             foreach my $key (keys(%{$groups_roles})) {
                   4841:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4842:                     push(@groupkeys,$key);
                   4843:                 }
                   4844:             }
                   4845:         }
                   4846:         if (@groupkeys > 0) {
                   4847:             foreach my $role (@groupkeys) {
                   4848:                 my ($trole,$area,$sec,$extendedarea);
                   4849:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4850:                     $trole = $1;
                   4851:                     $area = $2;
                   4852:                     $sec = $3;
                   4853:                     $extendedarea = $area.$sec;
                   4854:                     if (exists($$allgroups{$area})) {
                   4855:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4856:                             my $spec = $trole.'.'.$extendedarea;
                   4857:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4858:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4859:                         }
1.678     raeburn  4860:                     }
                   4861:                 }
                   4862:             }
                   4863:         }
                   4864:     }
1.800     albertel 4865:     foreach my $group (keys(%grouproles)) {
                   4866:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4867:     }
1.800     albertel 4868:     foreach my $role (keys(%{$allroles})) {
                   4869:         my %thesepriv;
1.941     raeburn  4870:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4871:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4872:             if ($item ne '') {
                   4873:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4874:                 if ($restrictions eq '') {
                   4875:                     $thesepriv{$privilege}='F';
                   4876:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4877:                     $thesepriv{$privilege}.=$restrictions;
                   4878:                 }
                   4879:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4880:             }
                   4881:         }
                   4882:         my $thesestr='';
1.1104    raeburn  4883:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4884: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4885: 	}
                   4886:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4887:     }
                   4888:     return ($author,$adv);
                   4889: }
                   4890: 
1.994     raeburn  4891: sub role_status {
1.1104    raeburn  4892:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4893:     my @pwhere = ();
                   4894:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4895:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4896:         unless (!defined($$role) || $$role eq '') {
                   4897:             $$where=join('.',@pwhere);
                   4898:             $$trolecode=$$role.'.'.$$where;
                   4899:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4900:             $$tstatus='is';
1.1104    raeburn  4901:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4902:                 $$tstatus='future';
1.1034    raeburn  4903:                 if ($$tstart<$now) {
                   4904:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4905:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4906:                             my (%allroles,%allgroups,$group_privs,
                   4907:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4908:                             my %userroles = (
                   4909:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4910:                             );
1.1064    raeburn  4911:                             @rolecodes = ('cm'); 
1.1002    raeburn  4912:                             my $spec=$$role.'.'.$$where;
                   4913:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4914:                             if ($$role =~ /^cr\//) {
                   4915:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4916:                                 push(@rolecodes,'cr');
1.1002    raeburn  4917:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4918:                                 push(@rolecodes,$$role);
1.1002    raeburn  4919:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4920:                                                     $env{'user.name'});
1.1064    raeburn  4921:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4922:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4923:                                 $group_privs = &unescape($group_privs);
                   4924:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4925:                                 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  4926:                                 &get_groups_roles($tdomain,$trest,
                   4927:                                                   \%course_roles,\@rolecodes,
                   4928:                                                   \%groups_roles);
1.1002    raeburn  4929:                             } else {
1.1064    raeburn  4930:                                 push(@rolecodes,$$role);
1.1002    raeburn  4931:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4932:                             }
1.1064    raeburn  4933:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4934:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4935:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4936:                         }
                   4937:                     }
1.1034    raeburn  4938:                     $$tstatus = 'is';
1.1002    raeburn  4939:                 }
1.994     raeburn  4940:             }
                   4941:             if ($$tend) {
1.1104    raeburn  4942:                 if ($$tend<$update) {
1.994     raeburn  4943:                     $$tstatus='expired';
                   4944:                 } elsif ($$tend<$now) {
                   4945:                     $$tstatus='will_not';
                   4946:                 }
                   4947:             }
                   4948:         }
                   4949:     }
                   4950: }
                   4951: 
1.1104    raeburn  4952: sub get_groups_roles {
                   4953:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4954:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4955:                   (ref($rolecodes) eq 'ARRAY') && 
                   4956:                   (ref($groups_roles) eq 'HASH')); 
                   4957:     if (keys(%{$cdom_courseroles}) > 0) {
                   4958:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4959:         if ($cdom ne '' && $cnum ne '') {
                   4960:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4961:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4962:                     my $crsrole = $1;
                   4963:                     my $crssec = $2;
                   4964:                     if ($crsrole =~ /^cr/) {
                   4965:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4966:                             push(@{$rolecodes},'cr');
                   4967:                         }
                   4968:                     } else {
                   4969:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4970:                             push(@{$rolecodes},$crsrole);
                   4971:                         }
                   4972:                     }
                   4973:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4974:                     if ($crssec ne '') {
                   4975:                         $rolekey .= "/$crssec";
                   4976:                     }
                   4977:                     $rolekey .= './';
                   4978:                     $groups_roles->{$rolekey} = $rolecodes;
                   4979:                 }
                   4980:             }
                   4981:         }
                   4982:     }
                   4983:     return;
                   4984: }
                   4985: 
                   4986: sub delete_env_groupprivs {
                   4987:     my ($where,$courseroles,$possroles) = @_;
                   4988:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4989:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4990:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4991:         %{$courseroles->{$udom}} =
                   4992:             &get_my_roles('','','userroles',['active'],
                   4993:                           $possroles,[$udom],1);
                   4994:     }
                   4995:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4996:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4997:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4998:             my $area = '/'.$cdom.'/'.$cnum;
                   4999:             my $privkey = "user.priv.$crsrole.$area";
                   5000:             if ($crssec ne '') {
                   5001:                 $privkey .= '/'.$crssec;
                   5002:             }
                   5003:             $privkey .= ".$area/$group";
                   5004:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5005:         }
                   5006:     }
                   5007:     return;
                   5008: }
                   5009: 
1.994     raeburn  5010: sub check_adhoc_privs {
1.1104    raeburn  5011:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5012:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   5013:     if ($env{$cckey}) {
                   5014:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5015:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5016:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5017:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5018:         }
                   5019:     } else {
1.1088    raeburn  5020:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5021:     }
                   5022: }
                   5023: 
                   5024: sub set_adhoc_privileges {
                   5025: # role can be cc or ca
1.1088    raeburn  5026:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5027:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5028:     my $spec = $role.'.'.$area;
                   5029:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5030:                                   $env{'user.name'});
                   5031:     my %ccrole = ();
                   5032:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5033:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5034:     &appenv(\%userroles,[$role,'cm']);
                   5035:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5036:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5037:         &appenv( {'request.role'        => $spec,
                   5038:                   'request.role.domain' => $dcdom,
                   5039:                   'request.course.sec'  => ''
                   5040:                  }
                   5041:                );
                   5042:         my $tadv=0;
                   5043:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5044:         &appenv({'request.role.adv'    => $tadv});
                   5045:     }
1.994     raeburn  5046: }
                   5047: 
1.12      www      5048: # --------------------------------------------------------------- get interface
                   5049: 
                   5050: sub get {
1.131     albertel 5051:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5052:    my $items='';
1.800     albertel 5053:    foreach my $item (@$storearr) {
                   5054:        $items.=&escape($item).'&';
1.191     harris41 5055:    }
1.12      www      5056:    $items=~s/\&$//;
1.620     albertel 5057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5058:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5059:    my $uhome=&homeserver($uname,$udomain);
                   5060: 
1.133     albertel 5061:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5062:    my @pairs=split(/\&/,$rep);
1.273     albertel 5063:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5064:      return @pairs;
                   5065:    }
1.15      www      5066:    my %returnhash=();
1.42      www      5067:    my $i=0;
1.800     albertel 5068:    foreach my $item (@$storearr) {
                   5069:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5070:       $i++;
1.191     harris41 5071:    }
1.15      www      5072:    return %returnhash;
1.27      www      5073: }
                   5074: 
                   5075: # --------------------------------------------------------------- del interface
                   5076: 
                   5077: sub del {
1.133     albertel 5078:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5079:    my $items='';
1.800     albertel 5080:    foreach my $item (@$storearr) {
                   5081:        $items.=&escape($item).'&';
1.191     harris41 5082:    }
1.984     neumanie 5083: 
1.27      www      5084:    $items=~s/\&$//;
1.620     albertel 5085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5086:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5087:    my $uhome=&homeserver($uname,$udomain);
                   5088:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5089: }
                   5090: 
                   5091: # -------------------------------------------------------------- dump interface
                   5092: 
1.1180    droeschl 5093: sub unserialize {
                   5094:     my ($rep, $escapedkeys) = @_;
                   5095: 
                   5096:     return {} if $rep =~ /^error/;
                   5097: 
                   5098:     my %returnhash=();
                   5099: 	foreach my $item (split /\&/, $rep) {
                   5100: 	    my ($key, $value) = split(/=/, $item, 2);
                   5101: 	    $key = unescape($key) unless $escapedkeys;
                   5102: 	    next if $key =~ /^error: 2 /;
                   5103: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5104: 	}
                   5105:     #return %returnhash;
                   5106:     return \%returnhash;
                   5107: }        
                   5108: 
                   5109: # see Lond::dump_with_regexp
                   5110: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5111: sub dump {
1.1180    droeschl 5112:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5113:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5114:     if (!$uname) { $uname=$env{'user.name'}; }
                   5115:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5116: 
1.1180    droeschl 5117:     my $reply;
                   5118:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5119:         # user is hosted on this machine
                   5120:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5121:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5122:         return %{unserialize($reply, $escapedkeys)};
                   5123:     }
1.755     albertel 5124:     if ($regexp) {
                   5125: 	$regexp=&escape($regexp);
                   5126:     } else {
                   5127: 	$regexp='.';
                   5128:     }
1.1166    raeburn  5129:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5130:     my @pairs=split(/\&/,$rep);
                   5131:     my %returnhash=();
1.1098    foxr     5132:     if (!($rep =~ /^error/ )) {
                   5133: 	foreach my $item (@pairs) {
                   5134: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5135:         $key = unescape($key) unless $escapedkeys;
                   5136:         #$key = &unescape($key);
1.1098    foxr     5137: 	    next if ($key =~ /^error: 2 /);
                   5138: 	    $returnhash{$key}=&thaw_unescape($value);
                   5139: 	}
1.755     albertel 5140:     }
                   5141:     return %returnhash;
1.407     www      5142: }
                   5143: 
1.1098    foxr     5144: 
1.717     albertel 5145: # --------------------------------------------------------- dumpstore interface
                   5146: 
                   5147: sub dumpstore {
                   5148:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5149:    # same as dump but keys must be escaped. They may contain colon separated
                   5150:    # lists of values that may themself contain colons (e.g. symbs).
                   5151:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5152: }
                   5153: 
1.407     www      5154: # -------------------------------------------------------------- keys interface
                   5155: 
                   5156: sub getkeys {
                   5157:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5158:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5159:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5160:    my $uhome=&homeserver($uname,$udomain);
                   5161:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5162:    my @keyarray=();
1.800     albertel 5163:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5164:       next if ($key =~ /^error: 2 /);
1.800     albertel 5165:       push(@keyarray,&unescape($key));
1.407     www      5166:    }
                   5167:    return @keyarray;
1.318     matthew  5168: }
                   5169: 
1.319     matthew  5170: # --------------------------------------------------------------- currentdump
                   5171: sub currentdump {
1.328     matthew  5172:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5173:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5174:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5175:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5176:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5177:    my $rep;
                   5178: 
                   5179:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5180:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5181:                    $courseid)));
                   5182:    } else {
                   5183:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5184:    }
                   5185: 
1.318     matthew  5186:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5187:    #
1.318     matthew  5188:    my %returnhash=();
1.319     matthew  5189:    #
                   5190:    if ($rep eq "unknown_cmd") { 
                   5191:        # an old lond will not know currentdump
                   5192:        # Do a dump and make it look like a currentdump
1.822     albertel 5193:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5194:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5195:        my %hash = @tmp;
                   5196:        @tmp=();
1.424     matthew  5197:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5198:    } else {
                   5199:        my @pairs=split(/\&/,$rep);
1.800     albertel 5200:        foreach my $pair (@pairs) {
                   5201:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5202:            my ($symb,$param) = split(/:/,$key);
                   5203:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5204:                                                         &thaw_unescape($value);
1.319     matthew  5205:        }
1.191     harris41 5206:    }
1.12      www      5207:    return %returnhash;
1.424     matthew  5208: }
                   5209: 
                   5210: sub convert_dump_to_currentdump{
                   5211:     my %hash = %{shift()};
                   5212:     my %returnhash;
                   5213:     # Code ripped from lond, essentially.  The only difference
                   5214:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5215:     # we might run in to problems with parameter names =~ /^v\./
                   5216:     while (my ($key,$value) = each(%hash)) {
                   5217:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5218: 	$symb  = &unescape($symb);
                   5219: 	$param = &unescape($param);
1.424     matthew  5220:         next if ($v eq 'version' || $symb eq 'keys');
                   5221:         next if (exists($returnhash{$symb}) &&
                   5222:                  exists($returnhash{$symb}->{$param}) &&
                   5223:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5224:         $returnhash{$symb}->{$param}=$value;
                   5225:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5226:     }
                   5227:     #
                   5228:     # Remove all of the keys in the hashes which keep track of
                   5229:     # the version of the parameter.
                   5230:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5231:         # use a foreach because we are going to delete from the hash.
                   5232:         foreach my $key (keys(%$param_hash)) {
                   5233:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5234:         }
                   5235:     }
                   5236:     return \%returnhash;
1.12      www      5237: }
                   5238: 
1.627     albertel 5239: # ------------------------------------------------------ critical inc interface
                   5240: 
                   5241: sub cinc {
                   5242:     return &inc(@_,'critical');
                   5243: }
                   5244: 
1.449     matthew  5245: # --------------------------------------------------------------- inc interface
                   5246: 
                   5247: sub inc {
1.627     albertel 5248:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5249:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5250:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5251:     my $uhome=&homeserver($uname,$udomain);
                   5252:     my $items='';
                   5253:     if (! ref($store)) {
                   5254:         # got a single value, so use that instead
                   5255:         $items = &escape($store).'=&';
                   5256:     } elsif (ref($store) eq 'SCALAR') {
                   5257:         $items = &escape($$store).'=&';        
                   5258:     } elsif (ref($store) eq 'ARRAY') {
                   5259:         $items = join('=&',map {&escape($_);} @{$store});
                   5260:     } elsif (ref($store) eq 'HASH') {
                   5261:         while (my($key,$value) = each(%{$store})) {
                   5262:             $items.= &escape($key).'='.&escape($value).'&';
                   5263:         }
                   5264:     }
                   5265:     $items=~s/\&$//;
1.627     albertel 5266:     if ($critical) {
                   5267: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5268:     } else {
                   5269: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5270:     }
1.449     matthew  5271: }
                   5272: 
1.12      www      5273: # --------------------------------------------------------------- put interface
                   5274: 
                   5275: sub put {
1.134     albertel 5276:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5277:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5278:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5279:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5280:    my $items='';
1.800     albertel 5281:    foreach my $item (keys(%$storehash)) {
                   5282:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5283:    }
1.12      www      5284:    $items=~s/\&$//;
1.134     albertel 5285:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5286: }
                   5287: 
1.631     albertel 5288: # ------------------------------------------------------------ newput interface
                   5289: 
                   5290: sub newput {
                   5291:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5292:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5293:    if (!$uname) { $uname=$env{'user.name'}; }
                   5294:    my $uhome=&homeserver($uname,$udomain);
                   5295:    my $items='';
                   5296:    foreach my $key (keys(%$storehash)) {
                   5297:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5298:    }
                   5299:    $items=~s/\&$//;
                   5300:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5301: }
                   5302: 
                   5303: # ---------------------------------------------------------  putstore interface
                   5304: 
1.524     raeburn  5305: sub putstore {
1.715     albertel 5306:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5307:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5308:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5309:    my $uhome=&homeserver($uname,$udomain);
                   5310:    my $items='';
1.715     albertel 5311:    foreach my $key (keys(%$storehash)) {
                   5312:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5313:    }
1.715     albertel 5314:    $items=~s/\&$//;
1.716     albertel 5315:    my $esc_symb=&escape($symb);
                   5316:    my $esc_v=&escape($version);
1.715     albertel 5317:    my $reply =
1.716     albertel 5318:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5319: 	      $uhome);
                   5320:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5321:        # gfall back to way things use to be done
1.715     albertel 5322:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5323: 			    $uname);
1.524     raeburn  5324:    }
1.715     albertel 5325:    return $reply;
                   5326: }
                   5327: 
                   5328: sub old_putstore {
1.716     albertel 5329:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5330:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5331:     if (!$uname) { $uname=$env{'user.name'}; }
                   5332:     my $uhome=&homeserver($uname,$udomain);
                   5333:     my %newstorehash;
1.800     albertel 5334:     foreach my $item (keys(%$storehash)) {
                   5335: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5336: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5337:     }
                   5338:     my $items='';
                   5339:     my %allitems = ();
1.800     albertel 5340:     foreach my $item (keys(%newstorehash)) {
                   5341: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5342: 	    my $key = $1.':keys:'.$2;
                   5343: 	    $allitems{$key} .= $3.':';
                   5344: 	}
1.800     albertel 5345: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5346:     }
1.800     albertel 5347:     foreach my $item (keys(%allitems)) {
                   5348: 	$allitems{$item} =~ s/\:$//;
                   5349: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5350:     }
                   5351:     $items=~s/\&$//;
                   5352:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5353: }
                   5354: 
1.47      www      5355: # ------------------------------------------------------ critical put interface
                   5356: 
                   5357: sub cput {
1.134     albertel 5358:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5359:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5360:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5361:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5362:    my $items='';
1.800     albertel 5363:    foreach my $item (keys(%$storehash)) {
                   5364:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5365:    }
1.47      www      5366:    $items=~s/\&$//;
1.134     albertel 5367:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5368: }
                   5369: 
                   5370: # -------------------------------------------------------------- eget interface
                   5371: 
                   5372: sub eget {
1.133     albertel 5373:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5374:    my $items='';
1.800     albertel 5375:    foreach my $item (@$storearr) {
                   5376:        $items.=&escape($item).'&';
1.191     harris41 5377:    }
1.12      www      5378:    $items=~s/\&$//;
1.620     albertel 5379:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5380:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5381:    my $uhome=&homeserver($uname,$udomain);
                   5382:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5383:    my @pairs=split(/\&/,$rep);
                   5384:    my %returnhash=();
1.42      www      5385:    my $i=0;
1.800     albertel 5386:    foreach my $item (@$storearr) {
                   5387:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5388:       $i++;
1.191     harris41 5389:    }
1.12      www      5390:    return %returnhash;
                   5391: }
                   5392: 
1.667     albertel 5393: # ------------------------------------------------------------ tmpput interface
                   5394: sub tmpput {
1.802     raeburn  5395:     my ($storehash,$server,$context)=@_;
1.667     albertel 5396:     my $items='';
1.800     albertel 5397:     foreach my $item (keys(%$storehash)) {
                   5398: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5399:     }
                   5400:     $items=~s/\&$//;
1.802     raeburn  5401:     if (defined($context)) {
                   5402:         $items .= ':'.&escape($context);
                   5403:     }
1.667     albertel 5404:     return &reply("tmpput:$items",$server);
                   5405: }
                   5406: 
                   5407: # ------------------------------------------------------------ tmpget interface
                   5408: sub tmpget {
1.688     albertel 5409:     my ($token,$server)=@_;
                   5410:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5411:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5412:     my %returnhash;
                   5413:     foreach my $item (split(/\&/,$rep)) {
                   5414: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5415:         next if ($key =~ /^error: 2 /);
1.667     albertel 5416: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5417:     }
                   5418:     return %returnhash;
                   5419: }
                   5420: 
1.1113    raeburn  5421: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5422: sub tmpdel {
                   5423:     my ($token,$server)=@_;
                   5424:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5425:     return &reply("tmpdel:$token",$server);
                   5426: }
                   5427: 
1.765     albertel 5428: # -------------------------------------------------- portfolio access checking
                   5429: 
                   5430: sub portfolio_access {
1.766     albertel 5431:     my ($requrl) = @_;
1.765     albertel 5432:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5433:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5434:     if ($result) {
                   5435:         my %setters;
                   5436:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5437:             my ($startblock,$endblock) =
                   5438:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5439:             if ($startblock && $endblock) {
                   5440:                 return 'B';
                   5441:             }
                   5442:         } else {
                   5443:             my ($startblock,$endblock) =
                   5444:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5445:             if ($startblock && $endblock) {
                   5446:                 return 'B';
                   5447:             }
                   5448:         }
                   5449:     }
1.765     albertel 5450:     if ($result eq 'ok') {
1.766     albertel 5451:        return 'F';
1.765     albertel 5452:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5453:        return 'A';
1.765     albertel 5454:     }
1.766     albertel 5455:     return '';
1.765     albertel 5456: }
                   5457: 
                   5458: sub get_portfolio_access {
1.767     albertel 5459:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5460: 
                   5461:     if (!ref($access_hash)) {
                   5462: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5463: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5464: 						   $file_name);
                   5465: 	$access_hash = $access_controls{$file_name};
                   5466:     }
                   5467: 
1.765     albertel 5468:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5469:     my $now = time;
                   5470:     if (ref($access_hash) eq 'HASH') {
                   5471:         foreach my $key (keys(%{$access_hash})) {
                   5472:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5473:             if ($start > $now) {
                   5474:                 next;
                   5475:             }
                   5476:             if ($end && $end<$now) {
                   5477:                 next;
                   5478:             }
                   5479:             if ($scope eq 'public') {
                   5480:                 $public = $key;
                   5481:                 last;
                   5482:             } elsif ($scope eq 'guest') {
                   5483:                 $guest = $key;
                   5484:             } elsif ($scope eq 'domains') {
                   5485:                 push(@domains,$key);
                   5486:             } elsif ($scope eq 'users') {
                   5487:                 push(@users,$key);
                   5488:             } elsif ($scope eq 'course') {
                   5489:                 push(@courses,$key);
                   5490:             } elsif ($scope eq 'group') {
                   5491:                 push(@groups,$key);
                   5492:             }
                   5493:         }
                   5494:         if ($public) {
                   5495:             return 'ok';
                   5496:         }
                   5497:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5498:             if ($guest) {
                   5499:                 return $guest;
                   5500:             }
                   5501:         } else {
                   5502:             if (@domains > 0) {
                   5503:                 foreach my $domkey (@domains) {
                   5504:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5505:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5506:                             return 'ok';
                   5507:                         }
                   5508:                     }
                   5509:                 }
                   5510:             }
                   5511:             if (@users > 0) {
                   5512:                 foreach my $userkey (@users) {
1.865     raeburn  5513:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5514:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5515:                             if (ref($item) eq 'HASH') {
                   5516:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5517:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5518:                                     return 'ok';
                   5519:                                 }
                   5520:                             }
                   5521:                         }
                   5522:                     } 
1.765     albertel 5523:                 }
                   5524:             }
                   5525:             my %roleshash;
                   5526:             my @courses_and_groups = @courses;
                   5527:             push(@courses_and_groups,@groups); 
                   5528:             if (@courses_and_groups > 0) {
                   5529:                 my (%allgroups,%allroles); 
                   5530:                 my ($start,$end,$role,$sec,$group);
                   5531:                 foreach my $envkey (%env) {
1.1060    raeburn  5532:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5533:                         my $cid = $2.'_'.$3; 
                   5534:                         if ($1 eq 'gr') {
                   5535:                             $group = $4;
                   5536:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5537:                         } else {
                   5538:                             if ($4 eq '') {
                   5539:                                 $sec = 'none';
                   5540:                             } else {
                   5541:                                 $sec = $4;
                   5542:                             }
                   5543:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5544:                         }
1.811     albertel 5545:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5546:                         my $cid = $2.'_'.$3;
                   5547:                         if ($4 eq '') {
                   5548:                             $sec = 'none';
                   5549:                         } else {
                   5550:                             $sec = $4;
                   5551:                         }
                   5552:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5553:                     }
                   5554:                 }
                   5555:                 if (keys(%allroles) == 0) {
                   5556:                     return;
                   5557:                 }
                   5558:                 foreach my $key (@courses_and_groups) {
                   5559:                     my %content = %{$$access_hash{$key}};
                   5560:                     my $cnum = $content{'number'};
                   5561:                     my $cdom = $content{'domain'};
                   5562:                     my $cid = $cdom.'_'.$cnum;
                   5563:                     if (!exists($allroles{$cid})) {
                   5564:                         next;
                   5565:                     }    
                   5566:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5567:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5568:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5569:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5570:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5571:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5572:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5573:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5574:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5575:                                         if (grep/^all$/,@sections) {
                   5576:                                             return 'ok';
                   5577:                                         } else {
                   5578:                                             if (grep/^$sec$/,@sections) {
                   5579:                                                 return 'ok';
                   5580:                                             }
                   5581:                                         }
                   5582:                                     }
                   5583:                                 }
                   5584:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5585:                                     if (grep/^none$/,@groups) {
                   5586:                                         return 'ok';
                   5587:                                     }
                   5588:                                 } else {
                   5589:                                     if (grep/^all$/,@groups) {
                   5590:                                         return 'ok';
                   5591:                                     } 
                   5592:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5593:                                         if (grep/^$group$/,@groups) {
                   5594:                                             return 'ok';
                   5595:                                         }
                   5596:                                     }
                   5597:                                 } 
                   5598:                             }
                   5599:                         }
                   5600:                     }
                   5601:                 }
                   5602:             }
                   5603:             if ($guest) {
                   5604:                 return $guest;
                   5605:             }
                   5606:         }
                   5607:     }
                   5608:     return;
                   5609: }
                   5610: 
                   5611: sub course_group_datechecker {
                   5612:     my ($dates,$now,$status) = @_;
                   5613:     my ($start,$end) = split(/\./,$dates);
                   5614:     if (!$start && !$end) {
                   5615:         return 'ok';
                   5616:     }
                   5617:     if (grep/^active$/,@{$status}) {
                   5618:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5619:             return 'ok';
                   5620:         }
                   5621:     }
                   5622:     if (grep/^previous$/,@{$status}) {
                   5623:         if ($end > $now ) {
                   5624:             return 'ok';
                   5625:         }
                   5626:     }
                   5627:     if (grep/^future$/,@{$status}) {
                   5628:         if ($start > $now) {
                   5629:             return 'ok';
                   5630:         }
                   5631:     }
                   5632:     return; 
                   5633: }
                   5634: 
                   5635: sub parse_portfolio_url {
                   5636:     my ($url) = @_;
                   5637: 
                   5638:     my ($type,$udom,$unum,$group,$file_name);
                   5639:     
1.823     albertel 5640:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5641: 	$type = 1;
                   5642:         $udom = $1;
                   5643:         $unum = $2;
                   5644:         $file_name = $3;
1.823     albertel 5645:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5646: 	$type = 2;
                   5647:         $udom = $1;
                   5648:         $unum = $2;
                   5649:         $group = $3;
                   5650:         $file_name = $3.'/'.$4;
                   5651:     }
                   5652:     if (wantarray) {
                   5653: 	return ($type,$udom,$unum,$file_name,$group);
                   5654:     }
                   5655:     return $type;
                   5656: }
                   5657: 
                   5658: sub is_portfolio_url {
                   5659:     my ($url) = @_;
                   5660:     return scalar(&parse_portfolio_url($url));
                   5661: }
                   5662: 
1.798     raeburn  5663: sub is_portfolio_file {
                   5664:     my ($file) = @_;
1.820     raeburn  5665:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5666:         return 1;
                   5667:     }
                   5668:     return;
                   5669: }
                   5670: 
1.976     raeburn  5671: sub usertools_access {
1.1084    raeburn  5672:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5673:     my ($access,%tools);
                   5674:     if ($context eq '') {
                   5675:         $context = 'tools';
                   5676:     }
                   5677:     if ($context eq 'requestcourses') {
                   5678:         %tools = (
                   5679:                       official   => 1,
                   5680:                       unofficial => 1,
1.1006    raeburn  5681:                       community  => 1,
1.985     raeburn  5682:                  );
                   5683:     } else {
                   5684:         %tools = (
                   5685:                       aboutme   => 1,
                   5686:                       blog      => 1,
1.1177    raeburn  5687:                       webdav    => 1,
1.985     raeburn  5688:                       portfolio => 1,
                   5689:                  );
                   5690:     }
1.976     raeburn  5691:     return if (!defined($tools{$tool}));
                   5692: 
                   5693:     if ((!defined($udom)) || (!defined($uname))) {
                   5694:         $udom = $env{'user.domain'};
                   5695:         $uname = $env{'user.name'};
                   5696:     }
                   5697: 
1.978     raeburn  5698:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5699:         if ($action ne 'reload') {
1.985     raeburn  5700:             if ($context eq 'requestcourses') {
                   5701:                 return $env{'environment.canrequest.'.$tool};
                   5702:             } else {
                   5703:                 return $env{'environment.availabletools.'.$tool};
                   5704:             }
                   5705:         }
1.976     raeburn  5706:     }
                   5707: 
                   5708:     my ($toolstatus,$inststatus);
                   5709: 
1.985     raeburn  5710:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5711:          ($action ne 'reload')) {
                   5712:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5713:         $inststatus = $env{'environment.inststatus'};
                   5714:     } else {
1.1084    raeburn  5715:         if (ref($userenvref) eq 'HASH') {
                   5716:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5717:             $inststatus = $userenvref->{'inststatus'};
                   5718:         } else {
                   5719:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5720:             $toolstatus = $userenv{$context.'.'.$tool};
                   5721:             $inststatus = $userenv{'inststatus'};
                   5722:         }
1.976     raeburn  5723:     }
                   5724: 
                   5725:     if ($toolstatus ne '') {
                   5726:         if ($toolstatus) {
                   5727:             $access = 1;
                   5728:         } else {
                   5729:             $access = 0;
                   5730:         }
                   5731:         return $access;
                   5732:     }
                   5733: 
1.1084    raeburn  5734:     my ($is_adv,%domdef);
                   5735:     if (ref($is_advref) eq 'HASH') {
                   5736:         $is_adv = $is_advref->{'is_adv'};
                   5737:     } else {
                   5738:         $is_adv = &is_advanced_user($udom,$uname);
                   5739:     }
                   5740:     if (ref($domdefref) eq 'HASH') {
                   5741:         %domdef = %{$domdefref};
                   5742:     } else {
                   5743:         %domdef = &get_domain_defaults($udom);
                   5744:     }
1.976     raeburn  5745:     if (ref($domdef{$tool}) eq 'HASH') {
                   5746:         if ($is_adv) {
                   5747:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5748:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5749:                     $access = 1;
                   5750:                 } else {
                   5751:                     $access = 0;
                   5752:                 }
                   5753:                 return $access;
                   5754:             }
                   5755:         }
                   5756:         if ($inststatus ne '') {
                   5757:             my ($hasaccess,$hasnoaccess);
                   5758:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5759:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5760:                     if ($domdef{$tool}{$affiliation}) {
                   5761:                         $hasaccess = 1;
                   5762:                     } else {
                   5763:                         $hasnoaccess = 1;
                   5764:                     }
                   5765:                 }
                   5766:             }
                   5767:             if ($hasaccess || $hasnoaccess) {
                   5768:                 if ($hasaccess) {
                   5769:                     $access = 1;
                   5770:                 } elsif ($hasnoaccess) {
                   5771:                     $access = 0; 
                   5772:                 }
                   5773:                 return $access;
                   5774:             }
                   5775:         } else {
                   5776:             if ($domdef{$tool}{'default'} ne '') {
                   5777:                 if ($domdef{$tool}{'default'}) {
                   5778:                     $access = 1;
                   5779:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5780:                     $access = 0;
                   5781:                 }
                   5782:                 return $access;
                   5783:             }
                   5784:         }
                   5785:     } else {
1.1177    raeburn  5786:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  5787:             $access = 1;
                   5788:         } else {
                   5789:             $access = 0;
                   5790:         }
1.976     raeburn  5791:         return $access;
                   5792:     }
                   5793: }
                   5794: 
1.1050    raeburn  5795: sub is_course_owner {
                   5796:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5797:     if (($udom eq '') || ($uname eq '')) {
                   5798:         $udom = $env{'user.domain'};
                   5799:         $uname = $env{'user.name'};
                   5800:     }
                   5801:     unless (($udom eq '') || ($uname eq '')) {
                   5802:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5803:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5804:                 return 1;
                   5805:             } else {
                   5806:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5807:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5808:                     return 1;
                   5809:                 }
                   5810:             }
                   5811:         }
                   5812:     }
                   5813:     return;
                   5814: }
                   5815: 
1.976     raeburn  5816: sub is_advanced_user {
                   5817:     my ($udom,$uname) = @_;
1.1085    raeburn  5818:     if ($udom ne '' && $uname ne '') {
                   5819:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5820:             if (wantarray) {
                   5821:                 return ($env{'user.adv'},$env{'user.author'});
                   5822:             } else {
                   5823:                 return $env{'user.adv'};
                   5824:             }
1.1085    raeburn  5825:         }
                   5826:     }
1.976     raeburn  5827:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5828:     my %allroles;
1.1128    raeburn  5829:     my ($is_adv,$is_author);
1.976     raeburn  5830:     foreach my $role (keys(%roleshash)) {
                   5831:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5832:         my $area = '/'.$tdomain.'/'.$trest;
                   5833:         if ($sec ne '') {
                   5834:             $area .= '/'.$sec;
                   5835:         }
                   5836:         if (($area ne '') && ($trole ne '')) {
                   5837:             my $spec=$trole.'.'.$area;
                   5838:             if ($trole =~ /^cr\//) {
                   5839:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5840:             } elsif ($trole ne 'gr') {
                   5841:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5842:             }
1.1128    raeburn  5843:             if ($trole eq 'au') {
                   5844:                 $is_author = 1;
                   5845:             }
1.976     raeburn  5846:         }
                   5847:     }
                   5848:     foreach my $role (keys(%allroles)) {
                   5849:         last if ($is_adv);
                   5850:         foreach my $item (split(/:/,$allroles{$role})) {
                   5851:             if ($item ne '') {
                   5852:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5853:                 if ($privilege eq 'adv') {
                   5854:                     $is_adv = 1;
                   5855:                     last;
                   5856:                 }
                   5857:             }
                   5858:         }
                   5859:     }
1.1128    raeburn  5860:     if (wantarray) {
                   5861:         return ($is_adv,$is_author);
                   5862:     }
1.976     raeburn  5863:     return $is_adv;
                   5864: }
1.798     raeburn  5865: 
1.1035    raeburn  5866: sub check_can_request {
1.1036    raeburn  5867:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5868:     my $canreq = 0;
                   5869:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5870:     my @options = ('approval','validate','autolimit');
                   5871:     my $optregex = join('|',@options);
                   5872:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5873:         foreach my $type (@{$types}) {
                   5874:             if (&usertools_access($env{'user.name'},
                   5875:                                   $env{'user.domain'},
                   5876:                                   $type,undef,'requestcourses')) {
                   5877:                 $canreq ++;
1.1036    raeburn  5878:                 if (ref($request_domains) eq 'HASH') {
                   5879:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5880:                 }
1.1035    raeburn  5881:                 if ($dom eq $env{'user.domain'}) {
                   5882:                     $can_request->{$type} = 1;
                   5883:                 }
                   5884:             }
                   5885:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5886:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5887:                 if (@curr > 0) {
1.1036    raeburn  5888:                     foreach my $item (@curr) {
                   5889:                         if (ref($request_domains) eq 'HASH') {
                   5890:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5891:                             if ($otherdom ne '') {
                   5892:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5893:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5894:                                         push(@{$request_domains->{$type}},$otherdom);
                   5895:                                     }
                   5896:                                 } else {
                   5897:                                     push(@{$request_domains->{$type}},$otherdom);
                   5898:                                 }
                   5899:                             }
                   5900:                         }
                   5901:                     }
                   5902:                     unless($dom eq $env{'user.domain'}) {
                   5903:                         $canreq ++;
1.1035    raeburn  5904:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5905:                             $can_request->{$type} = 1;
                   5906:                         }
                   5907:                     }
                   5908:                 }
                   5909:             }
                   5910:         }
                   5911:     }
                   5912:     return $canreq;
                   5913: }
                   5914: 
1.341     www      5915: # ---------------------------------------------- Custom access rule evaluation
                   5916: 
                   5917: sub customaccess {
                   5918:     my ($priv,$uri)=@_;
1.807     albertel 5919:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5920:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5921:     $udom = &LONCAPA::clean_domain($udom);
                   5922:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5923:     my $access=0;
1.800     albertel 5924:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5925: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5926: 	if ($type eq 'user') {
                   5927: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5928: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5929: 		if ($tdom) {
                   5930: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5931: 		}
1.896     albertel 5932: 		if ($tuname) {
                   5933: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5934: 		}
                   5935: 		$access=($effect eq 'allow');
                   5936: 		last;
                   5937: 	    }
                   5938: 	} else {
                   5939: 	    if ($role) {
                   5940: 		if ($role ne $urole) { next; }
                   5941: 	    }
                   5942: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5943: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5944: 		if ($tdom) {
                   5945: 		    if ($tdom ne $udom) { next; }
                   5946: 		}
                   5947: 		if ($tcrs) {
                   5948: 		    if ($tcrs ne $ucrs) { next; }
                   5949: 		}
                   5950: 		if ($tsec) {
                   5951: 		    if ($tsec ne $usec) { next; }
                   5952: 		}
                   5953: 		$access=($effect eq 'allow');
                   5954: 		last;
                   5955: 	    }
                   5956: 	    if ($realm eq '' && $role eq '') {
                   5957: 		$access=($effect eq 'allow');
                   5958: 	    }
1.402     bowersj2 5959: 	}
1.341     www      5960:     }
                   5961:     return $access;
                   5962: }
                   5963: 
1.103     harris41 5964: # ------------------------------------------------- Check for a user privilege
1.12      www      5965: 
                   5966: sub allowed {
1.810     raeburn  5967:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5968:     my $ver_orguri=$uri;
1.439     www      5969:     $uri=&deversion($uri);
1.152     www      5970:     my $orguri=$uri;
1.52      www      5971:     $uri=&declutter($uri);
1.809     raeburn  5972: 
1.810     raeburn  5973:     if ($priv eq 'evb') {
                   5974: # Evade communication block restrictions for specified role in a course
                   5975:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5976:             return $1;
                   5977:         } else {
                   5978:             return;
                   5979:         }
                   5980:     }
                   5981: 
1.620     albertel 5982:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5983: # Free bre access to adm and meta resources
1.775     albertel 5984:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5985: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5986: 	&& ($priv eq 'bre')) {
1.14      www      5987: 	return 'F';
1.159     www      5988:     }
                   5989: 
1.545     banghart 5990: # Free bre access to user's own portfolio contents
1.714     raeburn  5991:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5992:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5993: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5994:         my %setters;
                   5995:         my ($startblock,$endblock) = 
                   5996:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5997:         if ($startblock && $endblock) {
                   5998:             return 'B';
                   5999:         } else {
                   6000:             return 'F';
                   6001:         }
1.545     banghart 6002:     }
                   6003: 
1.762     raeburn  6004: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6005:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6006:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6007:         if (exists($env{'request.course.id'})) {
                   6008:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6009:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6010:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6011:                 my $courseprivid=$env{'request.course.id'};
                   6012:                 $courseprivid=~s/\_/\//;
                   6013:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6014:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6015:                     return $1; 
1.762     raeburn  6016:                 } else {
                   6017:                     if ($env{'request.course.sec'}) {
                   6018:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6019:                     }
                   6020:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6021:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6022:                         return $2;
                   6023:                     }
1.714     raeburn  6024:                 }
                   6025:             }
                   6026:         }
                   6027:     }
                   6028: 
1.159     www      6029: # Free bre to public access
                   6030: 
                   6031:     if ($priv eq 'bre') {
1.238     www      6032:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6033: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6034:            return 'F'; 
                   6035:         }
1.238     www      6036:         if ($copyright eq 'priv') {
                   6037:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6038: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6039: 		return '';
                   6040:             }
                   6041:         }
                   6042:         if ($copyright eq 'domain') {
                   6043:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6044: 	    unless (($env{'user.domain'} eq $1) ||
                   6045:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6046: 		return '';
                   6047:             }
1.262     matthew  6048:         }
1.620     albertel 6049:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6050:             # Library role, so allow browsing of resources in this domain.
                   6051:             return 'F';
1.238     www      6052:         }
1.341     www      6053:         if ($copyright eq 'custom') {
                   6054: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6055:         }
1.14      www      6056:     }
1.264     matthew  6057:     # Domain coordinator is trying to create a course
1.620     albertel 6058:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6059:         # uri is the requested domain in this case.
                   6060:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6061:         # a role of dc for the domain in question.
1.620     albertel 6062:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6063:     }
1.29      www      6064: 
1.52      www      6065:     my $thisallowed='';
                   6066:     my $statecond=0;
                   6067:     my $courseprivid='';
                   6068: 
1.1039    raeburn  6069:     my $ownaccess;
1.1043    raeburn  6070:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6071:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6072:         if ($uri eq '') {
                   6073:             $ownaccess = 1;
                   6074:         } else {
                   6075:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6076:                 my $udom = $env{'user.domain'};
                   6077:                 my $uname = $env{'user.name'};
                   6078:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6079:                     $ownaccess = 1;
1.1040    raeburn  6080:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6081:                     unless ($uri =~ m{\.\./}) {
                   6082:                         $ownaccess = 1;
                   6083:                     }
                   6084:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6085:                     my $now = time;
                   6086:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6087:                         my $adom = $1;
                   6088:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6089:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6090:                                 my ($start,$end) = split('.',$env{$key});
                   6091:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6092:                                     $ownaccess = 1;
                   6093:                                     last;
                   6094:                                 }
                   6095:                             }
                   6096:                         }
                   6097:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6098:                         my $adom = $1;
                   6099:                         my $aname = $2;
1.1042    raeburn  6100:                         foreach my $role ('ca','aa') { 
                   6101:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6102:                                 my ($start,$end) =
                   6103:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6104:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6105:                                     $ownaccess = 1;
                   6106:                                     last;
                   6107:                                 }
1.1039    raeburn  6108:                             }
                   6109:                         }
                   6110:                     }
                   6111:                 }
                   6112:             }
                   6113:         }
                   6114:     }
                   6115: 
1.52      www      6116: # Course
                   6117: 
1.620     albertel 6118:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6119:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6120:             $thisallowed.=$1;
                   6121:         }
1.52      www      6122:     }
1.29      www      6123: 
1.52      www      6124: # Domain
                   6125: 
1.620     albertel 6126:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6127:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6128:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6129:             $thisallowed.=$1;
                   6130:         }
1.12      www      6131:     }
1.52      www      6132: 
1.1141    raeburn  6133: # User who is not author or co-author might still be able to edit
                   6134: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6135:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6136:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6137:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6138:             $thisallowed.=$1;
                   6139:         }
                   6140:     }
                   6141: 
1.52      www      6142: # Course: uri itself is a course
1.66      www      6143:     my $courseuri=$uri;
                   6144:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6145:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6146: 
1.620     albertel 6147:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6148:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6149:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6150:             $thisallowed.=$1;
                   6151:         }
1.12      www      6152:     }
1.29      www      6153: 
1.665     albertel 6154: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6155: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6156:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6157: 	$thisallowed='';
1.671     raeburn  6158:         my ($match)=&is_on_map($uri);
                   6159:         if ($match) {
                   6160:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6161:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6162:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6163:                 if (@blockers > 0) {
                   6164:                     $thisallowed = 'B';
                   6165:                 } else {
                   6166:                     $thisallowed.=$1;
                   6167:                 }
1.671     raeburn  6168:             }
                   6169:         } else {
1.705     albertel 6170:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6171:             if ($refuri) {
                   6172:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6173:                     $thisallowed='F';
1.671     raeburn  6174:                 } else {
                   6175:                     $refuri=&declutter($refuri);
                   6176:                     my ($match) = &is_on_map($refuri);
                   6177:                     if ($match) {
1.1162    raeburn  6178:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6179:                         if (@blockers > 0) {
                   6180:                             $thisallowed = 'B';
                   6181:                         } else {
                   6182:                             $thisallowed='F';
                   6183:                         }
1.671     raeburn  6184:                     }
1.669     raeburn  6185:                 }
1.671     raeburn  6186:             }
                   6187:         }
1.314     www      6188:     }
1.492     albertel 6189: 
1.766     albertel 6190:     if ($priv eq 'bre'
                   6191: 	&& $thisallowed ne 'F' 
                   6192: 	&& $thisallowed ne '2'
                   6193: 	&& &is_portfolio_url($uri)) {
                   6194: 	$thisallowed = &portfolio_access($uri);
                   6195:     }
                   6196:     
1.52      www      6197: # Full access at system, domain or course-wide level? Exit.
1.29      www      6198:     if ($thisallowed=~/F/) {
                   6199: 	return 'F';
                   6200:     }
                   6201: 
1.52      www      6202: # If this is generating or modifying users, exit with special codes
1.29      www      6203: 
1.643     www      6204:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6205: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6206: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6207: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6208: 	    unless ($auname) { return $thisallowed; }
                   6209: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6210: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6211: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6212: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6213: 	}
1.52      www      6214: 	return $thisallowed;
                   6215:     }
                   6216: #
1.103     harris41 6217: # Gathered so far: system, domain and course wide privileges
1.52      www      6218: #
                   6219: # Course: See if uri or referer is an individual resource that is part of 
                   6220: # the course
                   6221: 
1.620     albertel 6222:     if ($env{'request.course.id'}) {
1.232     www      6223: 
1.620     albertel 6224:        $courseprivid=$env{'request.course.id'};
                   6225:        if ($env{'request.course.sec'}) {
                   6226:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6227:        }
                   6228:        $courseprivid=~s/\_/\//;
                   6229:        my $checkreferer=1;
1.232     www      6230:        my ($match,$cond)=&is_on_map($uri);
                   6231:        if ($match) {
                   6232:            $statecond=$cond;
1.620     albertel 6233:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6234:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6235:                my $value = $1;
                   6236:                if ($priv eq 'bre') {
                   6237:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6238:                    if (@blockers > 0) {
                   6239:                        $thisallowed = 'B';
                   6240:                    } else {
                   6241:                        $thisallowed.=$value;
                   6242:                    }
                   6243:                } else {
                   6244:                    $thisallowed.=$value;
                   6245:                }
1.52      www      6246:                $checkreferer=0;
                   6247:            }
1.29      www      6248:        }
1.83      www      6249:        
1.148     www      6250:        if ($checkreferer) {
1.620     albertel 6251: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6252:             unless ($refuri) {
1.800     albertel 6253:                 foreach my $key (keys(%env)) {
                   6254: 		    if ($key=~/^httpref\..*\*/) {
                   6255: 			my $pattern=$key;
1.156     www      6256:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6257:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6258:                         $pattern=~s/\//\\\//g;
1.152     www      6259:                         if ($orguri=~/$pattern/) {
1.800     albertel 6260: 			    $refuri=$env{$key};
1.148     www      6261:                         }
                   6262:                     }
1.191     harris41 6263:                 }
1.148     www      6264:             }
1.232     www      6265: 
1.148     www      6266:          if ($refuri) { 
1.152     www      6267: 	  $refuri=&declutter($refuri);
1.232     www      6268:           my ($match,$cond)=&is_on_map($refuri);
                   6269:             if ($match) {
                   6270:               my $refstatecond=$cond;
1.620     albertel 6271:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6272:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6273:                   my $value = $1;
                   6274:                   if ($priv eq 'bre') {
                   6275:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6276:                       if (@blockers > 0) {
                   6277:                           $thisallowed = 'B';
                   6278:                       } else {
                   6279:                           $thisallowed.=$value;
                   6280:                       }
                   6281:                   } else {
                   6282:                       $thisallowed.=$value;
                   6283:                   }
1.53      www      6284:                   $uri=$refuri;
                   6285:                   $statecond=$refstatecond;
1.52      www      6286:               }
                   6287:           }
1.148     www      6288:         }
1.29      www      6289:        }
1.52      www      6290:    }
1.29      www      6291: 
1.52      www      6292: #
1.103     harris41 6293: # Gathered now: all privileges that could apply, and condition number
1.52      www      6294: # 
                   6295: #
                   6296: # Full or no access?
                   6297: #
1.29      www      6298: 
1.52      www      6299:     if ($thisallowed=~/F/) {
                   6300: 	return 'F';
                   6301:     }
1.29      www      6302: 
1.52      www      6303:     unless ($thisallowed) {
                   6304:         return '';
                   6305:     }
1.29      www      6306: 
1.52      www      6307: # Restrictions exist, deal with them
                   6308: #
                   6309: #   C:according to course preferences
                   6310: #   R:according to resource settings
                   6311: #   L:unless locked
                   6312: #   X:according to user session state
                   6313: #
                   6314: 
                   6315: # Possibly locked functionality, check all courses
1.54      www      6316: # Locks might take effect only after 10 minutes cache expiration for other
                   6317: # courses, and 2 minutes for current course
1.52      www      6318: 
                   6319:     my $envkey;
                   6320:     if ($thisallowed=~/L/) {
1.1000    raeburn  6321:         foreach $envkey (keys(%env)) {
1.54      www      6322:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6323:                my $courseid=$2;
                   6324:                my $roleid=$1.'.'.$2;
1.92      www      6325:                $courseid=~s/^\///;
1.54      www      6326:                my $expiretime=600;
1.620     albertel 6327:                if ($env{'request.role'} eq $roleid) {
1.54      www      6328: 		  $expiretime=120;
                   6329:                }
                   6330: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6331:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6332:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6333: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6334:                }
1.620     albertel 6335:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6336:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6337: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6338:                        &log($env{'user.domain'},$env{'user.name'},
                   6339:                             $env{'user.home'},
1.57      www      6340:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6341:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6342:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6343: 		       return '';
                   6344:                    }
                   6345:                }
1.620     albertel 6346:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6347:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6348: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6349:                        &log($env{'user.domain'},$env{'user.name'},
                   6350:                             $env{'user.home'},
1.57      www      6351:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6352:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6353:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6354: 		       return '';
                   6355:                    }
                   6356:                }
                   6357: 	   }
1.29      www      6358:        }
1.52      www      6359:     }
                   6360:    
                   6361: #
                   6362: # Rest of the restrictions depend on selected course
                   6363: #
                   6364: 
1.620     albertel 6365:     unless ($env{'request.course.id'}) {
1.766     albertel 6366: 	if ($thisallowed eq 'A') {
                   6367: 	    return 'A';
1.814     raeburn  6368:         } elsif ($thisallowed eq 'B') {
                   6369:             return 'B';
1.766     albertel 6370: 	} else {
                   6371: 	    return '1';
                   6372: 	}
1.52      www      6373:     }
1.29      www      6374: 
1.52      www      6375: #
                   6376: # Now user is definitely in a course
                   6377: #
1.53      www      6378: 
                   6379: 
                   6380: # Course preferences
                   6381: 
                   6382:    if ($thisallowed=~/C/) {
1.620     albertel 6383:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6384:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6385:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6386: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6387: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6388: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6389: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6390: 			$env{'request.course.id'});
                   6391: 	   }
1.237     www      6392:            return '';
                   6393:        }
                   6394: 
1.620     albertel 6395:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6396: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6397: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6398: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6399: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6400: 			$env{'request.course.id'});
                   6401: 	   }
1.54      www      6402:            return '';
                   6403:        }
1.53      www      6404:    }
                   6405: 
                   6406: # Resource preferences
                   6407: 
                   6408:    if ($thisallowed=~/R/) {
1.620     albertel 6409:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6410:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6411: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6412: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6413: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6414: 	   }
                   6415: 	   return '';
1.54      www      6416:        }
1.53      www      6417:    }
1.30      www      6418: 
1.246     www      6419: # Restricted by state or randomout?
1.30      www      6420: 
1.52      www      6421:    if ($thisallowed=~/X/) {
1.620     albertel 6422:       if ($env{'acc.randomout'}) {
1.579     albertel 6423: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6424:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6425:             return ''; 
                   6426:          }
1.247     www      6427:       }
                   6428:       if (&condval($statecond)) {
1.52      www      6429: 	 return '2';
                   6430:       } else {
                   6431:          return '';
                   6432:       }
                   6433:    }
1.30      www      6434: 
1.766     albertel 6435:     if ($thisallowed eq 'A') {
                   6436: 	return 'A';
1.814     raeburn  6437:     } elsif ($thisallowed eq 'B') {
                   6438:         return 'B';
1.766     albertel 6439:     }
1.52      www      6440:    return 'F';
1.232     www      6441: }
1.1162    raeburn  6442: 
                   6443: sub get_comm_blocks {
                   6444:     my ($cdom,$cnum) = @_;
                   6445:     if ($cdom eq '' || $cnum eq '') {
                   6446:         return unless ($env{'request.course.id'});
                   6447:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6448:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6449:     }
                   6450:     my %commblocks;
                   6451:     my $hashid=$cdom.'_'.$cnum;
                   6452:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6453:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6454:         %commblocks = %{$blocksref};
                   6455:     } else {
                   6456:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6457:         my $cachetime = 600;
                   6458:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6459:     }
                   6460:     return %commblocks;
                   6461: }
                   6462: 
                   6463: sub has_comm_blocking {
                   6464:     my ($priv,$symb,$uri,$blocks) = @_;
                   6465:     return unless ($env{'request.course.id'});
                   6466:     return unless ($priv eq 'bre');
                   6467:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6468:     my %commblocks;
                   6469:     if (ref($blocks) eq 'HASH') {
                   6470:         %commblocks = %{$blocks};
                   6471:     } else {
                   6472:         %commblocks = &get_comm_blocks();
                   6473:     }
                   6474:     return unless (keys(%commblocks) > 0);
                   6475:     if (!$symb) { $symb=&symbread($uri,1); }
                   6476:     my ($map,$resid,undef)=&decode_symb($symb);
                   6477:     my %tocheck = (
                   6478:                     maps      => $map,
                   6479:                     resources => $symb,
                   6480:                   );
                   6481:     my @blockers;
                   6482:     my $now = time;
1.1163    raeburn  6483:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6484:     foreach my $block (keys(%commblocks)) {
                   6485:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6486:             my ($start,$end) = ($1,$2);
                   6487:             if ($start <= $now && $end >= $now) {
                   6488:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6489:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6490:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6491:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6492:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6493:                                     push(@blockers,$block);
                   6494:                                 }
                   6495:                             }
                   6496:                         }
                   6497:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6498:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6499:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6500:                                     push(@blockers,$block);
                   6501:                                 }
                   6502:                             }
                   6503:                         }
                   6504:                     }
                   6505:                 }
                   6506:             }
                   6507:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6508:             my $item = $1;
1.1163    raeburn  6509:             my @to_test;
1.1162    raeburn  6510:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6511:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6512:                     my $check_interval;
                   6513:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6514:                         my @interval;
                   6515:                         my $type = 'map';
                   6516:                         if ($item eq 'course') {
                   6517:                             $type = 'course';
                   6518:                             @interval=&EXT("resource.0.interval");
                   6519:                         } else {
                   6520:                             if ($item =~ /___\d+___/) {
                   6521:                                 $type = 'resource';
                   6522:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6523:                                 if (ref($navmap)) {                        
                   6524:                                     my $res = $navmap->getBySymb($item); 
                   6525:                                     push(@to_test,$res);
                   6526:                                 }
1.1162    raeburn  6527:                             } else {
                   6528:                                 my $mapsymb = &symbread($item,1);
                   6529:                                 if ($mapsymb) {
                   6530:                                     if (ref($navmap)) {
                   6531:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6532:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6533:                                         foreach my $res (@to_test) {
1.1162    raeburn  6534:                                             my $symb = $res->symb();
                   6535:                                             next if ($symb eq $mapsymb);
                   6536:                                             if ($symb ne '') {
                   6537:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6538:                                                 last;
                   6539:                                             }
                   6540:                                         }
                   6541:                                     }
                   6542:                                 }
                   6543:                             }
                   6544:                         }
                   6545:                         if ($interval[0] =~ /\d+/) {
                   6546:                             my $first_access;
                   6547:                             if ($type eq 'resource') {
                   6548:                                 $first_access=&get_first_access($interval[1],$item);
                   6549:                             } elsif ($type eq 'map') {
                   6550:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6551:                             } else {
                   6552:                                 $first_access=&get_first_access($interval[1]);
                   6553:                             }
                   6554:                             if ($first_access) {
                   6555:                                 my $timesup = $first_access+$interval[0];
                   6556:                                 if ($timesup > $now) {
1.1163    raeburn  6557:                                     foreach my $res (@to_test) {
                   6558:                                         if ($res->is_problem()) {
                   6559:                                             if ($res->completable()) {
                   6560:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6561:                                                     push(@blockers,$block);
                   6562:                                                 }
                   6563:                                                 last;
                   6564:                                             }
                   6565:                                         }
1.1162    raeburn  6566:                                     }
                   6567:                                 }
                   6568:                             }
                   6569:                         }
                   6570:                     }
                   6571:                 }
                   6572:             }
                   6573:         }
                   6574:     }
                   6575:     return @blockers;
                   6576: }
                   6577: 
                   6578: sub check_docs_block {
                   6579:     my ($docsblock,$tocheck) =@_;
                   6580:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6581:         return;
                   6582:     }
                   6583:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6584:         if ($tocheck->{'maps'}) {
                   6585:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6586:                 return 1;
                   6587:             }
                   6588:         }
                   6589:     }
                   6590:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6591:         if ($tocheck->{'resources'}) {
                   6592:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6593:                 return 1;
                   6594:             }
                   6595:         }
                   6596:     }
                   6597:     return;
                   6598: }
                   6599: 
1.1133    foxr     6600: #
                   6601: #   Removes the versino from a URI and
                   6602: #   splits it in to its filename and path to the filename.
                   6603: #   Seems like File::Basename could have done this more clearly.
                   6604: #   Parameters:
                   6605: #      $uri   - input URI
                   6606: #   Returns:
                   6607: #     Two element list consisting of 
                   6608: #     $pathname  - the URI up to and excluding the trailing /
                   6609: #     $filename  - The part of the URI following the last /
                   6610: #  NOTE:
                   6611: #    Another realization of this is simply:
                   6612: #    use File::Basename;
                   6613: #    ...
                   6614: #    $uri = shift;
                   6615: #    $filename = basename($uri);
                   6616: #    $path     = dirname($uri);
                   6617: #    return ($filename, $path);
                   6618: #
                   6619: #     The implementation below is probably faster however.
                   6620: #
1.710     albertel 6621: sub split_uri_for_cond {
                   6622:     my $uri=&deversion(&declutter(shift));
                   6623:     my @uriparts=split(/\//,$uri);
                   6624:     my $filename=pop(@uriparts);
                   6625:     my $pathname=join('/',@uriparts);
                   6626:     return ($pathname,$filename);
                   6627: }
1.232     www      6628: # --------------------------------------------------- Is a resource on the map?
                   6629: 
                   6630: sub is_on_map {
1.710     albertel 6631:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6632:     #Trying to find the conditional for the file
1.620     albertel 6633:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6634: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6635:     if ($match) {
1.289     bowersj2 6636: 	return (1,$1);
                   6637:     } else {
1.434     www      6638: 	return (0,0);
1.289     bowersj2 6639:     }
1.12      www      6640: }
                   6641: 
1.427     www      6642: # --------------------------------------------------------- Get symb from alias
                   6643: 
                   6644: sub get_symb_from_alias {
                   6645:     my $symb=shift;
                   6646:     my ($map,$resid,$url)=&decode_symb($symb);
                   6647: # Already is a symb
                   6648:     if ($url) { return $symb; }
                   6649: # Must be an alias
                   6650:     my $aliassymb='';
                   6651:     my %bighash;
1.620     albertel 6652:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6653:                             &GDBM_READER(),0640)) {
                   6654:         my $rid=$bighash{'mapalias_'.$symb};
                   6655: 	if ($rid) {
                   6656: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6657: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6658: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6659: 	}
                   6660:         untie %bighash;
                   6661:     }
                   6662:     return $aliassymb;
                   6663: }
                   6664: 
1.12      www      6665: # ----------------------------------------------------------------- Define Role
                   6666: 
                   6667: sub definerole {
                   6668:   if (allowed('mcr','/')) {
                   6669:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6670:     foreach my $role (split(':',$sysrole)) {
                   6671: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6672:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6673:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6674: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6675:                return "refused:s:$crole&$cqual"; 
                   6676:             }
                   6677:         }
1.191     harris41 6678:     }
1.800     albertel 6679:     foreach my $role (split(':',$domrole)) {
                   6680: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6681:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6682:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6683: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6684:                return "refused:d:$crole&$cqual"; 
                   6685:             }
                   6686:         }
1.191     harris41 6687:     }
1.800     albertel 6688:     foreach my $role (split(':',$courole)) {
                   6689: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6690:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6691:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6692: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6693:                return "refused:c:$crole&$cqual"; 
                   6694:             }
                   6695:         }
1.191     harris41 6696:     }
1.620     albertel 6697:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6698:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6699: 	        "rolesdef_$rolename=".
                   6700:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6701:     return reply($command,$env{'user.home'});
1.12      www      6702:   } else {
                   6703:     return 'refused';
                   6704:   }
1.105     harris41 6705: }
                   6706: 
                   6707: # ---------------- Make a metadata query against the network of library servers
                   6708: 
                   6709: sub metadata_query {
1.244     matthew  6710:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6711:     my %rhash;
1.845     albertel 6712:     my %libserv = &all_library();
1.244     matthew  6713:     my @server_list = (defined($server_array) ? @$server_array
                   6714:                                               : keys(%libserv) );
                   6715:     for my $server (@server_list) {
1.118     harris41 6716: 	unless ($custom or $customshow) {
                   6717: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6718: 	    $rhash{$server}=$reply;
                   6719: 	}
                   6720: 	else {
                   6721: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6722: 			     &escape($custom).':'.&escape($customshow),
                   6723: 			     $server);
                   6724: 	    $rhash{$server}=$reply;
                   6725: 	}
1.112     harris41 6726:     }
1.118     harris41 6727:     return \%rhash;
1.240     www      6728: }
                   6729: 
                   6730: # ----------------------------------------- Send log queries and wait for reply
                   6731: 
                   6732: sub log_query {
                   6733:     my ($uname,$udom,$query,%filters)=@_;
                   6734:     my $uhome=&homeserver($uname,$udom);
                   6735:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6736:     my $uhost=&hostname($uhome);
1.800     albertel 6737:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6738:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6739:                        $uhome);
1.479     albertel 6740:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6741:     return get_query_reply($queryid);
                   6742: }
                   6743: 
1.818     raeburn  6744: # -------------------------- Update MySQL table for portfolio file
                   6745: 
                   6746: sub update_portfolio_table {
1.821     raeburn  6747:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6748:     if ($group ne '') {
                   6749:         $file_name =~s /^\Q$group\E//;
                   6750:     }
1.818     raeburn  6751:     my $homeserver = &homeserver($uname,$udom);
                   6752:     my $queryid=
1.821     raeburn  6753:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6754:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6755:     my $reply = &get_query_reply($queryid);
                   6756:     return $reply;
                   6757: }
                   6758: 
1.899     raeburn  6759: # -------------------------- Update MySQL allusers table
                   6760: 
                   6761: sub update_allusers_table {
                   6762:     my ($uname,$udom,$names) = @_;
                   6763:     my $homeserver = &homeserver($uname,$udom);
                   6764:     my $queryid=
                   6765:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6766:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6767:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6768:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6769:                'generation='.&escape($names->{'generation'}).'%%'.
                   6770:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6771:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6772:     return;
1.899     raeburn  6773: }
                   6774: 
1.508     raeburn  6775: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6776: 
                   6777: sub fetch_enrollment_query {
1.511     raeburn  6778:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6779:     my $homeserver;
1.547     raeburn  6780:     my $maxtries = 1;
1.508     raeburn  6781:     if ($context eq 'automated') {
                   6782:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6783:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6784:     } else {
                   6785:         $homeserver = &homeserver($cnum,$dom);
                   6786:     }
1.838     albertel 6787:     my $host=&hostname($homeserver);
1.506     raeburn  6788:     my $cmd = '';
1.1000    raeburn  6789:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6790:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6791:     }
                   6792:     $cmd =~ s/%%$//;
                   6793:     $cmd = &escape($cmd);
                   6794:     my $query = 'fetchenrollment';
1.620     albertel 6795:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6796:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6797:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6798:         return 'error: '.$queryid;
                   6799:     }
1.506     raeburn  6800:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6801:     my $tries = 1;
                   6802:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6803:         $reply = &get_query_reply($queryid);
                   6804:         $tries ++;
                   6805:     }
1.526     raeburn  6806:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6807:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6808:     } else {
1.901     albertel 6809:         my @responses = split(/:/,$reply);
1.515     raeburn  6810:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6811:             foreach my $line (@responses) {
                   6812:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6813:                 $$replyref{$key} = $value;
                   6814:             }
                   6815:         } else {
1.1117    foxr     6816:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6817:             foreach my $line (@responses) {
                   6818:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6819:                 $$replyref{$key} = $value;
                   6820:                 if ($value > 0) {
1.800     albertel 6821:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6822:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6823:                         my $destname = $pathname.'/'.$filename;
                   6824:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6825:                         if ($xml_classlist =~ /^error/) {
                   6826:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6827:                         } else {
1.506     raeburn  6828:                             if ( open(FILE,">$destname") ) {
                   6829:                                 print FILE &unescape($xml_classlist);
                   6830:                                 close(FILE);
1.526     raeburn  6831:                             } else {
                   6832:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6833:                             }
                   6834:                         }
                   6835:                     }
                   6836:                 }
                   6837:             }
                   6838:         }
                   6839:         return 'ok';
                   6840:     }
                   6841:     return 'error';
                   6842: }
                   6843: 
1.242     www      6844: sub get_query_reply {
                   6845:     my $queryid=shift;
1.1117    foxr     6846:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6847:     my $reply='';
                   6848:     for (1..100) {
                   6849: 	sleep 2;
                   6850:         if (-e $replyfile.'.end') {
1.448     albertel 6851: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6852: 		$reply = join('',<$fh>);
                   6853: 		close($fh);
1.240     www      6854: 	   } else { return 'error: reply_file_error'; }
1.242     www      6855:            return &unescape($reply);
                   6856: 	}
1.240     www      6857:     }
1.242     www      6858:     return 'timeout:'.$queryid;
1.240     www      6859: }
                   6860: 
                   6861: sub courselog_query {
1.241     www      6862: #
                   6863: # possible filters:
                   6864: # url: url or symb
                   6865: # username
                   6866: # domain
                   6867: # action: view, submit, grade
                   6868: # start: timestamp
                   6869: # end: timestamp
                   6870: #
1.240     www      6871:     my (%filters)=@_;
1.620     albertel 6872:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6873:     if ($filters{'url'}) {
                   6874: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6875:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6876:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6877:     }
1.620     albertel 6878:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6879:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6880:     return &log_query($cname,$cdom,'courselog',%filters);
                   6881: }
                   6882: 
                   6883: sub userlog_query {
1.858     raeburn  6884: #
                   6885: # possible filters:
                   6886: # action: log check role
                   6887: # start: timestamp
                   6888: # end: timestamp
                   6889: #
1.240     www      6890:     my ($uname,$udom,%filters)=@_;
                   6891:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6892: }
                   6893: 
1.506     raeburn  6894: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6895: 
                   6896: sub auto_run {
1.508     raeburn  6897:     my ($cnum,$cdom) = @_;
1.876     raeburn  6898:     my $response = 0;
                   6899:     my $settings;
                   6900:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6901:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6902:         $settings = $domconfig{'autoenroll'};
                   6903:         if ($settings->{'run'} eq '1') {
                   6904:             $response = 1;
                   6905:         }
                   6906:     } else {
1.934     raeburn  6907:         my $homeserver;
                   6908:         if (&is_course($cdom,$cnum)) {
                   6909:             $homeserver = &homeserver($cnum,$cdom);
                   6910:         } else {
                   6911:             $homeserver = &domain($cdom,'primary');
                   6912:         }
                   6913:         if ($homeserver ne 'no_host') {
                   6914:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6915:         }
1.876     raeburn  6916:     }
1.506     raeburn  6917:     return $response;
                   6918: }
1.776     albertel 6919: 
1.506     raeburn  6920: sub auto_get_sections {
1.508     raeburn  6921:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6922:     my $homeserver;
                   6923:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6924:         $homeserver = &homeserver($cnum,$cdom);
                   6925:     }
                   6926:     if (!defined($homeserver)) { 
                   6927:         if ($cdom =~ /^$match_domain$/) {
                   6928:             $homeserver = &domain($cdom,'primary');
                   6929:         }
                   6930:     }
                   6931:     my @secs;
                   6932:     if (defined($homeserver)) {
                   6933:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6934:         unless ($response eq 'refused') {
                   6935:             @secs = split(/:/,$response);
                   6936:         }
1.506     raeburn  6937:     }
                   6938:     return @secs;
                   6939: }
1.776     albertel 6940: 
1.506     raeburn  6941: sub auto_new_course {
1.1099    raeburn  6942:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6943:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6944:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6945:     return $response;
                   6946: }
1.776     albertel 6947: 
1.506     raeburn  6948: sub auto_validate_courseID {
1.508     raeburn  6949:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6950:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6951:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6952:     return $response;
                   6953: }
1.776     albertel 6954: 
1.1007    raeburn  6955: sub auto_validate_instcode {
1.1020    raeburn  6956:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6957:     my ($homeserver,$response);
                   6958:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6959:         $homeserver = &homeserver($cnum,$cdom);
                   6960:     }
                   6961:     if (!defined($homeserver)) {
                   6962:         if ($cdom =~ /^$match_domain$/) {
                   6963:             $homeserver = &domain($cdom,'primary');
                   6964:         }
                   6965:     }
1.1065    raeburn  6966:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6967:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6968:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6969:     return ($outcome,$description);
1.1007    raeburn  6970: }
                   6971: 
1.506     raeburn  6972: sub auto_create_password {
1.873     raeburn  6973:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6974:     my ($homeserver,$response);
1.506     raeburn  6975:     my $create_passwd = 0;
                   6976:     my $authchk = '';
1.873     raeburn  6977:     if ($udom =~ /^$match_domain$/) {
                   6978:         $homeserver = &domain($udom,'primary');
                   6979:     }
                   6980:     if ($homeserver eq '') {
                   6981:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6982:             $homeserver = &homeserver($cnum,$cdom);
                   6983:         }
                   6984:     }
                   6985:     if ($homeserver eq '') {
                   6986:         $authchk = 'nodomain';
1.506     raeburn  6987:     } else {
1.873     raeburn  6988:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6989:         if ($response eq 'refused') {
                   6990:             $authchk = 'refused';
                   6991:         } else {
1.901     albertel 6992:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6993:         }
1.506     raeburn  6994:     }
                   6995:     return ($authparam,$create_passwd,$authchk);
                   6996: }
                   6997: 
1.706     raeburn  6998: sub auto_photo_permission {
                   6999:     my ($cnum,$cdom,$students) = @_;
                   7000:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7001:     my ($outcome,$perm_reqd,$conditions) = 
                   7002: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7003:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7004: 	return (undef,undef);
                   7005:     }
1.706     raeburn  7006:     return ($outcome,$perm_reqd,$conditions);
                   7007: }
                   7008: 
                   7009: sub auto_checkphotos {
                   7010:     my ($uname,$udom,$pid) = @_;
                   7011:     my $homeserver = &homeserver($uname,$udom);
                   7012:     my ($result,$resulttype);
                   7013:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7014: 				   &escape($uname).':'.&escape($pid),
                   7015: 				   $homeserver));
1.709     albertel 7016:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7017: 	return (undef,undef);
                   7018:     }
1.706     raeburn  7019:     if ($outcome) {
                   7020:         ($result,$resulttype) = split(/:/,$outcome);
                   7021:     } 
                   7022:     return ($result,$resulttype);
                   7023: }
                   7024: 
                   7025: sub auto_photochoice {
                   7026:     my ($cnum,$cdom) = @_;
                   7027:     my $homeserver = &homeserver($cnum,$cdom);
                   7028:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7029: 						       &escape($cdom),
                   7030: 						       $homeserver)));
1.709     albertel 7031:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7032: 	return (undef,undef);
                   7033:     }
1.706     raeburn  7034:     return ($update,$comment);
                   7035: }
                   7036: 
                   7037: sub auto_photoupdate {
                   7038:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7039:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7040:     my $host=&hostname($homeserver);
1.706     raeburn  7041:     my $cmd = '';
                   7042:     my $maxtries = 1;
1.800     albertel 7043:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7044:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7045:     }
                   7046:     $cmd =~ s/%%$//;
                   7047:     $cmd = &escape($cmd);
                   7048:     my $query = 'institutionalphotos';
                   7049:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7050:     unless ($queryid=~/^\Q$host\E\_/) {
                   7051:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7052:         return 'error: '.$queryid;
                   7053:     }
                   7054:     my $reply = &get_query_reply($queryid);
                   7055:     my $tries = 1;
                   7056:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7057:         $reply = &get_query_reply($queryid);
                   7058:         $tries ++;
                   7059:     }
                   7060:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7061:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7062:     } else {
                   7063:         my @responses = split(/:/,$reply);
                   7064:         my $outcome = shift(@responses); 
                   7065:         foreach my $item (@responses) {
                   7066:             my ($key,$value) = split(/=/,$item);
                   7067:             $$photo{$key} = $value;
                   7068:         }
                   7069:         return $outcome;
                   7070:     }
                   7071:     return 'error';
                   7072: }
                   7073: 
1.521     raeburn  7074: sub auto_instcode_format {
1.793     albertel 7075:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7076: 	$cat_order) = @_;
1.521     raeburn  7077:     my $courses = '';
1.772     raeburn  7078:     my @homeservers;
1.521     raeburn  7079:     if ($caller eq 'global') {
1.841     albertel 7080: 	my %servers = &get_servers($codedom,'library');
                   7081: 	foreach my $tryserver (keys(%servers)) {
                   7082: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7083: 		push(@homeservers,$tryserver);
                   7084: 	    }
1.584     raeburn  7085:         }
1.1022    raeburn  7086:     } elsif ($caller eq 'requests') {
                   7087:         if ($codedom =~ /^$match_domain$/) {
                   7088:             my $chome = &domain($codedom,'primary');
                   7089:             unless ($chome eq 'no_host') {
                   7090:                 push(@homeservers,$chome);
                   7091:             }
                   7092:         }
1.521     raeburn  7093:     } else {
1.772     raeburn  7094:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7095:     }
1.793     albertel 7096:     foreach my $code (keys(%{$instcodes})) {
                   7097:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7098:     }
                   7099:     chop($courses);
1.772     raeburn  7100:     my $ok_response = 0;
                   7101:     my $response;
                   7102:     while (@homeservers > 0 && $ok_response == 0) {
                   7103:         my $server = shift(@homeservers); 
                   7104:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7105:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7106:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7107: 		split(/:/,$response);
1.772     raeburn  7108:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7109:             push(@{$codetitles},&str2array($codetitles_str));
                   7110:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7111:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7112:             $ok_response = 1;
                   7113:         }
                   7114:     }
                   7115:     if ($ok_response) {
1.521     raeburn  7116:         return 'ok';
1.772     raeburn  7117:     } else {
                   7118:         return $response;
1.521     raeburn  7119:     }
                   7120: }
                   7121: 
1.792     raeburn  7122: sub auto_instcode_defaults {
                   7123:     my ($domain,$returnhash,$code_order) = @_;
                   7124:     my @homeservers;
1.841     albertel 7125: 
                   7126:     my %servers = &get_servers($domain,'library');
                   7127:     foreach my $tryserver (keys(%servers)) {
                   7128: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7129: 	    push(@homeservers,$tryserver);
                   7130: 	}
1.792     raeburn  7131:     }
1.841     albertel 7132: 
1.792     raeburn  7133:     my $response;
1.841     albertel 7134:     foreach my $server (@homeservers) {
1.792     raeburn  7135:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7136:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7137: 	
                   7138: 	foreach my $pair (split(/\&/,$response)) {
                   7139: 	    my ($name,$value)=split(/\=/,$pair);
                   7140: 	    if ($name eq 'code_order') {
                   7141: 		@{$code_order} = split(/\&/,&unescape($value));
                   7142: 	    } else {
                   7143: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7144: 	    }
                   7145: 	}
                   7146: 	return 'ok';
1.792     raeburn  7147:     }
1.841     albertel 7148: 
                   7149:     return $response;
1.1003    raeburn  7150: }
                   7151: 
                   7152: sub auto_possible_instcodes {
1.1007    raeburn  7153:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7154:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7155:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7156:         return;
                   7157:     }
1.1003    raeburn  7158:     my (@homeservers,$uhome);
                   7159:     if (defined(&domain($domain,'primary'))) {
                   7160:         $uhome=&domain($domain,'primary');
                   7161:         push(@homeservers,&domain($domain,'primary'));
                   7162:     } else {
                   7163:         my %servers = &get_servers($domain,'library');
                   7164:         foreach my $tryserver (keys(%servers)) {
                   7165:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7166:                 push(@homeservers,$tryserver);
                   7167:             }
                   7168:         }
                   7169:     }
                   7170:     my $response;
                   7171:     foreach my $server (@homeservers) {
                   7172:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7173:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7174:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7175:             split(':',$response);
                   7176:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7177:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7178:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7179:             my ($name,$value)=split('=',$item);
                   7180:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7181:         }
                   7182:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7183:             my ($name,$value)=split('=',$item);
                   7184:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7185:         }
                   7186:         return 'ok';
                   7187:     }
                   7188:     return $response;
                   7189: }
1.792     raeburn  7190: 
1.1010    raeburn  7191: sub auto_courserequest_checks {
                   7192:     my ($dom) = @_;
1.1020    raeburn  7193:     my ($homeserver,%validations);
                   7194:     if ($dom =~ /^$match_domain$/) {
                   7195:         $homeserver = &domain($dom,'primary');
                   7196:     }
                   7197:     unless ($homeserver eq 'no_host') {
                   7198:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7199:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7200:             my @items = split(/&/,$response);
                   7201:             foreach my $item (@items) {
                   7202:                 my ($key,$value) = split('=',$item);
                   7203:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7204:             }
                   7205:         }
                   7206:     }
1.1010    raeburn  7207:     return %validations; 
                   7208: }
                   7209: 
1.1020    raeburn  7210: sub auto_courserequest_validation {
                   7211:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7212:     my ($homeserver,$response);
                   7213:     if ($dom =~ /^$match_domain$/) {
                   7214:         $homeserver = &domain($dom,'primary');
                   7215:     }
                   7216:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7217:           
1.1020    raeburn  7218:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7219:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7220:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7221:                                     $homeserver));
                   7222:     }
                   7223:     return $response;
                   7224: }
                   7225: 
1.777     albertel 7226: sub auto_validate_class_sec {
1.918     raeburn  7227:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7228:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7229:     my $ownerlist;
                   7230:     if (ref($owners) eq 'ARRAY') {
                   7231:         $ownerlist = join(',',@{$owners});
                   7232:     } else {
                   7233:         $ownerlist = $owners;
                   7234:     }
1.773     raeburn  7235:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7236:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7237:     return $response;
                   7238: }
                   7239: 
1.679     raeburn  7240: # ------------------------------------------------------- Course Group routines
                   7241: 
                   7242: sub get_coursegroups {
1.809     raeburn  7243:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7244:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7245: }
                   7246: 
1.679     raeburn  7247: sub modify_coursegroup {
                   7248:     my ($cdom,$cnum,$groupsettings) = @_;
                   7249:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7250: }
                   7251: 
1.809     raeburn  7252: sub toggle_coursegroup_status {
                   7253:     my ($cdom,$cnum,$group,$action) = @_;
                   7254:     my ($from_namespace,$to_namespace);
                   7255:     if ($action eq 'delete') {
                   7256:         $from_namespace = 'coursegroups';
                   7257:         $to_namespace = 'deleted_groups';
                   7258:     } else {
                   7259:         $from_namespace = 'deleted_groups';
                   7260:         $to_namespace = 'coursegroups';
                   7261:     }
                   7262:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7263:     if (my $tmp = &error(%curr_group)) {
                   7264:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7265:         return ('read error',$tmp);
                   7266:     } else {
                   7267:         my %savedsettings = %curr_group; 
1.809     raeburn  7268:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7269:         my $deloutcome;
                   7270:         if ($result eq 'ok') {
1.809     raeburn  7271:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7272:         } else {
                   7273:             return ('write error',$result);
                   7274:         }
                   7275:         if ($deloutcome eq 'ok') {
                   7276:             return 'ok';
                   7277:         } else {
                   7278:             return ('delete error',$deloutcome);
                   7279:         }
                   7280:     }
                   7281: }
                   7282: 
1.679     raeburn  7283: sub modify_group_roles {
1.957     raeburn  7284:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7285:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7286:     my $role = 'gr/'.&escape($userprivs);
                   7287:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7288:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7289:     if ($result eq 'ok') {
                   7290:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7291:     }
1.679     raeburn  7292:     return $result;
                   7293: }
                   7294: 
                   7295: sub modify_coursegroup_membership {
                   7296:     my ($cdom,$cnum,$membership) = @_;
                   7297:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7298:     return $result;
                   7299: }
                   7300: 
1.682     raeburn  7301: sub get_active_groups {
                   7302:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7303:     my $now = time;
                   7304:     my %groups = ();
                   7305:     foreach my $key (keys(%env)) {
1.811     albertel 7306:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7307:             my ($start,$end) = split(/\./,$env{$key});
                   7308:             if (($end!=0) && ($end<$now)) { next; }
                   7309:             if (($start!=0) && ($start>$now)) { next; }
                   7310:             if ($1 eq $cdom && $2 eq $cnum) {
                   7311:                 $groups{$3} = $env{$key} ;
                   7312:             }
                   7313:         }
                   7314:     }
                   7315:     return %groups;
                   7316: }
                   7317: 
1.683     raeburn  7318: sub get_group_membership {
                   7319:     my ($cdom,$cnum,$group) = @_;
                   7320:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7321: }
                   7322: 
                   7323: sub get_users_groups {
                   7324:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7325:     my @usersgroups;
1.683     raeburn  7326:     my $cachetime=1800;
                   7327: 
                   7328:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7329:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7330:     if (defined($cached)) {
1.734     albertel 7331:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7332:     } else {  
                   7333:         $grouplist = '';
1.816     raeburn  7334:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7335:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7336:         my $access_end = $env{'course.'.$courseid.
                   7337:                               '.default_enrollment_end_date'};
                   7338:         my $now = time;
                   7339:         foreach my $key (keys(%roleshash)) {
                   7340:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7341:                 my $group = $1;
                   7342:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7343:                     my $start = $2;
                   7344:                     my $end = $1;
                   7345:                     if ($start == -1) { next; } # deleted from group
                   7346:                     if (($start!=0) && ($start>$now)) { next; }
                   7347:                     if (($end!=0) && ($end<$now)) {
                   7348:                         if ($access_end && $access_end < $now) {
                   7349:                             if ($access_end - $end < 86400) {
                   7350:                                 push(@usersgroups,$group);
1.733     raeburn  7351:                             }
                   7352:                         }
1.817     raeburn  7353:                         next;
1.733     raeburn  7354:                     }
1.817     raeburn  7355:                     push(@usersgroups,$group);
1.683     raeburn  7356:                 }
                   7357:             }
                   7358:         }
1.817     raeburn  7359:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7360:         $grouplist = join(':',@usersgroups);
                   7361:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7362:     }
1.733     raeburn  7363:     return @usersgroups;
1.683     raeburn  7364: }
                   7365: 
                   7366: sub devalidate_getgroups_cache {
                   7367:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7368:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7369: 
1.683     raeburn  7370:     my $hashid="$udom:$uname:$courseid";
                   7371:     &devalidate_cache_new('getgroups',$hashid);
                   7372: }
                   7373: 
1.12      www      7374: # ------------------------------------------------------------------ Plain Text
                   7375: 
                   7376: sub plaintext {
1.988     raeburn  7377:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7378:     if ($short =~ m{^cr/}) {
1.758     albertel 7379: 	return (split('/',$short))[-1];
                   7380:     }
1.742     raeburn  7381:     if (!defined($cid)) {
                   7382:         $cid = $env{'request.course.id'};
                   7383:     }
                   7384:     my %rolenames = (
1.1008    raeburn  7385:                       Course    => 'std',
                   7386:                       Community => 'alt1',
1.742     raeburn  7387:                     );
1.1037    raeburn  7388:     if ($cid ne '') {
                   7389:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7390:             unless ($forcedefault) {
                   7391:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7392:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7393:                 return &Apache::lonlocal::mt($roletext);
                   7394:             }
                   7395:         }
                   7396:     }
                   7397:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7398:         (defined($rolenames{$type})) && 
                   7399:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7400:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7401:     } elsif ($cid ne '') {
                   7402:         my $crstype = $env{'course.'.$cid.'.type'};
                   7403:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7404:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7405:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7406:         }
1.742     raeburn  7407:     }
1.1037    raeburn  7408:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7409: }
                   7410: 
                   7411: # ----------------------------------------------------------------- Assign Role
                   7412: 
                   7413: sub assignrole {
1.957     raeburn  7414:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7415:         $context)=@_;
1.21      www      7416:     my $mrole;
                   7417:     if ($role =~ /^cr\//) {
1.393     www      7418:         my $cwosec=$url;
1.811     albertel 7419:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7420: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7421:            my $refused = 1;
                   7422:            if ($context eq 'requestcourses') {
                   7423:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7424:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7425:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7426:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7427:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7428:                            if ($crsenv{'internal.courseowner'} eq
                   7429:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7430:                                $refused = '';
                   7431:                            }
                   7432:                        }
                   7433:                    }
                   7434:                }
                   7435:            }
                   7436:            if ($refused) {
                   7437:                &logthis('Refused custom assignrole: '.
                   7438:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7439:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7440:                return 'refused';
                   7441:            }
1.104     www      7442:         }
1.21      www      7443:         $mrole='cr';
1.678     raeburn  7444:     } elsif ($role =~ /^gr\//) {
                   7445:         my $cwogrp=$url;
1.811     albertel 7446:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7447:         unless (&allowed('mdg',$cwogrp)) {
                   7448:             &logthis('Refused group assignrole: '.
                   7449:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7450:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7451:             return 'refused';
                   7452:         }
                   7453:         $mrole='gr';
1.21      www      7454:     } else {
1.82      www      7455:         my $cwosec=$url;
1.811     albertel 7456:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7457:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7458:             my $refused;
                   7459:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7460:                 if (!(&allowed('c'.$role,$url))) {
                   7461:                     $refused = 1;
                   7462:                 }
                   7463:             } else {
                   7464:                 $refused = 1;
                   7465:             }
1.947     raeburn  7466:             if ($refused) {
1.1045    raeburn  7467:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7468:                 if (!$selfenroll && $context eq 'course') {
                   7469:                     my %crsenv;
                   7470:                     if ($role eq 'cc' || $role eq 'co') {
                   7471:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7472:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7473:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7474:                                 if ($crsenv{'internal.courseowner'} eq 
                   7475:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7476:                                     $refused = '';
                   7477:                                 }
                   7478:                             }
                   7479:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7480:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7481:                                 if ($crsenv{'internal.courseowner'} eq 
                   7482:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7483:                                     $refused = '';
                   7484:                                 }
                   7485:                             }
                   7486:                         }
                   7487:                     }
                   7488:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7489:                     $refused = '';
1.1017    raeburn  7490:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7491:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7492:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7493:                         my $wrongcc;
                   7494:                         if ($cnum =~ /^$match_community$/) {
                   7495:                             $wrongcc = 1 if ($role eq 'cc');
                   7496:                         } else {
                   7497:                             $wrongcc = 1 if ($role eq 'co');
                   7498:                         }
                   7499:                         unless ($wrongcc) {
                   7500:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7501:                             if ($crsenv{'internal.courseowner'} eq 
                   7502:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7503:                                 $refused = '';
                   7504:                             }
1.1017    raeburn  7505:                         }
                   7506:                     }
                   7507:                 }
                   7508:                 if ($refused) {
1.947     raeburn  7509:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7510:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7511: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7512:                     return 'refused';
                   7513:                 }
1.932     raeburn  7514:             }
1.1131    raeburn  7515:         } elsif ($role eq 'au') {
                   7516:             if ($url ne '/'.$udom.'/') {
                   7517:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7518:                          ' to assign author role for '.$uname.':'.$udom.
                   7519:                          ' in domain: '.$url.' refused (wrong domain).');
                   7520:                 return 'refused';
                   7521:             }
1.104     www      7522:         }
1.21      www      7523:         $mrole=$role;
                   7524:     }
1.620     albertel 7525:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7526:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7527:     if ($end) { $command.='_'.$end; }
1.21      www      7528:     if ($start) {
                   7529: 	if ($end) { 
1.81      www      7530:            $command.='_'.$start; 
1.21      www      7531:         } else {
1.81      www      7532:            $command.='_0_'.$start;
1.21      www      7533:         }
                   7534:     }
1.739     raeburn  7535:     my $origstart = $start;
                   7536:     my $origend = $end;
1.957     raeburn  7537:     my $delflag;
1.357     www      7538: # actually delete
                   7539:     if ($deleteflag) {
1.373     www      7540: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7541: # modify command to delete the role
1.620     albertel 7542:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7543:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7544: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7545: # set start and finish to negative values for userrolelog
                   7546:            $start=-1;
                   7547:            $end=-1;
1.957     raeburn  7548:            $delflag = 1;
1.357     www      7549:         }
                   7550:     }
                   7551: # send command
1.349     www      7552:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7553: # log new user role if status is ok
1.349     www      7554:     if ($answer eq 'ok') {
1.663     raeburn  7555: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7556: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7557:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7558:         unless ($role =~ /^gr/) {
                   7559:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7560:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7561:         }
1.1053    raeburn  7562:         if ($role eq 'cc') {
                   7563:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7564:         }
1.349     www      7565:     }
                   7566:     return $answer;
1.169     harris41 7567: }
                   7568: 
1.1053    raeburn  7569: sub autoupdate_coowners {
                   7570:     my ($url,$end,$start,$uname,$udom) = @_;
                   7571:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7572:     if (($cdom ne '') && ($cnum ne '')) {
                   7573:         my $now = time;
                   7574:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7575:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7576:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7577:             my $instcode = $coursehash{'internal.coursecode'};
                   7578:             if ($instcode ne '') {
1.1056    raeburn  7579:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7580:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7581:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7582:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7583:                         if ($result eq 'valid') {
                   7584:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7585:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7586:                                     push(@newcoowners,$coowner);
                   7587:                                 }
                   7588:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7589:                                     push(@newcoowners,$uname.':'.$udom);
                   7590:                                 }
                   7591:                                 @newcoowners = sort(@newcoowners);
                   7592:                             } else {
                   7593:                                 push(@newcoowners,$uname.':'.$udom);
                   7594:                             }
                   7595:                         } else {
                   7596:                             if ($coursehash{'internal.co-owners'}) {
                   7597:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7598:                                     unless ($coowner eq $uname.':'.$udom) {
                   7599:                                         push(@newcoowners,$coowner);
                   7600:                                     }
                   7601:                                 }
                   7602:                                 unless (@newcoowners > 0) {
                   7603:                                     $delcoowners = 1;
                   7604:                                     $coowners = '';
                   7605:                                 }
                   7606:                             }
                   7607:                         }
                   7608:                         if (@newcoowners || $delcoowners) {
                   7609:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7610:                                             $delcoowners,@newcoowners);
                   7611:                         }
                   7612:                     }
                   7613:                 }
                   7614:             }
                   7615:         }
                   7616:     }
                   7617: }
                   7618: 
                   7619: sub store_coowners {
                   7620:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7621:     my $cid = $cdom.'_'.$cnum;
                   7622:     my ($coowners,$delresult,$putresult);
                   7623:     if (@newcoowners) {
                   7624:         $coowners = join(',',@newcoowners);
                   7625:         my %coownershash = (
                   7626:                             'internal.co-owners' => $coowners,
                   7627:                            );
                   7628:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7629:         if ($putresult eq 'ok') {
                   7630:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7631:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7632:             }
                   7633:         }
                   7634:     }
                   7635:     if ($delcoowners) {
                   7636:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7637:         if ($delresult eq 'ok') {
                   7638:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7639:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7640:             }
                   7641:         }
                   7642:     }
                   7643:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7644:         my %crsinfo =
                   7645:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7646:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7647:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7648:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7649:         }
                   7650:     }
                   7651: }
                   7652: 
1.169     harris41 7653: # -------------------------------------------------- Modify user authentication
1.197     www      7654: # Overrides without validation
                   7655: 
1.169     harris41 7656: sub modifyuserauth {
                   7657:     my ($udom,$uname,$umode,$upass)=@_;
                   7658:     my $uhome=&homeserver($uname,$udom);
1.197     www      7659:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7660:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7661:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7662:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7663:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7664: 		     &escape($upass),$uhome);
1.620     albertel 7665:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7666:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7667:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7668:     &log($udom,,$uname,$uhome,
1.620     albertel 7669:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7670:                                      $env{'user.name'}.', '.$umode.
1.197     www      7671:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7672:     unless ($reply eq 'ok') {
1.197     www      7673:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7674: 	return 'error: '.$reply;
                   7675:     }   
1.170     harris41 7676:     return 'ok';
1.80      www      7677: }
                   7678: 
1.81      www      7679: # --------------------------------------------------------------- Modify a user
1.80      www      7680: 
1.81      www      7681: sub modifyuser {
1.206     matthew  7682:     my ($udom,    $uname, $uid,
                   7683:         $umode,   $upass, $first,
                   7684:         $middle,  $last,  $gene,
1.1058    raeburn  7685:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7686:     $udom= &LONCAPA::clean_domain($udom);
                   7687:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7688:     my $showcandelete = 'none';
                   7689:     if (ref($candelete) eq 'ARRAY') {
                   7690:         if (@{$candelete} > 0) {
                   7691:             $showcandelete = join(', ',@{$candelete});
                   7692:         }
                   7693:     }
1.81      www      7694:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7695:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7696: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7697:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7698:                                      ' desiredhome not specified'). 
1.620     albertel 7699:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7700:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7701:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7702:     my $newuser;
                   7703:     if ($uhome eq 'no_host') {
                   7704:         $newuser = 1;
                   7705:     }
1.80      www      7706: # ----------------------------------------------------------------- Create User
1.406     albertel 7707:     if (($uhome eq 'no_host') && 
                   7708: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7709:         my $unhome='';
1.844     albertel 7710:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7711:             $unhome = $desiredhome;
1.620     albertel 7712: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7713: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7714:         } else { # load balancing routine for determining $unhome
1.81      www      7715:             my $loadm=10000000;
1.841     albertel 7716: 	    my %servers = &get_servers($udom,'library');
                   7717: 	    foreach my $tryserver (keys(%servers)) {
                   7718: 		my $answer=reply('load',$tryserver);
                   7719: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7720: 		    $loadm=$answer;
                   7721: 		    $unhome=$tryserver;
                   7722: 		}
1.80      www      7723: 	    }
                   7724:         }
                   7725:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7726: 	    return 'error: unable to find a home server for '.$uname.
                   7727:                    ' in domain '.$udom;
1.80      www      7728:         }
                   7729:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7730:                          &escape($upass),$unhome);
                   7731: 	unless ($reply eq 'ok') {
                   7732:             return 'error: '.$reply;
                   7733:         }   
1.230     stredwic 7734:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7735:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7736: 	    return 'error: unable verify users home machine.';
1.80      www      7737:         }
1.209     matthew  7738:     }   # End of creation of new user
1.80      www      7739: # ---------------------------------------------------------------------- Add ID
                   7740:     if ($uid) {
                   7741:        $uid=~tr/A-Z/a-z/;
                   7742:        my %uidhash=&idrget($udom,$uname);
1.196     www      7743:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7744:          && (!$forceid)) {
1.80      www      7745: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7746: 	      return 'error: user id "'.$uid.'" does not match '.
                   7747:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7748:           }
                   7749:        } else {
                   7750: 	  &idput($udom,($uname => $uid));
                   7751:        }
                   7752:     }
                   7753: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7754:     my @tmp=&get('environment',
1.899     raeburn  7755: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7756:                     'permanentemail','inststatus'],
1.134     albertel 7757: 		   $udom,$uname);
1.1075    raeburn  7758:     my (%names,%oldnames);
1.313     matthew  7759:     if ($tmp[0] =~ m/^error:.*/) { 
                   7760:         %names=(); 
                   7761:     } else {
                   7762:         %names = @tmp;
1.1075    raeburn  7763:         %oldnames = %names;
1.313     matthew  7764:     }
1.388     www      7765: #
1.1058    raeburn  7766: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7767: # of users did not contain them), do not overwrite existing values
                   7768: # unless field is in $candelete array ref.  
                   7769: #
                   7770: 
                   7771:     my @fields = ('firstname','middlename','lastname','generation',
                   7772:                   'permanentemail','id');
                   7773:     my %newvalues;
                   7774:     if (ref($candelete) eq 'ARRAY') {
                   7775:         foreach my $field (@fields) {
                   7776:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7777:                 if ($field eq 'firstname') {
                   7778:                     $names{$field} = $first;
                   7779:                 } elsif ($field eq 'middlename') {
                   7780:                     $names{$field} = $middle;
                   7781:                 } elsif ($field eq 'lastname') {
                   7782:                     $names{$field} = $last;
                   7783:                 } elsif ($field eq 'generation') { 
                   7784:                     $names{$field} = $gene;
                   7785:                 } elsif ($field eq 'permanentemail') {
                   7786:                     $names{$field} = $email;
                   7787:                 } elsif ($field eq 'id') {
                   7788:                     $names{$field}  = $uid;
                   7789:                 }
                   7790:             }
                   7791:         }
                   7792:     }
1.388     www      7793:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7794:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7795:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7796:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7797:     if ($email) {
                   7798:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7799:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7800:     }
1.899     raeburn  7801:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7802:     if (defined($inststatus)) {
                   7803:         $names{'inststatus'} = '';
                   7804:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7805:         if (ref($usertypes) eq 'HASH') {
                   7806:             my @okstatuses; 
                   7807:             foreach my $item (split(/:/,$inststatus)) {
                   7808:                 if (defined($usertypes->{$item})) {
                   7809:                     push(@okstatuses,$item);  
                   7810:                 }
                   7811:             }
                   7812:             if (@okstatuses) {
                   7813:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7814:             }
                   7815:         }
                   7816:     }
1.1075    raeburn  7817:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7818:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7819:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7820:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7821:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7822:     } else {
                   7823:         $logmsg .= ' during self creation';
                   7824:     }
1.1075    raeburn  7825:     my $changed;
                   7826:     if ($newuser) {
                   7827:         $changed = 1;
                   7828:     } else {
                   7829:         foreach my $field (@fields) {
                   7830:             if ($names{$field} ne $oldnames{$field}) {
                   7831:                 $changed = 1;
                   7832:                 last;
                   7833:             }
                   7834:         }
                   7835:     }
                   7836:     unless ($changed) {
                   7837:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7838:         &logthis($logmsg);
                   7839:         return 'ok';
                   7840:     }
                   7841:     my $reply = &put('environment', \%names, $udom,$uname);
                   7842:     if ($reply ne 'ok') { 
                   7843:         return 'error: '.$reply;
                   7844:     }
1.1087    raeburn  7845:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7846:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7847:     }
1.1075    raeburn  7848:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7849:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7850:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7851:     &logthis($logmsg);
1.134     albertel 7852:     return 'ok';
1.80      www      7853: }
                   7854: 
1.81      www      7855: # -------------------------------------------------------------- Modify student
1.80      www      7856: 
1.81      www      7857: sub modifystudent {
                   7858:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7859:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7860:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7861:     if (!$cid) {
1.620     albertel 7862: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7863: 	    return 'not_in_class';
                   7864: 	}
1.80      www      7865:     }
                   7866: # --------------------------------------------------------------- Make the user
1.81      www      7867:     my $reply=&modifyuser
1.209     matthew  7868: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7869:          $desiredhome,$email,$inststatus);
1.80      www      7870:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7871:     # This will cause &modify_student_enrollment to get the uid from the
                   7872:     # students environment
                   7873:     $uid = undef if (!$forceid);
1.455     albertel 7874:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7875: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7876:     return $reply;
                   7877: }
                   7878: 
                   7879: sub modify_student_enrollment {
1.957     raeburn  7880:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7881:     my ($cdom,$cnum,$chome);
                   7882:     if (!$cid) {
1.620     albertel 7883: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7884: 	    return 'not_in_class';
                   7885: 	}
1.620     albertel 7886: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7887: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7888:     } else {
                   7889: 	($cdom,$cnum)=split(/_/,$cid);
                   7890:     }
1.620     albertel 7891:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7892:     if (!$chome) {
1.457     raeburn  7893: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7894:     }
1.455     albertel 7895:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7896:     # Make sure the user exists
1.81      www      7897:     my $uhome=&homeserver($uname,$udom);
                   7898:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7899: 	return 'error: no such user';
                   7900:     }
1.297     matthew  7901:     # Get student data if we were not given enough information
                   7902:     if (!defined($first)  || $first  eq '' || 
                   7903:         !defined($last)   || $last   eq '' || 
                   7904:         !defined($uid)    || $uid    eq '' || 
                   7905:         !defined($middle) || $middle eq '' || 
                   7906:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7907:         # They did not supply us with enough data to enroll the student, so
                   7908:         # we need to pick up more information.
1.297     matthew  7909:         my %tmp = &get('environment',
1.294     matthew  7910:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7911:                        ,$udom,$uname);
                   7912: 
1.800     albertel 7913:         #foreach my $key (keys(%tmp)) {
                   7914:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7915:         #}
1.294     matthew  7916:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7917:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7918:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7919:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7920:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7921:     }
1.556     albertel 7922:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7923:     my $user = "$uname:$udom";
                   7924:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7925:     my $reply=cput('classlist',
1.1148    raeburn  7926: 		   {$user => 
1.515     raeburn  7927: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7928: 		   $cdom,$cnum);
1.1148    raeburn  7929:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7930:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7931:     } else { 
1.81      www      7932: 	return 'error: '.$reply;
                   7933:     }
1.297     matthew  7934:     # Add student role to user
1.83      www      7935:     my $uurl='/'.$cid;
1.81      www      7936:     $uurl=~s/\_/\//g;
                   7937:     if ($usec) {
                   7938: 	$uurl.='/'.$usec;
                   7939:     }
1.1148    raeburn  7940:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7941:                              $selfenroll,$context);
                   7942:     if ($result ne 'ok') {
                   7943:         if ($old_entry{$user} ne '') {
                   7944:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7945:         } else {
                   7946:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7947:         }
                   7948:     }
                   7949:     return $result; 
1.21      www      7950: }
                   7951: 
1.556     albertel 7952: sub format_name {
                   7953:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7954:     my $name;
                   7955:     if ($first ne 'lastname') {
                   7956: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7957:     } else {
                   7958: 	if ($lastname=~/\S/) {
                   7959: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7960: 	    $name=~s/\s+,/,/;
                   7961: 	} else {
                   7962: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7963: 	}
                   7964:     }
                   7965:     $name=~s/^\s+//;
                   7966:     $name=~s/\s+$//;
                   7967:     $name=~s/\s+/ /g;
                   7968:     return $name;
                   7969: }
                   7970: 
1.84      www      7971: # ------------------------------------------------- Write to course preferences
                   7972: 
                   7973: sub writecoursepref {
                   7974:     my ($courseid,%prefs)=@_;
                   7975:     $courseid=~s/^\///;
                   7976:     $courseid=~s/\_/\//g;
                   7977:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7978:     my $chome=homeserver($cnum,$cdomain);
                   7979:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7980: 	return 'error: no such course';
                   7981:     }
                   7982:     my $cstring='';
1.800     albertel 7983:     foreach my $pref (keys(%prefs)) {
                   7984: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7985:     }
1.84      www      7986:     $cstring=~s/\&$//;
                   7987:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7988: }
                   7989: 
                   7990: # ---------------------------------------------------------- Make/modify course
                   7991: 
                   7992: sub createcourse {
1.741     raeburn  7993:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7994:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7995:     $url=&declutter($url);
                   7996:     my $cid='';
1.1028    raeburn  7997:     if ($context eq 'requestcourses') {
                   7998:         my $can_create = 0;
                   7999:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8000:         if ($udom eq $ownerdom) {
                   8001:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8002:                                   $context)) {
                   8003:                 $can_create = 1;
                   8004:             }
                   8005:         } else {
                   8006:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8007:                                            $category);
                   8008:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8009:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8010:                 if (@curr > 0) {
                   8011:                     my @options = qw(approval validate autolimit);
                   8012:                     my $optregex = join('|',@options);
                   8013:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8014:                         $can_create = 1;
                   8015:                     }
                   8016:                 }
                   8017:             }
                   8018:         }
                   8019:         if ($can_create) {
                   8020:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8021:                 unless (&allowed('ccc',$udom)) {
                   8022:                     return 'refused'; 
                   8023:                 }
1.1017    raeburn  8024:             }
                   8025:         } else {
                   8026:             return 'refused';
                   8027:         }
1.1028    raeburn  8028:     } elsif (!&allowed('ccc',$udom)) {
                   8029:         return 'refused';
1.84      www      8030:     }
1.1011    raeburn  8031: # --------------------------------------------------------------- Get Unique ID
                   8032:     my $uname;
                   8033:     if ($cnum =~ /^$match_courseid$/) {
                   8034:         my $chome=&homeserver($cnum,$udom,'true');
                   8035:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8036:             $uname = $cnum;
                   8037:         } else {
1.1038    raeburn  8038:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8039:         }
                   8040:     } else {
1.1038    raeburn  8041:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8042:     }
                   8043:     return $uname if ($uname =~ /^error/);
                   8044: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8045:     if (!defined($course_server)) {
                   8046:         if (defined(&domain($udom,'primary'))) {
                   8047:             $course_server = &domain($udom,'primary');
                   8048:         } else {
                   8049:             $course_server = $env{'user.home'}; 
                   8050:         }
                   8051:     }
                   8052:     my %host_servers =
                   8053:         &Apache::lonnet::get_servers($udom,'library');
                   8054:     unless ($host_servers{$course_server}) {
                   8055:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8056:     }
1.84      www      8057: # ------------------------------------------------------------- Make the course
                   8058:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8059:                       $course_server);
1.84      www      8060:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8061:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8062:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8063: 	return 'error: no such course';
                   8064:     }
1.271     www      8065: # ----------------------------------------------------------------- Course made
1.516     raeburn  8066: # log existence
1.1029    raeburn  8067:     my $now = time;
1.918     raeburn  8068:     my $newcourse = {
                   8069:                     $udom.'_'.$uname => {
1.921     raeburn  8070:                                      description => $description,
                   8071:                                      inst_code   => $inst_code,
                   8072:                                      owner       => $course_owner,
                   8073:                                      type        => $crstype,
1.1029    raeburn  8074:                                      creator     => $env{'user.name'}.':'.
                   8075:                                                     $env{'user.domain'},
                   8076:                                      created     => $now,
                   8077:                                      context     => $context,
1.918     raeburn  8078:                                                 },
                   8079:                     };
1.921     raeburn  8080:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8081: # set toplevel url
1.271     www      8082:     my $topurl=$url;
                   8083:     unless ($nonstandard) {
                   8084: # ------------------------------------------ For standard courses, make top url
                   8085:         my $mapurl=&clutter($url);
1.278     www      8086:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8087:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8088: <map>
                   8089: <resource id="1" type="start"></resource>
                   8090: <resource id="2" src="$mapurl"></resource>
                   8091: <resource id="3" type="finish"></resource>
                   8092: <link index="1" from="1" to="2"></link>
                   8093: <link index="2" from="2" to="3"></link>
                   8094: </map>
                   8095: ENDINITMAP
                   8096:         $topurl=&declutter(
1.638     albertel 8097:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8098:                           );
                   8099:     }
                   8100: # ----------------------------------------------------------- Write preferences
1.84      www      8101:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8102:                      ('description'              => $description,
                   8103:                       'url'                      => $topurl,
                   8104:                       'internal.creator'         => $env{'user.name'}.':'.
                   8105:                                                     $env{'user.domain'},
                   8106:                       'internal.created'         => $now,
                   8107:                       'internal.creationcontext' => $context)
                   8108:                     );
1.84      www      8109:     return '/'.$udom.'/'.$uname;
                   8110: }
                   8111: 
1.1011    raeburn  8112: # ------------------------------------------------------------------- Create ID
                   8113: sub generate_coursenum {
1.1038    raeburn  8114:     my ($udom,$crstype) = @_;
1.1011    raeburn  8115:     my $domdesc = &domain($udom);
                   8116:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8117:     my $first;
                   8118:     if ($crstype eq 'Community') {
                   8119:         $first = '0';
                   8120:     } else {
                   8121:         $first = int(1+rand(9)); 
                   8122:     } 
                   8123:     my $uname=$first.
1.1011    raeburn  8124:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8125:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8126:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8127: # ----------------------------------------------- Make sure that does not exist
                   8128:     my $uhome=&homeserver($uname,$udom,'true');
                   8129:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8130:         if ($crstype eq 'Community') {
                   8131:             $first = '0';
                   8132:         } else {
                   8133:             $first = int(1+rand(9));
                   8134:         }
                   8135:         $uname=$first.
1.1011    raeburn  8136:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8137:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8138:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8139:         $uhome=&homeserver($uname,$udom,'true');
                   8140:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8141:             return 'error: unable to generate unique course-ID';
                   8142:         }
                   8143:     }
                   8144:     return $uname;
                   8145: }
                   8146: 
1.813     albertel 8147: sub is_course {
1.1167    droeschl 8148:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8149:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8150: 
                   8151:     return unless $cdom and $cnum;
                   8152: 
                   8153:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8154:         '.');
                   8155: 
                   8156:     return unless exists($courses{$cdom.'_'.$cnum});
                   8157:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8158: }
                   8159: 
1.1015    raeburn  8160: sub store_userdata {
                   8161:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8162:     my $result;
1.1016    raeburn  8163:     if ($datakey ne '') {
1.1013    raeburn  8164:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8165:             if ($udom eq '' || $uname eq '') {
                   8166:                 $udom = $env{'user.domain'};
                   8167:                 $uname = $env{'user.name'};
                   8168:             }
                   8169:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8170:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8171:                 $result = 'error: no_host';
                   8172:             } else {
                   8173:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8174:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8175: 
                   8176:                 my $namevalue='';
                   8177:                 foreach my $key (keys(%{$storehash})) {
                   8178:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8179:                 }
                   8180:                 $namevalue=~s/\&$//;
1.1105    raeburn  8181:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8182:                                   $namevalue,$uhome);
1.1013    raeburn  8183:             }
                   8184:         } else {
                   8185:             $result = 'error: data to store was not a hash reference'; 
                   8186:         }
                   8187:     } else {
                   8188:         $result= 'error: invalid requestkey'; 
                   8189:     }
                   8190:     return $result;
                   8191: }
                   8192: 
1.21      www      8193: # ---------------------------------------------------------- Assign Custom Role
                   8194: 
                   8195: sub assigncustomrole {
1.957     raeburn  8196:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8197:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8198:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8199: }
                   8200: 
                   8201: # ----------------------------------------------------------------- Revoke Role
                   8202: 
                   8203: sub revokerole {
1.957     raeburn  8204:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8205:     my $now=time;
1.965     raeburn  8206:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8207: }
                   8208: 
                   8209: # ---------------------------------------------------------- Revoke Custom Role
                   8210: 
                   8211: sub revokecustomrole {
1.957     raeburn  8212:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8213:     my $now=time;
1.357     www      8214:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8215:            $deleteflag,$selfenroll,$context);
1.17      www      8216: }
                   8217: 
1.533     banghart 8218: # ------------------------------------------------------------ Disk usage
1.535     albertel 8219: sub diskusage {
1.955     raeburn  8220:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8221:     $directorypath =~ s/\/$//;
                   8222:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8223:                        .&escape($getpropath).':'.&escape($uname).':'
                   8224:                        .&escape($udom),homeserver($uname,$udom));
                   8225:     if ($listing eq 'unknown_cmd') {
                   8226:         if ($getpropath) {
                   8227:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8228:         }
                   8229:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8230:     }
1.514     albertel 8231:     return $listing;
1.512     banghart 8232: }
                   8233: 
1.566     banghart 8234: sub is_locked {
1.1096    raeburn  8235:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8236:     my @check;
                   8237:     my $is_locked;
1.1093    raeburn  8238:     push (@check,$file_name);
1.613     albertel 8239:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8240: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8241:     my ($tmp)=keys(%locked);
                   8242:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8243:     
1.566     banghart 8244:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8245:         $is_locked = 'false';
                   8246:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8247:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8248:                $is_locked = 'true';
1.1096    raeburn  8249:                if (ref($which) eq 'ARRAY') {
                   8250:                    push(@{$which},$entry);
                   8251:                } else {
                   8252:                    last;
                   8253:                }
1.745     raeburn  8254:            }
                   8255:        }
1.566     banghart 8256:     } else {
                   8257:         $is_locked = 'false';
                   8258:     }
1.1093    raeburn  8259:     return $is_locked;
1.566     banghart 8260: }
                   8261: 
1.759     albertel 8262: sub declutter_portfile {
                   8263:     my ($file) = @_;
1.833     albertel 8264:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8265:     return $file;
                   8266: }
                   8267: 
1.559     banghart 8268: # ------------------------------------------------------------- Mark as Read Only
                   8269: 
                   8270: sub mark_as_readonly {
                   8271:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8272:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8273:     my ($tmp)=keys(%current_permissions);
                   8274:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8275:     foreach my $file (@{$files}) {
1.759     albertel 8276: 	$file = &declutter_portfile($file);
1.561     banghart 8277:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8278:     }
1.613     albertel 8279:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8280:     return;
                   8281: }
                   8282: 
1.572     banghart 8283: # ------------------------------------------------------------Save Selected Files
                   8284: 
                   8285: sub save_selected_files {
                   8286:     my ($user, $path, @files) = @_;
                   8287:     my $filename = $user."savedfiles";
1.573     banghart 8288:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8289:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8290:     foreach my $file (@files) {
1.620     albertel 8291:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8292:     }
                   8293:     foreach my $file (@other_files) {
1.574     banghart 8294:         print (OUT $file."\n");
1.572     banghart 8295:     }
1.574     banghart 8296:     close (OUT);
1.572     banghart 8297:     return 'ok';
                   8298: }
                   8299: 
1.574     banghart 8300: sub clear_selected_files {
                   8301:     my ($user) = @_;
                   8302:     my $filename = $user."savedfiles";
1.1117    foxr     8303:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8304:     print (OUT undef);
                   8305:     close (OUT);
                   8306:     return ("ok");    
                   8307: }
                   8308: 
1.572     banghart 8309: sub files_in_path {
                   8310:     my ($user, $path) = @_;
                   8311:     my $filename = $user."savedfiles";
                   8312:     my %return_files;
1.1117    foxr     8313:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8314:     while (my $line_in = <IN>) {
1.574     banghart 8315:         chomp ($line_in);
                   8316:         my @paths_and_file = split (m!/!, $line_in);
                   8317:         my $file_part = pop (@paths_and_file);
                   8318:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8319:         $path_part.='/';
                   8320:         my $path_and_file = $path_part.$file_part;
                   8321:         if ($path_part eq $path) {
                   8322:             $return_files{$file_part}= 'selected';
                   8323:         }
                   8324:     }
1.574     banghart 8325:     close (IN);
                   8326:     return (\%return_files);
1.572     banghart 8327: }
                   8328: 
                   8329: # called in portfolio select mode, to show files selected NOT in current directory
                   8330: sub files_not_in_path {
                   8331:     my ($user, $path) = @_;
                   8332:     my $filename = $user."savedfiles";
                   8333:     my @return_files;
                   8334:     my $path_part;
1.1117    foxr     8335:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8336:     while (my $line = <IN>) {
1.572     banghart 8337:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8338:         my @paths_and_file = split(m|/|, $line);
                   8339:         my $file_part = pop(@paths_and_file);
                   8340:         chomp($file_part);
                   8341:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8342:         $path_part .= '/';
                   8343:         my $path_and_file = $path_part.$file_part;
                   8344:         if ($path_part ne $path) {
1.800     albertel 8345:             push(@return_files, ($path_and_file));
1.572     banghart 8346:         }
                   8347:     }
1.800     albertel 8348:     close(OUT);
1.574     banghart 8349:     return (@return_files);
1.572     banghart 8350: }
                   8351: 
1.745     raeburn  8352: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8353: 
1.745     raeburn  8354: sub get_portfile_permissions {
                   8355:     my ($domain,$user) = @_;
1.613     albertel 8356:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8357:     my ($tmp)=keys(%current_permissions);
                   8358:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8359:     return \%current_permissions;
                   8360: }
                   8361: 
                   8362: #---------------------------------------------Get portfolio file access controls
                   8363: 
1.749     raeburn  8364: sub get_access_controls {
1.745     raeburn  8365:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8366:     my %access;
                   8367:     my $real_file = $file;
                   8368:     $file =~ s/\.meta$//;
1.745     raeburn  8369:     if (defined($file)) {
1.749     raeburn  8370:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8371:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8372:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8373:             }
                   8374:         }
1.745     raeburn  8375:     } else {
1.749     raeburn  8376:         foreach my $key (keys(%{$current_permissions})) {
                   8377:             if ($key =~ /\0accesscontrol$/) {
                   8378:                 if (defined($group)) {
                   8379:                     if ($key !~ m-^\Q$group\E/-) {
                   8380:                         next;
                   8381:                     }
                   8382:                 }
                   8383:                 my ($fullpath) = split(/\0/,$key);
                   8384:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8385:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8386:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8387:                     }
                   8388:                 }
                   8389:             }
                   8390:         }
                   8391:     }
                   8392:     return %access;
                   8393: }
                   8394: 
                   8395: sub modify_access_controls {
                   8396:     my ($file_name,$changes,$domain,$user)=@_;
                   8397:     my ($outcome,$deloutcome);
                   8398:     my %store_permissions;
                   8399:     my %new_values;
                   8400:     my %new_control;
                   8401:     my %translation;
                   8402:     my @deletions = ();
                   8403:     my $now = time;
                   8404:     if (exists($$changes{'activate'})) {
                   8405:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8406:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8407:             my $numnew = scalar(@newitems);
                   8408:             for (my $i=0; $i<$numnew; $i++) {
                   8409:                 my $newkey = $newitems[$i];
                   8410:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8411:                 if ($newkey =~ /^\d+:/) { 
                   8412:                     $newkey =~ s/^(\d+)/$newid/;
                   8413:                     $translation{$1} = $newid;
                   8414:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8415:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8416:                     $translation{$1} = $newid;
                   8417:                 }
1.749     raeburn  8418:                 $new_values{$file_name."\0".$newkey} = 
                   8419:                                           $$changes{'activate'}{$newitems[$i]};
                   8420:                 $new_control{$newkey} = $now;
                   8421:             }
                   8422:         }
                   8423:     }
                   8424:     my %todelete;
                   8425:     my %changed_items;
                   8426:     foreach my $action ('delete','update') {
                   8427:         if (exists($$changes{$action})) {
                   8428:             if (ref($$changes{$action}) eq 'HASH') {
                   8429:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8430:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8431:                     if ($action eq 'delete') { 
                   8432:                         $todelete{$itemnum} = 1;
                   8433:                     } else {
                   8434:                         $changed_items{$itemnum} = $key;
                   8435:                     }
                   8436:                 }
1.745     raeburn  8437:             }
                   8438:         }
1.749     raeburn  8439:     }
                   8440:     # get lock on access controls for file.
                   8441:     my $lockhash = {
                   8442:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8443:                                                        ':'.$env{'user.domain'},
                   8444:                    }; 
                   8445:     my $tries = 0;
                   8446:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8447:    
                   8448:     while (($gotlock ne 'ok') && $tries <3) {
                   8449:         $tries ++;
                   8450:         sleep 1;
                   8451:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8452:     }
                   8453:     if ($gotlock eq 'ok') {
                   8454:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8455:         my ($tmp)=keys(%curr_permissions);
                   8456:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8457:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8458:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8459:             if (ref($curr_controls) eq 'HASH') {
                   8460:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8461:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8462:                     if (defined($todelete{$itemnum})) {
                   8463:                         push(@deletions,$file_name."\0".$control_item);
                   8464:                     } else {
                   8465:                         if (defined($changed_items{$itemnum})) {
                   8466:                             $new_control{$changed_items{$itemnum}} = $now;
                   8467:                             push(@deletions,$file_name."\0".$control_item);
                   8468:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8469:                         } else {
                   8470:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8471:                         }
                   8472:                     }
1.745     raeburn  8473:                 }
                   8474:             }
                   8475:         }
1.970     raeburn  8476:         my ($group);
                   8477:         if (&is_course($domain,$user)) {
                   8478:             ($group,my $file) = split(/\//,$file_name,2);
                   8479:         }
1.749     raeburn  8480:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8481:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8482:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8483:         #  remove lock
                   8484:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8485:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8486:         my $sqlresult =
1.970     raeburn  8487:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8488:                                     $group);
1.749     raeburn  8489:     } else {
                   8490:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8491:     }
1.749     raeburn  8492:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8493: }
                   8494: 
1.827     raeburn  8495: sub make_public_indefinitely {
                   8496:     my ($requrl) = @_;
                   8497:     my $now = time;
                   8498:     my $action = 'activate';
                   8499:     my $aclnum = 0;
                   8500:     if (&is_portfolio_url($requrl)) {
                   8501:         my (undef,$udom,$unum,$file_name,$group) =
                   8502:             &parse_portfolio_url($requrl);
                   8503:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8504:         my %access_controls = &get_access_controls($current_perms,
                   8505:                                                    $group,$file_name);
                   8506:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8507:             my ($num,$scope,$end,$start) = 
                   8508:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8509:             if ($scope eq 'public') {
                   8510:                 if ($start <= $now && $end == 0) {
                   8511:                     $action = 'none';
                   8512:                 } else {
                   8513:                     $action = 'update';
                   8514:                     $aclnum = $num;
                   8515:                 }
                   8516:                 last;
                   8517:             }
                   8518:         }
                   8519:         if ($action eq 'none') {
                   8520:              return 'ok';
                   8521:         } else {
                   8522:             my %changes;
                   8523:             my $newend = 0;
                   8524:             my $newstart = $now;
                   8525:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8526:             $changes{$action}{$newkey} = {
                   8527:                 type => 'public',
                   8528:                 time => {
                   8529:                     start => $newstart,
                   8530:                     end   => $newend,
                   8531:                 },
                   8532:             };
                   8533:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8534:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8535:             return $outcome;
                   8536:         }
                   8537:     } else {
                   8538:         return 'invalid';
                   8539:     }
                   8540: }
                   8541: 
1.745     raeburn  8542: #------------------------------------------------------Get Marked as Read Only
                   8543: 
                   8544: sub get_marked_as_readonly {
                   8545:     my ($domain,$user,$what,$group) = @_;
                   8546:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8547:     my @readonly_files;
1.629     banghart 8548:     my $cmp1=$what;
                   8549:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8550:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8551:         if (defined($group)) {
                   8552:             if ($file_name !~ m-^\Q$group\E/-) {
                   8553:                 next;
                   8554:             }
                   8555:         }
1.561     banghart 8556:         if (ref($value) eq "ARRAY"){
                   8557:             foreach my $stored_what (@{$value}) {
1.629     banghart 8558:                 my $cmp2=$stored_what;
1.759     albertel 8559:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8560:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8561:                 }
1.629     banghart 8562:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8563:                     push(@readonly_files, $file_name);
1.745     raeburn  8564:                     last;
1.563     banghart 8565:                 } elsif (!defined($what)) {
                   8566:                     push(@readonly_files, $file_name);
1.745     raeburn  8567:                     last;
1.561     banghart 8568:                 }
                   8569:             }
1.745     raeburn  8570:         }
1.561     banghart 8571:     }
                   8572:     return @readonly_files;
                   8573: }
1.577     banghart 8574: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8575: 
1.577     banghart 8576: sub get_marked_as_readonly_hash {
1.745     raeburn  8577:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8578:     my %readonly_files;
1.745     raeburn  8579:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8580:         if (defined($group)) {
                   8581:             if ($file_name !~ m-^\Q$group\E/-) {
                   8582:                 next;
                   8583:             }
                   8584:         }
1.577     banghart 8585:         if (ref($value) eq "ARRAY"){
                   8586:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8587:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8588:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8589:                         if ($lock_descriptor eq 'graded') {
                   8590:                             $readonly_files{$file_name} = 'graded';
                   8591:                         } elsif ($lock_descriptor eq 'handback') {
                   8592:                             $readonly_files{$file_name} = 'handback';
                   8593:                         } else {
                   8594:                             if (!exists($readonly_files{$file_name})) {
                   8595:                                 $readonly_files{$file_name} = 'locked';
                   8596:                             }
                   8597:                         }
1.745     raeburn  8598:                     }
1.750     banghart 8599:                 } 
1.577     banghart 8600:             }
                   8601:         } 
                   8602:     }
                   8603:     return %readonly_files;
                   8604: }
1.559     banghart 8605: # ------------------------------------------------------------ Unmark as Read Only
                   8606: 
                   8607: sub unmark_as_readonly {
1.629     banghart 8608:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8609:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8610:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8611:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8612:     my $symb_crs = $what;
                   8613:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8614:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8615:     my ($tmp)=keys(%current_permissions);
                   8616:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8617:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8618:     foreach my $file (@readonly_files) {
1.759     albertel 8619: 	my $clean_file = &declutter_portfile($file);
                   8620: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8621: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8622:         my @new_locks;
                   8623:         my @del_keys;
                   8624:         if (ref($current_locks) eq "ARRAY"){
                   8625:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8626:                 my $compare=$locker;
1.749     raeburn  8627:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8628:                     $compare=join('',@{$locker});
1.746     raeburn  8629:                     if ($compare ne $symb_crs) {
                   8630:                         push(@new_locks, $locker);
                   8631:                     }
1.563     banghart 8632:                 }
                   8633:             }
1.650     albertel 8634:             if (scalar(@new_locks) > 0) {
1.563     banghart 8635:                 $current_permissions{$file} = \@new_locks;
                   8636:             } else {
                   8637:                 push(@del_keys, $file);
1.613     albertel 8638:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8639:                 delete($current_permissions{$file});
1.563     banghart 8640:             }
                   8641:         }
1.561     banghart 8642:     }
1.613     albertel 8643:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8644:     return;
                   8645: }
1.512     banghart 8646: 
1.17      www      8647: # ------------------------------------------------------------ Directory lister
                   8648: 
                   8649: sub dirlist {
1.955     raeburn  8650:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8651:     $uri=~s/^\///;
                   8652:     $uri=~s/\/$//;
1.253     stredwic 8653:     my ($udom, $uname);
1.955     raeburn  8654:     if ($getuserdir) {
1.253     stredwic 8655:         $udom = $userdomain;
                   8656:         $uname = $username;
1.955     raeburn  8657:     } else {
                   8658:         (undef,$udom,$uname)=split(/\//,$uri);
                   8659:         if(defined($userdomain)) {
                   8660:             $udom = $userdomain;
                   8661:         }
                   8662:         if(defined($username)) {
                   8663:             $uname = $username;
                   8664:         }
1.253     stredwic 8665:     }
1.955     raeburn  8666:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8667: 
1.955     raeburn  8668:     $dirRoot = $perlvar{'lonDocRoot'};
                   8669:     if (defined($getpropath)) {
                   8670:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8671:         $dirRoot =~ s/\/$//;
1.955     raeburn  8672:     } elsif (defined($getuserdir)) {
                   8673:         my $subdir=$uname.'__';
                   8674:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8675:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8676:                    ."/$udom/$subdir/$uname";
                   8677:     } elsif (defined($alternateRoot)) {
                   8678:         $dirRoot = $alternateRoot;
1.751     banghart 8679:     }
1.253     stredwic 8680: 
                   8681:     if($udom) {
                   8682:         if($uname) {
1.1135    raeburn  8683:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8684:             if ($uhome eq 'no_host') {
                   8685:                 return ([],'no_host');
                   8686:             }
1.955     raeburn  8687:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8688:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8689:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8690:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8691:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8692:             } else {
                   8693:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8694:             }
1.605     matthew  8695:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8696:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8697:                 @listing_results = split(/:/,$listing);
                   8698:             } else {
                   8699:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8700:             }
1.1135    raeburn  8701:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8702:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8703:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8704:                 return ([],$listing);
                   8705:             } else {
                   8706:                 return (\@listing_results);
1.1135    raeburn  8707:             }
1.955     raeburn  8708:         } elsif(!$alternateRoot) {
1.1136    raeburn  8709:             my (%allusers,%listerror);
1.841     albertel 8710: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8711:  	    foreach my $tryserver (keys(%servers)) {
                   8712:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8713:                                   &escape($udom),$tryserver);
                   8714:                 if ($listing eq 'unknown_cmd') {
                   8715: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8716: 				      $udom, $tryserver);
                   8717:                 } else {
                   8718:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8719:                 }
1.841     albertel 8720: 		if ($listing eq 'unknown_cmd') {
                   8721: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8722: 				      $udom, $tryserver);
                   8723: 		    @listing_results = split(/:/,$listing);
                   8724: 		} else {
                   8725: 		    @listing_results =
                   8726: 			map { &unescape($_); } split(/:/,$listing);
                   8727: 		}
1.1136    raeburn  8728:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8729:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8730:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8731:                     $listerror{$tryserver} = $listing;
                   8732:                 } else {
1.841     albertel 8733: 		    foreach my $line (@listing_results) {
                   8734: 			my ($entry) = split(/&/,$line,2);
                   8735: 			$allusers{$entry} = 1;
                   8736: 		    }
                   8737: 		}
1.253     stredwic 8738:             }
1.1136    raeburn  8739:             my @alluserslist=();
1.800     albertel 8740:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8741:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8742:             }
1.1136    raeburn  8743:             return (\@alluserslist);
1.253     stredwic 8744:         } else {
1.1136    raeburn  8745:             return ([],'missing username');
1.253     stredwic 8746:         }
1.955     raeburn  8747:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8748:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8749:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8750:         return (\@all_domains);
1.955     raeburn  8751:     } else {
1.1136    raeburn  8752:         return ([],'missing domain');
1.275     stredwic 8753:     }
                   8754: }
                   8755: 
                   8756: # --------------------------------------------- GetFileTimestamp
                   8757: # This function utilizes dirlist and returns the date stamp for
                   8758: # when it was last modified.  It will also return an error of -1
                   8759: # if an error occurs
                   8760: 
                   8761: sub GetFileTimestamp {
1.955     raeburn  8762:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8763:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8764:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8765:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8766:                                     undef,$getuserdir);
                   8767:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8768:         return -1;
                   8769:     }
                   8770:     if (ref($fileref) eq 'ARRAY') {
                   8771:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8772:         # @stats contains first the filename, then the stat output
                   8773:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8774:     } else {
                   8775:         return -1;
1.253     stredwic 8776:     }
1.26      www      8777: }
                   8778: 
1.712     albertel 8779: sub stat_file {
                   8780:     my ($uri) = @_;
1.787     albertel 8781:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8782: 
1.955     raeburn  8783:     my ($udom,$uname,$file);
1.712     albertel 8784:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8785: 	($udom,$uname,$file) =
1.811     albertel 8786: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8787: 	$file = 'userfiles/'.$file;
                   8788:     }
                   8789:     if ($uri =~ m-^/res/-) {
                   8790: 	($udom,$uname) = 
1.807     albertel 8791: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8792: 	$file = $uri;
                   8793:     }
                   8794: 
                   8795:     if (!$udom || !$uname || !$file) {
                   8796: 	# unable to handle the uri
                   8797: 	return ();
                   8798:     }
1.956     raeburn  8799:     my $getpropath;
                   8800:     if ($file =~ /^userfiles\//) {
                   8801:         $getpropath = 1;
                   8802:     }
1.1136    raeburn  8803:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8804:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8805:         return ();
                   8806:     } else {
                   8807:         if (ref($listref) eq 'ARRAY') {
                   8808:             my @stats = split('&',$listref->[0]);
                   8809: 	    shift(@stats); #filename is first
                   8810: 	    return @stats;
                   8811:         }
1.712     albertel 8812:     }
                   8813:     return ();
                   8814: }
                   8815: 
1.26      www      8816: # -------------------------------------------------------- Value of a Condition
                   8817: 
1.713     albertel 8818: # gets the value of a specific preevaluated condition
                   8819: #    stored in the string  $env{user.state.<cid>}
                   8820: # or looks up a condition reference in the bighash and if if hasn't
                   8821: # already been evaluated recurses into docondval to get the value of
                   8822: # the condition, then memoizing it to 
                   8823: #   $env{user.state.<cid>.<condition>}
1.40      www      8824: sub directcondval {
                   8825:     my $number=shift;
1.620     albertel 8826:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8827: 	&Apache::lonuserstate::evalstate();
                   8828:     }
1.713     albertel 8829:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8830: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8831:     } elsif ($number =~ /^_/) {
                   8832: 	my $sub_condition;
                   8833: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8834: 		&GDBM_READER(),0640)) {
                   8835: 	    $sub_condition=$bighash{'conditions'.$number};
                   8836: 	    untie(%bighash);
                   8837: 	}
                   8838: 	my $value = &docondval($sub_condition);
1.949     raeburn  8839: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8840: 	return $value;
                   8841:     }
1.620     albertel 8842:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8843:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8844:     } else {
                   8845:        return 2;
                   8846:     }
                   8847: }
                   8848: 
1.713     albertel 8849: # get the collection of conditions for this resource
1.26      www      8850: sub condval {
                   8851:     my $condidx=shift;
1.54      www      8852:     my $allpathcond='';
1.713     albertel 8853:     foreach my $cond (split(/\|/,$condidx)) {
                   8854: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8855: 	    $allpathcond.=
                   8856: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8857: 	}
1.191     harris41 8858:     }
1.54      www      8859:     $allpathcond=~s/\|$//;
1.713     albertel 8860:     return &docondval($allpathcond);
                   8861: }
                   8862: 
                   8863: #evaluates an expression of conditions
                   8864: sub docondval {
                   8865:     my ($allpathcond) = @_;
                   8866:     my $result=0;
                   8867:     if ($env{'request.course.id'}
                   8868: 	&& defined($allpathcond)) {
                   8869: 	my $operand='|';
                   8870: 	my @stack;
                   8871: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8872: 	    if ($chunk eq '(') {
                   8873: 		push @stack,($operand,$result);
                   8874: 	    } elsif ($chunk eq ')') {
                   8875: 		my $before=pop @stack;
                   8876: 		if (pop @stack eq '&') {
                   8877: 		    $result=$result>$before?$before:$result;
                   8878: 		} else {
                   8879: 		    $result=$result>$before?$result:$before;
                   8880: 		}
                   8881: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8882: 		$operand=$chunk;
                   8883: 	    } else {
                   8884: 		my $new=directcondval($chunk);
                   8885: 		if ($operand eq '&') {
                   8886: 		    $result=$result>$new?$new:$result;
                   8887: 		} else {
                   8888: 		    $result=$result>$new?$result:$new;
                   8889: 		}
                   8890: 	    }
                   8891: 	}
1.26      www      8892:     }
                   8893:     return $result;
1.421     albertel 8894: }
                   8895: 
                   8896: # ---------------------------------------------------- Devalidate courseresdata
                   8897: 
                   8898: sub devalidatecourseresdata {
                   8899:     my ($coursenum,$coursedomain)=@_;
                   8900:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8901:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8902: }
                   8903: 
1.763     www      8904: 
1.200     www      8905: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8906: #
                   8907: #  Parameters:
                   8908: #      $coursenum    - Number of the course.
                   8909: #      $coursedomain - Domain at which the course was created.
                   8910: #  Returns:
                   8911: #     A hash of the course parameters along (I think) with timestamps
                   8912: #     and version info.
1.877     foxr     8913: 
1.624     albertel 8914: sub get_courseresdata {
                   8915:     my ($coursenum,$coursedomain)=@_;
1.200     www      8916:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8917:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8918:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8919:     my %dumpreply;
1.417     albertel 8920:     unless (defined($cached)) {
1.624     albertel 8921: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8922: 	$result=\%dumpreply;
1.251     albertel 8923: 	my ($tmp) = keys(%dumpreply);
                   8924: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8925: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8926: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8927: 	    return $tmp;
1.416     albertel 8928: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8929: 	    $result=undef;
1.599     albertel 8930: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8931: 	}
                   8932:     }
1.624     albertel 8933:     return $result;
                   8934: }
                   8935: 
1.633     albertel 8936: sub devalidateuserresdata {
                   8937:     my ($uname,$udom)=@_;
                   8938:     my $hashid="$udom:$uname";
                   8939:     &devalidate_cache_new('userres',$hashid);
                   8940: }
                   8941: 
1.624     albertel 8942: sub get_userresdata {
                   8943:     my ($uname,$udom)=@_;
                   8944:     #most student don\'t have any data set, check if there is some data
                   8945:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8946: 
                   8947:     my $hashid="$udom:$uname";
                   8948:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8949:     if (!defined($cached)) {
                   8950: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8951: 	$result=\%resourcedata;
                   8952: 	&do_cache_new('userres',$hashid,$result,600);
                   8953:     }
                   8954:     my ($tmp)=keys(%$result);
                   8955:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8956: 	return $result;
                   8957:     }
                   8958:     #error 2 occurs when the .db doesn't exist
                   8959:     if ($tmp!~/error: 2 /) {
1.672     albertel 8960: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8961: 		 " Trying to get resource data for ".
                   8962: 		 $uname." at ".$udom.": ".
                   8963: 		 $tmp."</font>");
                   8964:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8965: 	#&EXT_cache_set($udom,$uname);
                   8966: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8967: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8968:     }
                   8969:     return $tmp;
                   8970: }
1.879     foxr     8971: #----------------------------------------------- resdata - return resource data
                   8972: #  Purpose:
                   8973: #    Return resource data for either users or for a course.
                   8974: #  Parameters:
                   8975: #     $name      - Course/user name.
                   8976: #     $domain    - Name of the domain the user/course is registered on.
                   8977: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8978: #     @which     - Array of names of resources desired.
                   8979: #  Returns:
                   8980: #     The value of the first reasource in @which that is found in the
                   8981: #     resource hash.
                   8982: #  Exceptional Conditions:
                   8983: #     If the $type passed in is not valid (not the string 'course' or 
                   8984: #     'user', an undefined  reference is returned.
                   8985: #     If none of the resources are found, an undef is returned
1.624     albertel 8986: sub resdata {
                   8987:     my ($name,$domain,$type,@which)=@_;
                   8988:     my $result;
                   8989:     if ($type eq 'course') {
                   8990: 	$result=&get_courseresdata($name,$domain);
                   8991:     } elsif ($type eq 'user') {
                   8992: 	$result=&get_userresdata($name,$domain);
                   8993:     }
                   8994:     if (!ref($result)) { return $result; }    
1.251     albertel 8995:     foreach my $item (@which) {
1.927     albertel 8996: 	if (defined($result->{$item->[0]})) {
                   8997: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8998: 	}
1.250     albertel 8999:     }
1.291     albertel 9000:     return undef;
1.200     www      9001: }
                   9002: 
1.379     matthew  9003: #
                   9004: # EXT resource caching routines
                   9005: #
                   9006: 
                   9007: sub clear_EXT_cache_status {
1.383     albertel 9008:     &delenv('cache.EXT.');
1.379     matthew  9009: }
                   9010: 
                   9011: sub EXT_cache_status {
                   9012:     my ($target_domain,$target_user) = @_;
1.383     albertel 9013:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9014:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9015:         # We know already the user has no data
                   9016:         return 1;
                   9017:     } else {
                   9018:         return 0;
                   9019:     }
                   9020: }
                   9021: 
                   9022: sub EXT_cache_set {
                   9023:     my ($target_domain,$target_user) = @_;
1.383     albertel 9024:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9025:     #&appenv({$cachename => time});
1.379     matthew  9026: }
                   9027: 
1.28      www      9028: # --------------------------------------------------------- Value of a Variable
1.58      www      9029: sub EXT {
1.715     albertel 9030: 
1.395     albertel 9031:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9032:     unless ($varname) { return ''; }
1.218     albertel 9033:     #get real user name/domain, courseid and symb
                   9034:     my $courseid;
1.359     albertel 9035:     my $publicuser;
1.427     www      9036:     if ($symbparm) {
                   9037: 	$symbparm=&get_symb_from_alias($symbparm);
                   9038:     }
1.218     albertel 9039:     if (!($uname && $udom)) {
1.790     albertel 9040:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9041:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9042:     } else {
1.620     albertel 9043: 	$courseid=$env{'request.course.id'};
1.218     albertel 9044:     }
1.48      www      9045:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9046:     my $rest;
1.320     albertel 9047:     if (defined($therest[0])) {
1.48      www      9048:        $rest=join('.',@therest);
                   9049:     } else {
                   9050:        $rest='';
                   9051:     }
1.320     albertel 9052: 
1.57      www      9053:     my $qualifierrest=$qualifier;
                   9054:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9055:     my $spacequalifierrest=$space;
                   9056:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9057:     if ($realm eq 'user') {
1.48      www      9058: # --------------------------------------------------------------- user.resource
                   9059: 	if ($space eq 'resource') {
1.651     albertel 9060: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9061: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9062: 		 &&
1.744     albertel 9063: 		 ($symbparm eq &symbread()) ) {	
                   9064: 		# if we are in the middle of processing the resource the
                   9065: 		# get the value we are planning on committing
                   9066:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9067:                     return $Apache::lonhomework::results{$qualifierrest};
                   9068:                 } else {
                   9069:                     return $Apache::lonhomework::history{$qualifierrest};
                   9070:                 }
1.335     albertel 9071: 	    } else {
1.359     albertel 9072: 		my %restored;
1.620     albertel 9073: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9074: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9075: 		} else {
                   9076: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9077: 		}
1.335     albertel 9078: 		return $restored{$qualifierrest};
                   9079: 	    }
1.48      www      9080: # ----------------------------------------------------------------- user.access
                   9081:         } elsif ($space eq 'access') {
1.218     albertel 9082: 	    # FIXME - not supporting calls for a specific user
1.48      www      9083:             return &allowed($qualifier,$rest);
                   9084: # ------------------------------------------ user.preferences, user.environment
                   9085:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9086: 	    if (($uname eq $env{'user.name'}) &&
                   9087: 		($udom eq $env{'user.domain'})) {
                   9088: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9089: 	    } else {
1.359     albertel 9090: 		my %returnhash;
                   9091: 		if (!$publicuser) {
                   9092: 		    %returnhash=&userenvironment($udom,$uname,
                   9093: 						 $qualifierrest);
                   9094: 		}
1.218     albertel 9095: 		return $returnhash{$qualifierrest};
                   9096: 	    }
1.48      www      9097: # ----------------------------------------------------------------- user.course
                   9098:         } elsif ($space eq 'course') {
1.218     albertel 9099: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9100:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9101: # ------------------------------------------------------------------- user.role
                   9102:         } elsif ($space eq 'role') {
1.218     albertel 9103: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9104:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9105:             if ($qualifier eq 'value') {
                   9106: 		return $role;
                   9107:             } elsif ($qualifier eq 'extent') {
                   9108:                 return $where;
                   9109:             }
                   9110: # ----------------------------------------------------------------- user.domain
                   9111:         } elsif ($space eq 'domain') {
1.218     albertel 9112:             return $udom;
1.48      www      9113: # ------------------------------------------------------------------- user.name
                   9114:         } elsif ($space eq 'name') {
1.218     albertel 9115:             return $uname;
1.48      www      9116: # ---------------------------------------------------- Any other user namespace
1.29      www      9117:         } else {
1.359     albertel 9118: 	    my %reply;
                   9119: 	    if (!$publicuser) {
                   9120: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9121: 	    }
                   9122: 	    return $reply{$qualifierrest};
1.48      www      9123:         }
1.236     www      9124:     } elsif ($realm eq 'query') {
                   9125: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9126:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9127: 						[$spacequalifierrest]);
1.620     albertel 9128: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9129:    } elsif ($realm eq 'request') {
1.48      www      9130: # ------------------------------------------------------------- request.browser
                   9131:         if ($space eq 'browser') {
1.1145    bisitz   9132:             return $env{'browser.'.$qualifier};
1.57      www      9133: # ------------------------------------------------------------ request.filename
                   9134:         } else {
1.620     albertel 9135:             return $env{'request.'.$spacequalifierrest};
1.29      www      9136:         }
1.28      www      9137:     } elsif ($realm eq 'course') {
1.48      www      9138: # ---------------------------------------------------------- course.description
1.620     albertel 9139:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9140:     } elsif ($realm eq 'resource') {
1.165     www      9141: 
1.620     albertel 9142: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9143: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9144: 	}
1.693     albertel 9145: 
                   9146: 	if ($space eq 'title') {
                   9147: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9148: 	    return &gettitle($symbparm);
                   9149: 	}
                   9150: 	
                   9151: 	if ($space eq 'map') {
                   9152: 	    my ($map) = &decode_symb($symbparm);
                   9153: 	    return &symbread($map);
                   9154: 	}
1.905     albertel 9155: 	if ($space eq 'filename') {
                   9156: 	    if ($symbparm) {
                   9157: 		return &clutter((&decode_symb($symbparm))[2]);
                   9158: 	    }
                   9159: 	    return &hreflocation('',$env{'request.filename'});
                   9160: 	}
1.693     albertel 9161: 
                   9162: 	my ($section, $group, @groups);
1.593     albertel 9163: 	my ($courselevelm,$courselevel);
1.539     albertel 9164: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9165: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9166: 
1.218     albertel 9167: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9168: 
1.60      www      9169: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9170: 	    my $symbp=$symbparm;
1.735     albertel 9171: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9172: 
                   9173: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9174: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9175: 
1.620     albertel 9176: 	    if (($env{'user.name'} eq $uname) &&
                   9177: 		($env{'user.domain'} eq $udom)) {
                   9178: 		$section=$env{'request.course.sec'};
1.733     raeburn  9179:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9180:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9181: 	    } else {
1.539     albertel 9182: 		if (! defined($usection)) {
1.551     albertel 9183: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9184: 		} else {
                   9185: 		    $section = $usection;
                   9186: 		}
1.733     raeburn  9187:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9188: 	    }
                   9189: 
                   9190: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9191: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9192: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9193: 
1.593     albertel 9194: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9195: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9196: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9197: 
1.60      www      9198: # ----------------------------------------------------------- first, check user
1.624     albertel 9199: 
                   9200: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9201: 				       ([$courselevelr,'resource'],
                   9202: 					[$courselevelm,'map'     ],
                   9203: 					[$courselevel, 'course'  ]));
1.931     albertel 9204: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9205: 
1.594     albertel 9206: # ------------------------------------------------ second, check some of course
1.684     raeburn  9207:             my $coursereply;
1.691     raeburn  9208:             if (@groups > 0) {
                   9209:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9210:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9211:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9212:             }
1.96      www      9213: 
1.684     raeburn  9214: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9215: 				  $env{'course.'.$courseid.'.domain'},
                   9216: 				  'course',
                   9217: 				  ([$seclevelr,   'resource'],
                   9218: 				   [$seclevelm,   'map'     ],
                   9219: 				   [$seclevel,    'course'  ],
                   9220: 				   [$courselevelr,'resource']));
                   9221: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9222: 
1.60      www      9223: # ------------------------------------------------------ third, check map parms
1.218     albertel 9224: 	    my %parmhash=();
                   9225: 	    my $thisparm='';
                   9226: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9227: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9228: 		    &GDBM_READER(),0640)) {
1.218     albertel 9229: 		$thisparm=$parmhash{$symbparm};
                   9230: 		untie(%parmhash);
                   9231: 	    }
1.927     albertel 9232: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9233: 	}
1.594     albertel 9234: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9235: 
1.218     albertel 9236: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9237: 	my $filename;
                   9238: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9239: 	if ($symbparm) {
1.409     www      9240: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9241: 	} else {
1.620     albertel 9242: 	    $filename=$env{'request.filename'};
1.282     albertel 9243: 	}
                   9244: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9245: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9246: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9247: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9248: 
1.927     albertel 9249: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9250: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9251: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9252: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9253: 				     $env{'course.'.$courseid.'.domain'},
                   9254: 				     'course',
1.927     albertel 9255: 				     ([$courselevelm,'map'   ],
                   9256: 				      [$courselevel, 'course']));
                   9257: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9258: 	}
1.145     www      9259: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9260: 	unless ($space eq '0') {
1.336     albertel 9261: 	    my @parts=split(/_/,$space);
                   9262: 	    my $id=pop(@parts);
                   9263: 	    my $part=join('_',@parts);
                   9264: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9265: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9266: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9267: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9268: 	}
1.395     albertel 9269: 	if ($recurse) { return undef; }
                   9270: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9271: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9272: # ---------------------------------------------------- Any other user namespace
                   9273:     } elsif ($realm eq 'environment') {
                   9274: # ----------------------------------------------------------------- environment
1.620     albertel 9275: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9276: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9277: 	} else {
1.770     albertel 9278: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9279: 		return '';
                   9280: 	    }
1.219     albertel 9281: 	    my %returnhash=&userenvironment($udom,$uname,
                   9282: 					    $spacequalifierrest);
                   9283: 	    return $returnhash{$spacequalifierrest};
                   9284: 	}
1.28      www      9285:     } elsif ($realm eq 'system') {
1.48      www      9286: # ----------------------------------------------------------------- system.time
                   9287: 	if ($space eq 'time') {
                   9288: 	    return time;
                   9289:         }
1.696     albertel 9290:     } elsif ($realm eq 'server') {
                   9291: # ----------------------------------------------------------------- system.time
                   9292: 	if ($space eq 'name') {
                   9293: 	    return $ENV{'SERVER_NAME'};
                   9294:         }
1.28      www      9295:     }
1.48      www      9296:     return '';
1.61      www      9297: }
                   9298: 
1.927     albertel 9299: sub get_reply {
                   9300:     my ($reply_value) = @_;
1.940     raeburn  9301:     if (ref($reply_value) eq 'ARRAY') {
                   9302:         if (wantarray) {
                   9303: 	    return @$reply_value;
                   9304:         }
                   9305:         return $reply_value->[0];
                   9306:     } else {
                   9307:         return $reply_value;
1.927     albertel 9308:     }
                   9309: }
                   9310: 
1.691     raeburn  9311: sub check_group_parms {
                   9312:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9313:     my @groupitems = ();
                   9314:     my $resultitem;
1.927     albertel 9315:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9316:     foreach my $group (@{$groups}) {
                   9317:         foreach my $level (@levels) {
1.927     albertel 9318:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9319:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9320:         }
                   9321:     }
                   9322:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9323:                             $env{'course.'.$courseid.'.domain'},
                   9324:                                      'course',@groupitems);
                   9325:     return $coursereply;
                   9326: }
                   9327: 
                   9328: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9329:     my ($courseid,@groups) = @_;
                   9330:     @groups = sort(@groups);
1.691     raeburn  9331:     return @groups;
                   9332: }
                   9333: 
1.395     albertel 9334: sub packages_tab_default {
                   9335:     my ($uri,$varname)=@_;
                   9336:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9337: 
                   9338:     my (@extension,@specifics,$do_default);
                   9339:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9340: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9341: 	if ($pack_type eq 'default') {
                   9342: 	    $do_default=1;
                   9343: 	} elsif ($pack_type eq 'extension') {
                   9344: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9345: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9346: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9347: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9348: 	}
                   9349:     }
                   9350:     # first look for a package that matches the requested part id
                   9351:     foreach my $package (@specifics) {
                   9352: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9353: 	next if ($pack_part ne $part);
                   9354: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9355: 	    return $packagetab{"$pack_type&$name&default"};
                   9356: 	}
                   9357:     }
                   9358:     # look for any possible matching non extension_ package
                   9359:     foreach my $package (@specifics) {
                   9360: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9361: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9362: 	    return $packagetab{"$pack_type&$name&default"};
                   9363: 	}
1.585     albertel 9364: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9365: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9366: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9367: 	}
                   9368:     }
1.738     albertel 9369:     # look for any posible extension_ match
                   9370:     foreach my $package (@extension) {
                   9371: 	my ($package,$pack_type)=@{$package};
                   9372: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9373: 	    return $packagetab{"$pack_type&$name&default"};
                   9374: 	}
                   9375: 	if (defined($packagetab{$package."&$name&default"})) {
                   9376: 	    return $packagetab{$package."&$name&default"};
                   9377: 	}
                   9378:     }
                   9379:     # look for a global default setting
                   9380:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9381: 	return $packagetab{"default&$name&default"};
                   9382:     }
1.395     albertel 9383:     return undef;
                   9384: }
                   9385: 
1.334     albertel 9386: sub add_prefix_and_part {
                   9387:     my ($prefix,$part)=@_;
                   9388:     my $keyroot;
                   9389:     if (defined($prefix) && $prefix !~ /^__/) {
                   9390: 	# prefix that has a part already
                   9391: 	$keyroot=$prefix;
                   9392:     } elsif (defined($prefix)) {
                   9393: 	# prefix that is missing a part
                   9394: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9395:     } else {
                   9396: 	# no prefix at all
                   9397: 	if (defined($part)) { $keyroot='_'.$part; }
                   9398:     }
                   9399:     return $keyroot;
                   9400: }
                   9401: 
1.71      www      9402: # ---------------------------------------------------------------- Get metadata
                   9403: 
1.599     albertel 9404: my %metaentry;
1.1070    www      9405: my %importedpartids;
1.71      www      9406: sub metadata {
1.176     www      9407:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9408:     $uri=&declutter($uri);
1.288     albertel 9409:     # if it is a non metadata possible uri return quickly
1.529     albertel 9410:     if (($uri eq '') || 
                   9411: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9412: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9413:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9414: 	return undef;
                   9415:     }
1.1140    www      9416:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9417: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9418: 	return undef;
1.288     albertel 9419:     }
1.73      www      9420:     my $filename=$uri;
                   9421:     $uri=~s/\.meta$//;
1.172     www      9422: #
                   9423: # Is the metadata already cached?
1.177     www      9424: # Look at timestamp of caching
1.172     www      9425: # Everything is cached by the main uri, libraries are never directly cached
                   9426: #
1.428     albertel 9427:     if (!defined($liburi)) {
1.599     albertel 9428: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9429: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9430:     }
                   9431:     {
1.1069    www      9432: # Imported parts would go here
1.1070    www      9433:         my %importedids=();
                   9434:         my @origfileimportpartids=();
1.1069    www      9435:         my $importedparts=0;
1.172     www      9436: #
                   9437: # Is this a recursive call for a library?
                   9438: #
1.599     albertel 9439: #	if (! exists($metacache{$uri})) {
                   9440: #	    $metacache{$uri}={};
                   9441: #	}
1.924     albertel 9442: 	my $cachetime = 60*60;
1.171     www      9443:         if ($liburi) {
                   9444: 	    $liburi=&declutter($liburi);
                   9445:             $filename=$liburi;
1.401     bowersj2 9446:         } else {
1.599     albertel 9447: 	    &devalidate_cache_new('meta',$uri);
                   9448: 	    undef(%metaentry);
1.401     bowersj2 9449: 	}
1.140     www      9450:         my %metathesekeys=();
1.73      www      9451:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9452: 	my $metastring;
1.1140    www      9453: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9454: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9455: 	    $metastring = 
1.929     albertel 9456: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9457: 					  ('grade_target' => 'meta'));
                   9458: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9459: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9460:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9461: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9462: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9463: 	    $metastring=&getfile($file);
1.489     albertel 9464: 	}
1.208     albertel 9465:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9466:         my $token;
1.140     www      9467:         undef %metathesekeys;
1.71      www      9468:         while ($token=$parser->get_token) {
1.339     albertel 9469: 	    if ($token->[0] eq 'S') {
                   9470: 		if (defined($token->[2]->{'package'})) {
1.172     www      9471: #
                   9472: # This is a package - get package info
                   9473: #
1.339     albertel 9474: 		    my $package=$token->[2]->{'package'};
                   9475: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9476: 		    if (defined($token->[2]->{'id'})) { 
                   9477: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9478: 		    }
1.599     albertel 9479: 		    if ($metaentry{':packages'}) {
                   9480: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9481: 		    } else {
1.599     albertel 9482: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9483: 		    }
1.736     albertel 9484: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9485: 			my $part=$keyroot;
                   9486: 			$part=~s/^\_//;
1.736     albertel 9487: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9488: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9489: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9490: 			    # ignore package.tab specified default values
                   9491:                             # here &package_tab_default() will fetch those
                   9492: 			    if ($subp eq 'default') { next; }
1.736     albertel 9493: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9494: 			    my $unikey;
                   9495: 			    if ($pack =~ /_0$/) {
                   9496: 				$unikey='parameter_0_'.$name;
                   9497: 				$part=0;
                   9498: 			    } else {
                   9499: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9500: 			    }
1.339     albertel 9501: 			    if ($subp eq 'display') {
                   9502: 				$value.=' [Part: '.$part.']';
                   9503: 			    }
1.599     albertel 9504: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9505: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9506: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9507: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9508: 			    }
1.599     albertel 9509: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9510: 				$metaentry{':'.$unikey}=
                   9511: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9512: 			    }
1.339     albertel 9513: 			}
                   9514: 		    }
                   9515: 		} else {
1.172     www      9516: #
                   9517: # This is not a package - some other kind of start tag
1.339     albertel 9518: #
                   9519: 		    my $entry=$token->[1];
1.1068    www      9520: 		    my $unikey='';
1.175     www      9521: 
1.339     albertel 9522: 		    if ($entry eq 'import') {
1.175     www      9523: #
                   9524: # Importing a library here
1.339     albertel 9525: #
1.1067    www      9526:                         my $location=$parser->get_text('/import');
                   9527:                         my $dir=$filename;
                   9528:                         $dir=~s|[^/]*$||;
                   9529:                         $location=&filelocation($dir,$location);
1.1069    www      9530:                        
1.1068    www      9531:                         my $importmode=$token->[2]->{'importmode'};
                   9532:                         if ($importmode eq 'problem') {
1.1069    www      9533: # Import as problem/response
1.1068    www      9534:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9535:                         } elsif ($importmode eq 'part') {
                   9536: # Import as part(s)
1.1069    www      9537:                            $importedparts=1;
                   9538: # We need to get the original file and the imported file to get the part order correct
                   9539: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9540: # Load and inspect original file
1.1070    www      9541:                            if ($#origfileimportpartids<0) {
                   9542:                               undef(%importedpartids);
                   9543:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9544:                               my $origfile=&getfile($origfilelocation);
                   9545:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9546:                            }
                   9547: 
1.1069    www      9548: # Load and inspect imported file
                   9549:                            my $impfile=&getfile($location);
                   9550:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9551:                            if ($#impfilepartids>=0) {
                   9552: # This problem had parts
1.1070    www      9553:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9554:                            } else {
                   9555: # Importing by turning a single problem into a problem part
                   9556: # It gets the import-tags ID as part-ID
                   9557:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9558:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9559:                            }
1.1068    www      9560:                         } else {
                   9561: # Normal import
                   9562:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9563:                            if (defined($token->[2]->{'id'})) {
                   9564:                               $unikey.='_'.$token->[2]->{'id'};
                   9565:                            }
1.1067    www      9566:                         }
                   9567: 
1.339     albertel 9568: 			if ($depthcount<20) {
1.736     albertel 9569: 			    my $metadata = 
                   9570: 				&metadata($uri,'keys', $location,$unikey,
                   9571: 					  $depthcount+1);
                   9572: 			    foreach my $meta (split(',',$metadata)) {
                   9573: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9574: 				$metathesekeys{$meta}=1;
1.339     albertel 9575: 			    }
1.1068    www      9576: 			
                   9577:                         }
1.1067    www      9578: 		    } else {
                   9579: #
                   9580: # Not importing, some other kind of non-package, non-library start tag
                   9581: # 
                   9582:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9583:                         if (defined($token->[2]->{'id'})) {
                   9584:                             $unikey.='_'.$token->[2]->{'id'};
                   9585:                         }
1.339     albertel 9586: 			if (defined($token->[2]->{'name'})) { 
                   9587: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9588: 			}
                   9589: 			$metathesekeys{$unikey}=1;
1.736     albertel 9590: 			foreach my $param (@{$token->[3]}) {
                   9591: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9592: 				$token->[2]->{$param};
1.339     albertel 9593: 			}
                   9594: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9595: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9596: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9597: 		 # only ws inside the tag, and not in default, so use default
                   9598: 		 # as value
1.599     albertel 9599: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9600: 			} elsif ( $internaltext =~ /\S/ ) {
                   9601: 		  # something interesting inside the tag
                   9602: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9603: 			} else {
1.908     albertel 9604: 		  # no interesting values, don't set a default
1.339     albertel 9605: 			}
1.172     www      9606: # end of not-a-package not-a-library import
1.339     albertel 9607: 		    }
1.172     www      9608: # end of not-a-package start tag
1.339     albertel 9609: 		}
1.172     www      9610: # the next is the end of "start tag"
1.339     albertel 9611: 	    }
                   9612: 	}
1.483     albertel 9613: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9614: 	$extension = lc($extension);
                   9615: 	if ($extension eq 'htm') { $extension='html'; }
                   9616: 
1.737     albertel 9617: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9618: 	    #no specific packages #how's our extension
                   9619: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9620: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9621: 					 \%metathesekeys);
                   9622: 	}
1.883     albertel 9623: 
                   9624: 	if (!exists($metaentry{':packages'})
                   9625: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9626: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9627: 		#no specific packages well let's get default then
                   9628: 		if ($key!~/^default&/) { next; }
1.488     albertel 9629: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9630: 					     \%metathesekeys);
                   9631: 	    }
                   9632: 	}
1.338     www      9633: # are there custom rights to evaluate
1.599     albertel 9634: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9635: 
1.338     www      9636:     #
                   9637:     # Importing a rights file here
1.339     albertel 9638:     #
                   9639: 	    unless ($depthcount) {
1.599     albertel 9640: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9641: 		my $dir=$filename;
                   9642: 		$dir=~s|[^/]*$||;
                   9643: 		$location=&filelocation($dir,$location);
1.736     albertel 9644: 		my $rights_metadata =
                   9645: 		    &metadata($uri,'keys',$location,'_rights',
                   9646: 			      $depthcount+1);
                   9647: 		foreach my $rights (split(',',$rights_metadata)) {
                   9648: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9649: 		    $metathesekeys{$rights}=1;
1.339     albertel 9650: 		}
                   9651: 	    }
                   9652: 	}
1.737     albertel 9653: 	# uniqifiy package listing
                   9654: 	my %seen;
                   9655: 	my @uniq_packages =
                   9656: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9657: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9658: 
1.1070    www      9659:         if ($importedparts) {
                   9660: # We had imported parts and need to rebuild partorder
                   9661:            $metaentry{':partorder'}='';
                   9662:            $metathesekeys{'partorder'}=1;
                   9663:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9664:                if ($origfileimportpartids[$index] eq 'part') {
                   9665: # original part, part of the problem
                   9666:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9667:                } else {
                   9668: # we have imported parts at this position
                   9669:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9670:                }
                   9671:            }
                   9672:            $metaentry{':partorder'}=~s/^\,//;
                   9673:         }
                   9674: 
1.737     albertel 9675: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9676: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9677: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9678: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9679: # this is the end of "was not already recently cached
1.71      www      9680:     }
1.599     albertel 9681:     return $metaentry{':'.$what};
1.261     albertel 9682: }
                   9683: 
1.488     albertel 9684: sub metadata_create_package_def {
1.483     albertel 9685:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9686:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9687:     if ($subp eq 'default') { next; }
                   9688:     
1.599     albertel 9689:     if (defined($metaentry{':packages'})) {
                   9690: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9691:     } else {
1.599     albertel 9692: 	$metaentry{':packages'}=$package;
1.483     albertel 9693:     }
                   9694:     my $value=$packagetab{$key};
                   9695:     my $unikey;
                   9696:     $unikey='parameter_0_'.$name;
1.599     albertel 9697:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9698:     $$metathesekeys{$unikey}=1;
1.599     albertel 9699:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9700: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9701:     }
1.599     albertel 9702:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9703: 	$metaentry{':'.$unikey}=
                   9704: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9705:     }
                   9706: }
                   9707: 
1.261     albertel 9708: sub metadata_generate_part0 {
                   9709:     my ($metadata,$metacache,$uri) = @_;
                   9710:     my %allnames;
1.737     albertel 9711:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9712: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9713: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9714: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9715: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9716: 	    $allnames{$name}=$part;
                   9717: 	  }
                   9718: 	}
                   9719:     }
                   9720:     foreach my $name (keys(%allnames)) {
                   9721:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9722:       my $key=":parameter_0_$name";
1.261     albertel 9723:       $$metacache{"$key.part"}='0';
                   9724:       $$metacache{"$key.name"}=$name;
1.428     albertel 9725:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9726: 					   $allnames{$name}.'_'.$name.
                   9727: 					   '.type'};
1.428     albertel 9728:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9729: 			     '.display'};
1.644     www      9730:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9731:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9732:       $$metacache{"$key.display"}=$olddis;
                   9733:     }
1.71      www      9734: }
                   9735: 
1.764     albertel 9736: # ------------------------------------------------------ Devalidate title cache
                   9737: 
                   9738: sub devalidate_title_cache {
                   9739:     my ($url)=@_;
                   9740:     if (!$env{'request.course.id'}) { return; }
                   9741:     my $symb=&symbread($url);
                   9742:     if (!$symb) { return; }
                   9743:     my $key=$env{'request.course.id'}."\0".$symb;
                   9744:     &devalidate_cache_new('title',$key);
                   9745: }
                   9746: 
1.1014    droeschl 9747: # ------------------------------------------------- Get the title of a course
                   9748: 
                   9749: sub current_course_title {
                   9750:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9751: }
1.301     www      9752: # ------------------------------------------------- Get the title of a resource
                   9753: 
                   9754: sub gettitle {
                   9755:     my $urlsymb=shift;
                   9756:     my $symb=&symbread($urlsymb);
1.534     albertel 9757:     if ($symb) {
1.620     albertel 9758: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9759: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9760: 	if (defined($cached)) { 
                   9761: 	    return $result;
                   9762: 	}
1.534     albertel 9763: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9764: 	my $title='';
1.907     albertel 9765: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9766: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9767: 	} else {
                   9768: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9769: 		    &GDBM_READER(),0640)) {
                   9770: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9771: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9772: 		untie(%bighash);
                   9773: 	    }
1.534     albertel 9774: 	}
                   9775: 	$title=~s/\&colon\;/\:/gs;
                   9776: 	if ($title) {
1.1159    www      9777: # Remember both $symb and $title for dynamic metadata
                   9778:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9779:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9780: # Cache this title and then return it
1.599     albertel 9781: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9782: 	}
                   9783: 	$urlsymb=$url;
                   9784:     }
                   9785:     my $title=&metadata($urlsymb,'title');
                   9786:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9787:     return $title;
1.301     www      9788: }
1.613     albertel 9789: 
1.614     albertel 9790: sub get_slot {
                   9791:     my ($which,$cnum,$cdom)=@_;
                   9792:     if (!$cnum || !$cdom) {
1.790     albertel 9793: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9794: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9795: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9796:     }
1.703     albertel 9797:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9798:     my %slotinfo;
                   9799:     if (exists($remembered{$key})) {
                   9800: 	$slotinfo{$which} = $remembered{$key};
                   9801:     } else {
                   9802: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9803: 	&Apache::lonhomework::showhash(%slotinfo);
                   9804: 	my ($tmp)=keys(%slotinfo);
                   9805: 	if ($tmp=~/^error:/) { return (); }
                   9806: 	$remembered{$key} = $slotinfo{$which};
                   9807:     }
1.616     albertel 9808:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9809: 	return %{$slotinfo{$which}};
                   9810:     }
                   9811:     return $slotinfo{$which};
1.614     albertel 9812: }
1.1150    raeburn  9813: 
                   9814: sub get_reservable_slots {
                   9815:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9816:     my $now = time;
                   9817:     my $reservable_info;
                   9818:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9819:     if (exists($remembered{$key})) {
                   9820:         $reservable_info = $remembered{$key};
                   9821:     } else {
                   9822:         my %resv;
                   9823:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9824:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9825:         $reservable_info = \%resv;
                   9826:         $remembered{$key} = $reservable_info;
                   9827:     }
                   9828:     return $reservable_info;
                   9829: }
                   9830: 
                   9831: sub get_course_slots {
                   9832:     my ($cnum,$cdom) = @_;
                   9833:     my $hashid=$cnum.':'.$cdom;
                   9834:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9835:     if (defined($cached)) {
                   9836:         if (ref($result) eq 'HASH') {
                   9837:             return %{$result};
                   9838:         }
                   9839:     } else {
                   9840:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9841:         my ($tmp) = keys(%slots);
                   9842:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9843:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9844:             return %slots;
                   9845:         }
                   9846:     }
                   9847:     return;
                   9848: }
                   9849: 
                   9850: sub devalidate_slots_cache {
                   9851:     my ($cnum,$cdom)=@_;
                   9852:     my $hashid=$cnum.':'.$cdom;
                   9853:     &devalidate_cache_new('allslots',$hashid);
                   9854: }
                   9855: 
1.1181    raeburn  9856: sub get_coursechange {
                   9857:     my ($cdom,$cnum) = @_;
                   9858:     if ($cdom eq '' || $cnum eq '') {
                   9859:         return unless ($env{'request.course.id'});
                   9860:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9861:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9862:     }
                   9863:     my $hashid=$cdom.'_'.$cnum;
                   9864:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   9865:     if ((defined($cached)) && ($change ne '')) {
                   9866:         return $change;
                   9867:     } else {
                   9868:         my %crshash;
                   9869:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   9870:         if ($crshash{'internal.contentchange'} eq '') {
                   9871:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   9872:             if ($change eq '') {
                   9873:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   9874:                 $change = $crshash{'internal.created'};
                   9875:             }
                   9876:         } else {
                   9877:             $change = $crshash{'internal.contentchange'};
                   9878:         }
                   9879:         my $cachetime = 600;
                   9880:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   9881:     }
                   9882:     return $change;
                   9883: }
                   9884: 
                   9885: sub devalidate_coursechange_cache {
                   9886:     my ($cnum,$cdom)=@_;
                   9887:     my $hashid=$cnum.':'.$cdom;
                   9888:     &devalidate_cache_new('crschange',$hashid);
                   9889: }
                   9890: 
1.31      www      9891: # ------------------------------------------------- Update symbolic store links
                   9892: 
                   9893: sub symblist {
                   9894:     my ($mapname,%newhash)=@_;
1.438     www      9895:     $mapname=&deversion(&declutter($mapname));
1.31      www      9896:     my %hash;
1.620     albertel 9897:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9898:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9899:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9900: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9901: 		next if ($url eq 'last_known'
                   9902: 			 && $env{'form.no_update_last_known'});
                   9903: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9904: 						    $newhash{$url}->[1],
                   9905: 						    $newhash{$url}->[0]);
1.191     harris41 9906:             }
1.31      www      9907:             if (untie(%hash)) {
                   9908: 		return 'ok';
                   9909:             }
                   9910:         }
                   9911:     }
                   9912:     return 'error';
1.212     www      9913: }
                   9914: 
                   9915: # --------------------------------------------------------------- Verify a symb
                   9916: 
                   9917: sub symbverify {
1.510     www      9918:     my ($symb,$thisurl)=@_;
                   9919:     my $thisfn=$thisurl;
1.439     www      9920:     $thisfn=&declutter($thisfn);
1.215     www      9921: # direct jump to resource in page or to a sequence - will construct own symbs
                   9922:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9923: # check URL part
1.409     www      9924:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9925: 
1.431     www      9926:     unless ($url eq $thisfn) { return 0; }
1.213     www      9927: 
1.216     www      9928:     $symb=&symbclean($symb);
1.510     www      9929:     $thisurl=&deversion($thisurl);
1.439     www      9930:     $thisfn=&deversion($thisfn);
1.213     www      9931: 
                   9932:     my %bighash;
                   9933:     my $okay=0;
1.431     www      9934: 
1.620     albertel 9935:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9936:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9937:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9938:             $thisurl =~ s/\?.+$//;
                   9939:         }
1.510     www      9940:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9941:         unless ($ids) {
                   9942:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9943:             $ids=$bighash{$idkey};
1.216     www      9944:         }
                   9945:         if ($ids) {
                   9946: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9947: 	    foreach my $id (split(/\,/,$ids)) {
                   9948: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9949:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9950:                    $symb =~ s/\?.+$//;
                   9951:                }
1.216     www      9952:                if (
                   9953:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9954:    eq $symb) { 
1.620     albertel 9955: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9956: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9957:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9958: 		       $okay=1; 
                   9959: 		   }
                   9960: 	       }
1.216     www      9961: 	   }
                   9962:         }
1.213     www      9963: 	untie(%bighash);
                   9964:     }
                   9965:     return $okay;
1.31      www      9966: }
                   9967: 
1.210     www      9968: # --------------------------------------------------------------- Clean-up symb
                   9969: 
                   9970: sub symbclean {
                   9971:     my $symb=shift;
1.568     albertel 9972:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9973: # remove version from map
                   9974:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9975: 
1.210     www      9976: # remove version from URL
                   9977:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9978: 
1.507     www      9979: # remove wrapper
                   9980: 
1.510     www      9981:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9982:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9983:     return $symb;
1.409     www      9984: }
                   9985: 
                   9986: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9987: 
                   9988: sub encode_symb {
                   9989:     my ($map,$resid,$url)=@_;
                   9990:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9991: }
1.409     www      9992: 
                   9993: sub decode_symb {
1.568     albertel 9994:     my $symb=shift;
                   9995:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9996:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9997:     return (&fixversion($map),$resid,&fixversion($url));
                   9998: }
                   9999: 
                   10000: sub fixversion {
                   10001:     my $fn=shift;
1.609     banghart 10002:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10003:     my %bighash;
                   10004:     my $uri=&clutter($fn);
1.620     albertel 10005:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10006: # is this cached?
1.599     albertel 10007:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10008:     if (defined($cached)) { return $result; }
                   10009: # unfortunately not cached, or expired
1.620     albertel 10010:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10011: 	    &GDBM_READER(),0640)) {
                   10012:  	if ($bighash{'version_'.$uri}) {
                   10013:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10014:  	    unless (($version eq 'mostrecent') || 
                   10015: 		    ($version==&getversion($uri))) {
1.440     www      10016:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10017:  	    }
                   10018:  	}
                   10019:  	untie %bighash;
1.413     www      10020:     }
1.599     albertel 10021:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10022: }
                   10023: 
                   10024: sub deversion {
                   10025:     my $url=shift;
                   10026:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10027:     return $url;
1.210     www      10028: }
                   10029: 
1.31      www      10030: # ------------------------------------------------------ Return symb list entry
                   10031: 
                   10032: sub symbread {
1.249     www      10033:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10034:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1179    raeburn  10035:     if (defined($env{$cache_str})) {
                   10036:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10037:             return $env{$cache_str};
                   10038:         }
                   10039:     }
1.242     www      10040: # no filename provided? try from environment
1.44      www      10041:     unless ($thisfn) {
1.620     albertel 10042:         if ($env{'request.symb'}) {
                   10043: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10044: 	}
1.620     albertel 10045: 	$thisfn=$env{'request.filename'};
1.44      www      10046:     }
1.569     albertel 10047:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10048: # is that filename actually a symb? Verify, clean, and return
                   10049:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10050: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10051: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10052: 	}
1.242     www      10053:     }
1.44      www      10054:     $thisfn=declutter($thisfn);
1.31      www      10055:     my %hash;
1.37      www      10056:     my %bighash;
                   10057:     my $syval='';
1.620     albertel 10058:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10059:         my $targetfn = $thisfn;
1.609     banghart 10060:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10061:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10062:         }
1.687     albertel 10063: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10064: 	    $targetfn=$1;
                   10065: 	}
1.620     albertel 10066:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10067:                       &GDBM_READER(),0640)) {
1.481     raeburn  10068: 	    $syval=$hash{$targetfn};
1.37      www      10069:             untie(%hash);
                   10070:         }
                   10071: # ---------------------------------------------------------- There was an entry
                   10072:         if ($syval) {
1.601     albertel 10073: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10074: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10075: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10076: 		    #return $env{$cache_str}='';
1.601     albertel 10077: 		#}    
                   10078: 		#$syval.=$1;
                   10079: 	    #}
1.37      www      10080:         } else {
                   10081: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10082:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10083:                             &GDBM_READER(),0640)) {
1.37      www      10084: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10085:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10086:               unless ($ids) { 
                   10087:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10088:               }
                   10089:               unless ($ids) {
                   10090: # alias?
                   10091: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10092:               }
1.37      www      10093:               if ($ids) {
                   10094: # ------------------------------------------------------------------- Has ID(s)
                   10095:                  my @possibilities=split(/\,/,$ids);
1.39      www      10096:                  if ($#possibilities==0) {
                   10097: # ----------------------------------------------- There is only one possibility
1.37      www      10098: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10099: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10100: 						    $resid,$thisfn);
1.249     www      10101:                  } elsif (!$donotrecurse) {
1.39      www      10102: # ------------------------------------------ There is more than one possibility
                   10103:                      my $realpossible=0;
1.800     albertel 10104:                      foreach my $id (@possibilities) {
                   10105: 			 my $file=$bighash{'src_'.$id};
1.39      www      10106:                          if (&allowed('bre',$file)) {
1.800     albertel 10107:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10108:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10109: 				$realpossible++;
1.626     albertel 10110:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10111: 						    $resid,$thisfn);
1.39      www      10112:                             }
                   10113: 			 }
1.191     harris41 10114:                      }
1.39      www      10115: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10116:                  } else {
                   10117:                      $syval='';
1.37      www      10118:                  }
                   10119: 	      }
                   10120:               untie(%bighash)
1.481     raeburn  10121:            }
1.31      www      10122:         }
1.62      www      10123:         if ($syval) {
1.620     albertel 10124: 	    return $env{$cache_str}=$syval;
1.62      www      10125:         }
1.31      www      10126:     }
1.949     raeburn  10127:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10128:     return $env{$cache_str}='';
1.31      www      10129: }
                   10130: 
                   10131: # ---------------------------------------------------------- Return random seed
                   10132: 
1.32      www      10133: sub numval {
                   10134:     my $txt=shift;
                   10135:     $txt=~tr/A-J/0-9/;
                   10136:     $txt=~tr/a-j/0-9/;
                   10137:     $txt=~tr/K-T/0-9/;
                   10138:     $txt=~tr/k-t/0-9/;
                   10139:     $txt=~tr/U-Z/0-5/;
                   10140:     $txt=~tr/u-z/0-5/;
                   10141:     $txt=~s/\D//g;
1.564     albertel 10142:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10143:     return int($txt);
1.368     albertel 10144: }
                   10145: 
1.484     albertel 10146: sub numval2 {
                   10147:     my $txt=shift;
                   10148:     $txt=~tr/A-J/0-9/;
                   10149:     $txt=~tr/a-j/0-9/;
                   10150:     $txt=~tr/K-T/0-9/;
                   10151:     $txt=~tr/k-t/0-9/;
                   10152:     $txt=~tr/U-Z/0-5/;
                   10153:     $txt=~tr/u-z/0-5/;
                   10154:     $txt=~s/\D//g;
                   10155:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10156:     my $total;
                   10157:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10158:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10159:     return int($total);
                   10160: }
                   10161: 
1.575     albertel 10162: sub numval3 {
                   10163:     use integer;
                   10164:     my $txt=shift;
                   10165:     $txt=~tr/A-J/0-9/;
                   10166:     $txt=~tr/a-j/0-9/;
                   10167:     $txt=~tr/K-T/0-9/;
                   10168:     $txt=~tr/k-t/0-9/;
                   10169:     $txt=~tr/U-Z/0-5/;
                   10170:     $txt=~tr/u-z/0-5/;
                   10171:     $txt=~s/\D//g;
                   10172:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10173:     my $total;
                   10174:     foreach my $val (@txts) { $total+=$val; }
                   10175:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10176:     return $total;
                   10177: }
                   10178: 
1.675     albertel 10179: sub digest {
                   10180:     my ($data)=@_;
                   10181:     my $digest=&Digest::MD5::md5($data);
                   10182:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10183:     my ($e,$f);
                   10184:     {
                   10185:         use integer;
                   10186:         $e=($a+$b);
                   10187:         $f=($c+$d);
                   10188:         if ($_64bit) {
                   10189:             $e=(($e<<32)>>32);
                   10190:             $f=(($f<<32)>>32);
                   10191:         }
                   10192:     }
                   10193:     if (wantarray) {
                   10194: 	return ($e,$f);
                   10195:     } else {
                   10196: 	my $g;
                   10197: 	{
                   10198: 	    use integer;
                   10199: 	    $g=($e+$f);
                   10200: 	    if ($_64bit) {
                   10201: 		$g=(($g<<32)>>32);
                   10202: 	    }
                   10203: 	}
                   10204: 	return $g;
                   10205:     }
                   10206: }
                   10207: 
1.368     albertel 10208: sub latest_rnd_algorithm_id {
1.675     albertel 10209:     return '64bit5';
1.366     albertel 10210: }
1.32      www      10211: 
1.503     albertel 10212: sub get_rand_alg {
                   10213:     my ($courseid)=@_;
1.790     albertel 10214:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10215:     if ($courseid) {
1.620     albertel 10216: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10217:     }
                   10218:     return &latest_rnd_algorithm_id();
                   10219: }
                   10220: 
1.562     albertel 10221: sub validCODE {
                   10222:     my ($CODE)=@_;
                   10223:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10224:     return 0;
                   10225: }
                   10226: 
1.491     albertel 10227: sub getCODE {
1.620     albertel 10228:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10229:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10230: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10231: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10232: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10233:     }
                   10234:     return undef;
                   10235: }
1.1133    foxr     10236: #
                   10237: #  Determines the random seed for a specific context:
                   10238: #
                   10239: # parameters:
                   10240: #   symb      - in course context the symb for the seed.
                   10241: #   course_id - The course id of the form domain_coursenum.
                   10242: #   domain    - Domain for the user.
                   10243: #   course    - Course for the user.
                   10244: #   cenv      - environment of the course.
                   10245: #
                   10246: # NOTE:
                   10247: #   All parameters are picked out of the environment if missing
                   10248: #   or not defined.
                   10249: #   If a symb cannot be determined the current time is used instead.
                   10250: #
                   10251: #  For a given well defined symb, courside, domain, username,
                   10252: #  and course environment, the seed is reproducible.
                   10253: #
1.31      www      10254: sub rndseed {
1.1133    foxr     10255:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10256:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10257:     if (!defined($symb)) {
1.366     albertel 10258: 	unless ($symb=$wsymb) { return time; }
                   10259:     }
1.1146    foxr     10260:     if (!defined $courseid) { 
                   10261: 	$courseid=$wcourseid; 
                   10262:     }
                   10263:     if (!defined $domain) { $domain=$wdomain; }
                   10264:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10265: 
                   10266:     my $which;
                   10267:     if (defined($cenv->{'rndseed'})) {
                   10268: 	$which = $cenv->{'rndseed'};
                   10269:     } else {
                   10270: 	$which =&get_rand_alg($courseid);
                   10271:     }
1.491     albertel 10272:     if (defined(&getCODE())) {
1.1133    foxr     10273: 
1.675     albertel 10274: 	if ($which eq '64bit5') {
                   10275: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10276: 	} elsif ($which eq '64bit4') {
1.575     albertel 10277: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10278: 	} else {
                   10279: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10280: 	}
1.675     albertel 10281:     } elsif ($which eq '64bit5') {
                   10282: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10283:     } elsif ($which eq '64bit4') {
                   10284: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10285:     } elsif ($which eq '64bit3') {
                   10286: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10287:     } elsif ($which eq '64bit2') {
                   10288: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10289:     } elsif ($which eq '64bit') {
                   10290: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10291:     }
                   10292:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10293: }
                   10294: 
                   10295: sub rndseed_32bit {
                   10296:     my ($symb,$courseid,$domain,$username)=@_;
                   10297:     {
                   10298: 	use integer;
                   10299: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10300: 	my $symbseed=numval($symb) << 22;
                   10301: 	my $namechck=unpack("%32C*",$username) << 17;
                   10302: 	my $nameseed=numval($username) << 12;
                   10303: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10304: 	my $courseseed=unpack("%32C*",$courseid);
                   10305: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10306: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10307: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10308: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10309: 	return $num;
                   10310:     }
                   10311: }
                   10312: 
                   10313: sub rndseed_64bit {
                   10314:     my ($symb,$courseid,$domain,$username)=@_;
                   10315:     {
                   10316: 	use integer;
                   10317: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10318: 	my $symbseed=numval($symb) << 10;
                   10319: 	my $namechck=unpack("%32S*",$username);
                   10320: 	
                   10321: 	my $nameseed=numval($username) << 21;
                   10322: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10323: 	my $courseseed=unpack("%32S*",$courseid);
                   10324: 	
                   10325: 	my $num1=$symbchck+$symbseed+$namechck;
                   10326: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10327: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10328: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10329: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10330: 	return "$num1,$num2";
1.155     albertel 10331:     }
1.366     albertel 10332: }
                   10333: 
1.443     albertel 10334: sub rndseed_64bit2 {
                   10335:     my ($symb,$courseid,$domain,$username)=@_;
                   10336:     {
                   10337: 	use integer;
                   10338: 	# strings need to be an even # of cahracters long, it it is odd the
                   10339:         # last characters gets thrown away
                   10340: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10341: 	my $symbseed=numval($symb) << 10;
                   10342: 	my $namechck=unpack("%32S*",$username.' ');
                   10343: 	
                   10344: 	my $nameseed=numval($username) << 21;
1.501     albertel 10345: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10346: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10347: 	
                   10348: 	my $num1=$symbchck+$symbseed+$namechck;
                   10349: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10350: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10351: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10352: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10353: 	return "$num1,$num2";
                   10354:     }
                   10355: }
                   10356: 
                   10357: sub rndseed_64bit3 {
                   10358:     my ($symb,$courseid,$domain,$username)=@_;
                   10359:     {
                   10360: 	use integer;
                   10361: 	# strings need to be an even # of cahracters long, it it is odd the
                   10362:         # last characters gets thrown away
                   10363: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10364: 	my $symbseed=numval2($symb) << 10;
                   10365: 	my $namechck=unpack("%32S*",$username.' ');
                   10366: 	
                   10367: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10368: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10369: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10370: 	
                   10371: 	my $num1=$symbchck+$symbseed+$namechck;
                   10372: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10373: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10374: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10375: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10376: 	
1.503     albertel 10377: 	return "$num1:$num2";
1.443     albertel 10378:     }
                   10379: }
                   10380: 
1.575     albertel 10381: sub rndseed_64bit4 {
                   10382:     my ($symb,$courseid,$domain,$username)=@_;
                   10383:     {
                   10384: 	use integer;
                   10385: 	# strings need to be an even # of cahracters long, it it is odd the
                   10386:         # last characters gets thrown away
                   10387: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10388: 	my $symbseed=numval3($symb) << 10;
                   10389: 	my $namechck=unpack("%32S*",$username.' ');
                   10390: 	
                   10391: 	my $nameseed=numval3($username) << 21;
                   10392: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10393: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10394: 	
                   10395: 	my $num1=$symbchck+$symbseed+$namechck;
                   10396: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10397: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10398: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10399: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10400: 	
1.575     albertel 10401: 	return "$num1:$num2";
                   10402:     }
                   10403: }
                   10404: 
1.675     albertel 10405: sub rndseed_64bit5 {
                   10406:     my ($symb,$courseid,$domain,$username)=@_;
                   10407:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10408:     return "$num1:$num2";
                   10409: }
                   10410: 
1.366     albertel 10411: sub rndseed_CODE_64bit {
                   10412:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10413:     {
1.366     albertel 10414: 	use integer;
1.443     albertel 10415: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10416: 	my $symbseed=numval2($symb);
1.491     albertel 10417: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10418: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10419: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10420: 	my $num1=$symbseed+$CODEchck;
                   10421: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10422: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10423: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10424: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10425: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10426: 	return "$num1:$num2";
1.366     albertel 10427:     }
                   10428: }
                   10429: 
1.575     albertel 10430: sub rndseed_CODE_64bit4 {
                   10431:     my ($symb,$courseid,$domain,$username)=@_;
                   10432:     {
                   10433: 	use integer;
                   10434: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10435: 	my $symbseed=numval3($symb);
                   10436: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10437: 	my $CODEseed=numval3(&getCODE());
                   10438: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10439: 	my $num1=$symbseed+$CODEchck;
                   10440: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10441: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10442: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10443: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10444: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10445: 	return "$num1:$num2";
                   10446:     }
                   10447: }
                   10448: 
1.675     albertel 10449: sub rndseed_CODE_64bit5 {
                   10450:     my ($symb,$courseid,$domain,$username)=@_;
                   10451:     my $code = &getCODE();
                   10452:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10453:     return "$num1:$num2";
                   10454: }
                   10455: 
1.366     albertel 10456: sub setup_random_from_rndseed {
                   10457:     my ($rndseed)=@_;
1.503     albertel 10458:     if ($rndseed =~/([,:])/) {
                   10459: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10460: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10461:     } else {
                   10462: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10463:     }
1.36      albertel 10464: }
                   10465: 
1.474     albertel 10466: sub latest_receipt_algorithm_id {
1.835     albertel 10467:     return 'receipt3';
1.474     albertel 10468: }
                   10469: 
1.480     www      10470: sub recunique {
                   10471:     my $fucourseid=shift;
                   10472:     my $unique;
1.835     albertel 10473:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10474: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10475: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10476:     } else {
                   10477: 	$unique=$perlvar{'lonReceipt'};
                   10478:     }
                   10479:     return unpack("%32C*",$unique);
                   10480: }
                   10481: 
                   10482: sub recprefix {
                   10483:     my $fucourseid=shift;
                   10484:     my $prefix;
1.835     albertel 10485:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10486: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10487: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10488:     } else {
                   10489: 	$prefix=$perlvar{'lonHostID'};
                   10490:     }
                   10491:     return unpack("%32C*",$prefix);
                   10492: }
                   10493: 
1.76      www      10494: sub ireceipt {
1.474     albertel 10495:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10496: 
                   10497:     my $return =&recprefix($fucourseid).'-';
                   10498: 
                   10499:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10500: 	$env{'request.state'} eq 'construct') {
                   10501: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10502: 	return $return;
                   10503:     }
                   10504: 
1.76      www      10505:     my $cuname=unpack("%32C*",$funame);
                   10506:     my $cudom=unpack("%32C*",$fudom);
                   10507:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10508:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10509:     my $cunique=&recunique($fucourseid);
1.474     albertel 10510:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10511:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10512: 
1.790     albertel 10513: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10514: 			       
                   10515: 	$return.= ($cunique%$cuname+
                   10516: 		   $cunique%$cudom+
                   10517: 		   $cusymb%$cuname+
                   10518: 		   $cusymb%$cudom+
                   10519: 		   $cucourseid%$cuname+
                   10520: 		   $cucourseid%$cudom+
                   10521: 		   $cpart%$cuname+
                   10522: 		   $cpart%$cudom);
                   10523:     } else {
                   10524: 	$return.= ($cunique%$cuname+
                   10525: 		   $cunique%$cudom+
                   10526: 		   $cusymb%$cuname+
                   10527: 		   $cusymb%$cudom+
                   10528: 		   $cucourseid%$cuname+
                   10529: 		   $cucourseid%$cudom);
                   10530:     }
                   10531:     return $return;
1.76      www      10532: }
                   10533: 
                   10534: sub receipt {
1.474     albertel 10535:     my ($part)=@_;
1.790     albertel 10536:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10537:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10538: }
1.260     ng       10539: 
1.790     albertel 10540: sub whichuser {
                   10541:     my ($passedsymb)=@_;
                   10542:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10543:     if (defined($env{'form.grade_symb'})) {
                   10544: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10545: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10546: 	if (!$allowed &&
                   10547: 	    exists($env{'request.course.sec'}) &&
                   10548: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10549: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10550: 			      '/'.$env{'request.course.sec'});
                   10551: 	}
                   10552: 	if ($allowed) {
                   10553: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10554: 	    $courseid=$tmp_courseid;
                   10555: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10556: 	    ($name)=&get_env_multiple('form.grade_username');
                   10557: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10558: 	}
                   10559:     }
                   10560:     if (!$passedsymb) {
                   10561: 	$symb=&symbread();
                   10562:     } else {
                   10563: 	$symb=$passedsymb;
                   10564:     }
                   10565:     $courseid=$env{'request.course.id'};
                   10566:     $domain=$env{'user.domain'};
                   10567:     $name=$env{'user.name'};
                   10568:     if ($name eq 'public' && $domain eq 'public') {
                   10569: 	if (!defined($env{'form.username'})) {
                   10570: 	    $env{'form.username'}.=time.rand(10000000);
                   10571: 	}
                   10572: 	$name.=$env{'form.username'};
                   10573:     }
                   10574:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10575: 
                   10576: }
                   10577: 
1.36      albertel 10578: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10579: # returns either the contents of the file or 
                   10580: # -1 if the file doesn't exist
1.481     raeburn  10581: #
                   10582: # if the target is a file that was uploaded via DOCS, 
                   10583: # a check will be made to see if a current copy exists on the local server,
                   10584: # if it does this will be served, otherwise a copy will be retrieved from
                   10585: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10586: # the local server.   
1.472     albertel 10587: 
1.36      albertel 10588: sub getfile {
1.538     albertel 10589:     my ($file) = @_;
1.609     banghart 10590:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10591:     &repcopy($file);
                   10592:     return &readfile($file);
                   10593: }
                   10594: 
                   10595: sub repcopy_userfile {
                   10596:     my ($file)=@_;
1.1142    raeburn  10597:     my $londocroot = $perlvar{'lonDocRoot'};
                   10598:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10599:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10600:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10601: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10602:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10603:     if (-e "$file") {
1.828     www      10604: # we already have a local copy, check it out
1.538     albertel 10605: 	my @fileinfo = stat($file);
1.828     www      10606: 	my $rtncode;
                   10607: 	my $info;
1.538     albertel 10608: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10609: 	if ($lwpresp ne 'ok') {
1.828     www      10610: # there is no such file anymore, even though we had a local copy
1.482     albertel 10611: 	    if ($rtncode eq '404') {
1.538     albertel 10612: 		unlink($file);
1.482     albertel 10613: 	    }
                   10614: 	    return -1;
                   10615: 	}
                   10616: 	if ($info < $fileinfo[9]) {
1.828     www      10617: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10618: 	    return 'ok';
1.828     www      10619: 	} else {
                   10620: # the file is outdated, get rid of it
                   10621: 	    unlink($file);
1.482     albertel 10622: 	}
1.828     www      10623:     }
                   10624: # one way or the other, at this point, we don't have the file
                   10625: # construct the correct path for the file
                   10626:     my @parts = ($cdom,$cnum); 
                   10627:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10628: 	push @parts, split(/\//,$1);
                   10629:     }
                   10630:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10631:     foreach my $part (@parts) {
                   10632: 	$path .= '/'.$part;
                   10633: 	if (!-e $path) {
                   10634: 	    mkdir($path,0770);
1.482     albertel 10635: 	}
                   10636:     }
1.828     www      10637: # now the path exists for sure
                   10638: # get a user agent
                   10639:     my $ua=new LWP::UserAgent;
                   10640:     my $transferfile=$file.'.in.transfer';
                   10641: # FIXME: this should flock
                   10642:     if (-e $transferfile) { return 'ok'; }
                   10643:     my $request;
                   10644:     $uri=~s/^\///;
1.980     raeburn  10645:     my $homeserver = &homeserver($cnum,$cdom);
                   10646:     my $protocol = $protocol{$homeserver};
                   10647:     $protocol = 'http' if ($protocol ne 'https');
                   10648:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10649:     my $response=$ua->request($request,$transferfile);
                   10650: # did it work?
                   10651:     if ($response->is_error()) {
                   10652: 	unlink($transferfile);
                   10653: 	&logthis("Userfile repcopy failed for $uri");
                   10654: 	return -1;
                   10655:     }
                   10656: # worked, rename the transfer file
                   10657:     rename($transferfile,$file);
1.607     raeburn  10658:     return 'ok';
1.481     raeburn  10659: }
                   10660: 
1.517     albertel 10661: sub tokenwrapper {
                   10662:     my $uri=shift;
1.980     raeburn  10663:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10664:     $uri=~s|^/||;
1.620     albertel 10665:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10666:     my $token=$1;
1.552     albertel 10667:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10668:     if ($udom && $uname && $file) {
                   10669: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10670:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10671:         my $homeserver = &homeserver($uname,$udom);
                   10672:         my $protocol = $protocol{$homeserver};
                   10673:         $protocol = 'http' if ($protocol ne 'https');
                   10674:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10675:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10676:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10677:     } else {
                   10678:         return '/adm/notfound.html';
                   10679:     }
                   10680: }
                   10681: 
1.828     www      10682: # call with reqtype HEAD: get last modification time
                   10683: # call with reqtype GET: get the file contents
                   10684: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10685: #
1.481     raeburn  10686: sub getuploaded {
                   10687:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10688:     $uri=~s/^\///;
1.980     raeburn  10689:     my $homeserver = &homeserver($cnum,$cdom);
                   10690:     my $protocol = $protocol{$homeserver};
                   10691:     $protocol = 'http' if ($protocol ne 'https');
                   10692:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10693:     my $ua=new LWP::UserAgent;
                   10694:     my $request=new HTTP::Request($reqtype,$uri);
                   10695:     my $response=$ua->request($request);
                   10696:     $$rtncode = $response->code;
1.482     albertel 10697:     if (! $response->is_success()) {
                   10698: 	return 'failed';
                   10699:     }      
                   10700:     if ($reqtype eq 'HEAD') {
1.486     www      10701: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10702:     } elsif ($reqtype eq 'GET') {
                   10703: 	$$info = $response->content;
1.472     albertel 10704:     }
1.482     albertel 10705:     return 'ok';
1.36      albertel 10706: }
                   10707: 
1.481     raeburn  10708: sub readfile {
                   10709:     my $file = shift;
                   10710:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10711:     my $fh;
                   10712:     open($fh,"<$file");
                   10713:     my $a='';
1.800     albertel 10714:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10715:     return $a;
                   10716: }
                   10717: 
1.36      albertel 10718: sub filelocation {
1.590     banghart 10719:     my ($dir,$file) = @_;
                   10720:     my $location;
                   10721:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10722: 
                   10723:     if ($file =~ m-^/adm/-) {
                   10724: 	$file=~s-^/adm/wrapper/-/-;
                   10725: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10726:     }
1.882     albertel 10727: 
1.1139    www      10728:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10729:         $location = $file;
1.609     banghart 10730:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10731:         my ($udom,$uname,$filename)=
1.811     albertel 10732:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10733:         my $home=&homeserver($uname,$udom);
                   10734:         my $is_me=0;
                   10735:         my @ids=&current_machine_ids();
                   10736:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10737:         if ($is_me) {
1.1117    foxr     10738:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10739:         } else {
                   10740:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10741:   	      $udom.'/'.$uname.'/'.$filename;
                   10742:         }
1.882     albertel 10743:     } elsif ($file =~ m-^/adm/-) {
                   10744: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10745:     } else {
                   10746:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10747:         $file=~s:^/(res|priv)/:/:;
                   10748:         my $space=$1;
1.590     banghart 10749:         if ( !( $file =~ m:^/:) ) {
                   10750:             $location = $dir. '/'.$file;
                   10751:         } else {
1.1142    raeburn  10752:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10753:         }
1.59      albertel 10754:     }
1.590     banghart 10755:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10756:     while ($location=~m{/\.\./}) {
                   10757: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10758: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10759: 	} else {
                   10760: 	    $location=~ s{/\.\./}{/}g;
                   10761: 	}
                   10762:     } #remove dir/..
1.590     banghart 10763:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10764:     return $location;
1.46      www      10765: }
1.36      albertel 10766: 
1.46      www      10767: sub hreflocation {
                   10768:     my ($dir,$file)=@_;
1.980     raeburn  10769:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10770: 	$file=filelocation($dir,$file);
1.700     albertel 10771:     } elsif ($file=~m-^/adm/-) {
                   10772: 	$file=~s-^/adm/wrapper/-/-;
                   10773: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10774:     }
                   10775:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10776: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10777:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10778: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10779: 	        {/uploaded/$1/$2/}x;
1.46      www      10780:     }
1.913     albertel 10781:     if ($file=~ m{^/userfiles/}) {
                   10782: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10783:     }
1.462     albertel 10784:     return $file;
1.465     albertel 10785: }
                   10786: 
1.1139    www      10787: 
                   10788: 
                   10789: 
                   10790: 
1.465     albertel 10791: sub current_machine_domains {
1.853     albertel 10792:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10793: }
                   10794: 
                   10795: sub machine_domains {
                   10796:     my ($hostname) = @_;
1.465     albertel 10797:     my @domains;
1.838     albertel 10798:     my %hostname = &all_hostnames();
1.465     albertel 10799:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10800: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10801: 	if ($hostname eq $name) {
1.844     albertel 10802: 	    push(@domains,&host_domain($id));
1.465     albertel 10803: 	}
                   10804:     }
                   10805:     return @domains;
                   10806: }
                   10807: 
                   10808: sub current_machine_ids {
1.853     albertel 10809:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10810: }
                   10811: 
                   10812: sub machine_ids {
                   10813:     my ($hostname) = @_;
                   10814:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10815:     my @ids;
1.888     albertel 10816:     my %name_to_host = &all_names();
1.889     albertel 10817:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10818: 	return @{ $name_to_host{$hostname} };
                   10819:     }
                   10820:     return;
1.31      www      10821: }
                   10822: 
1.824     raeburn  10823: sub additional_machine_domains {
                   10824:     my @domains;
                   10825:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10826:     while( my $line = <$fh>) {
                   10827:         $line =~ s/\s//g;
                   10828:         push(@domains,$line);
                   10829:     }
                   10830:     return @domains;
                   10831: }
                   10832: 
                   10833: sub default_login_domain {
                   10834:     my $domain = $perlvar{'lonDefDomain'};
                   10835:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10836:     foreach my $posdom (&current_machine_domains(),
                   10837:                         &additional_machine_domains()) {
                   10838:         if (lc($posdom) eq lc($testdomain)) {
                   10839:             $domain=$posdom;
                   10840:             last;
                   10841:         }
                   10842:     }
                   10843:     return $domain;
                   10844: }
                   10845: 
1.31      www      10846: # ------------------------------------------------------------- Declutters URLs
                   10847: 
                   10848: sub declutter {
                   10849:     my $thisfn=shift;
1.569     albertel 10850:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10851:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10852:     $thisfn=~s/^\///;
1.697     albertel 10853:     $thisfn=~s|^adm/wrapper/||;
                   10854:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10855:     $thisfn=~s/^res\///;
1.1172    bisitz   10856:     $thisfn=~s/^priv\///;
1.1032    raeburn  10857:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10858:         $thisfn=~s/\?.+$//;
                   10859:     }
1.268     www      10860:     return $thisfn;
                   10861: }
                   10862: 
                   10863: # ------------------------------------------------------------- Clutter up URLs
                   10864: 
                   10865: sub clutter {
                   10866:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10867:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10868: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10869:        $thisfn='/res'.$thisfn; 
                   10870:     }
1.1031    raeburn  10871:     if ($thisfn !~m|^/adm|) {
                   10872: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10873: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10874: 	} else {
                   10875: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10876: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10877: 	    if ($embstyle eq 'ssi'
                   10878: 		|| ($embstyle eq 'hdn')
                   10879: 		|| ($embstyle eq 'rat')
                   10880: 		|| ($embstyle eq 'prv')
                   10881: 		|| ($embstyle eq 'ign')) {
                   10882: 		#do nothing with these
                   10883: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10884: 		|| ($embstyle eq 'emb')
                   10885: 		|| ($embstyle eq 'wrp')) {
                   10886: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10887: 	    } elsif ($embstyle eq 'unk'
                   10888: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10889: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10890: 	    } else {
1.718     www      10891: #		&logthis("Got a blank emb style");
1.695     albertel 10892: 	    }
1.694     albertel 10893: 	}
                   10894:     }
1.31      www      10895:     return $thisfn;
1.12      www      10896: }
                   10897: 
1.787     albertel 10898: sub clutter_with_no_wrapper {
                   10899:     my $uri = &clutter(shift);
                   10900:     if ($uri =~ m-^/adm/-) {
                   10901: 	$uri =~ s-^/adm/wrapper/-/-;
                   10902: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10903:     }
                   10904:     return $uri;
                   10905: }
                   10906: 
1.557     albertel 10907: sub freeze_escape {
                   10908:     my ($value)=@_;
                   10909:     if (ref($value)) {
                   10910: 	$value=&nfreeze($value);
                   10911: 	return '__FROZEN__'.&escape($value);
                   10912:     }
                   10913:     return &escape($value);
                   10914: }
                   10915: 
1.11      www      10916: 
1.557     albertel 10917: sub thaw_unescape {
                   10918:     my ($value)=@_;
                   10919:     if ($value =~ /^__FROZEN__/) {
                   10920: 	substr($value,0,10,undef);
                   10921: 	$value=&unescape($value);
                   10922: 	return &thaw($value);
                   10923:     }
                   10924:     return &unescape($value);
                   10925: }
                   10926: 
1.436     albertel 10927: sub correct_line_ends {
                   10928:     my ($result)=@_;
                   10929:     $$result =~s/\r\n/\n/mg;
                   10930:     $$result =~s/\r/\n/mg;
1.415     albertel 10931: }
1.1       albertel 10932: # ================================================================ Main Program
                   10933: 
1.184     www      10934: sub goodbye {
1.204     albertel 10935:    &logthis("Starting Shut down");
1.443     albertel 10936: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10937:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10938: #converted
1.599     albertel 10939: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10940:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10941: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10942: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10943: #1.1 only
1.870     albertel 10944: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10945: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10946: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10947: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10948:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10949:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10950:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10951:    &flushcourselogs();
                   10952:    &logthis("Shutting down");
                   10953: }
                   10954: 
1.852     albertel 10955: sub get_dns {
1.869     albertel 10956:     my ($url,$func,$ignore_cache) = @_;
                   10957:     if (!$ignore_cache) {
                   10958: 	my ($content,$cached)=
                   10959: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10960: 	if ($cached) {
                   10961: 	    &$func($content);
                   10962: 	    return;
                   10963: 	}
                   10964:     }
                   10965: 
                   10966:     my %alldns;
1.852     albertel 10967:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10968:     foreach my $dns (<$config>) {
                   10969: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10970:         my $line = $1;
                   10971:         my ($host,$protocol) = split(/:/,$line);
                   10972:         if ($protocol ne 'https') {
                   10973:             $protocol = 'http';
                   10974:         }
                   10975: 	$alldns{$host} = $protocol;
1.869     albertel 10976:     }
                   10977:     while (%alldns) {
                   10978: 	my ($dns) = keys(%alldns);
1.852     albertel 10979: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10980:         $ua->timeout(30);
1.979     raeburn  10981: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10982: 	my $response=$ua->request($request);
1.979     raeburn  10983:         delete($alldns{$dns});
1.852     albertel 10984: 	next if ($response->is_error());
                   10985: 	my @content = split("\n",$response->content);
1.869     albertel 10986: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10987: 	&$func(\@content);
1.869     albertel 10988: 	return;
1.852     albertel 10989:     }
                   10990:     close($config);
1.871     albertel 10991:     my $which = (split('/',$url))[3];
                   10992:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10993:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10994:     my @content = <$config>;
                   10995:     &$func(\@content);
                   10996:     return;
1.852     albertel 10997: }
1.327     albertel 10998: # ------------------------------------------------------------ Read domain file
                   10999: {
1.852     albertel 11000:     my $loaded;
1.846     albertel 11001:     my %domain;
                   11002: 
1.852     albertel 11003:     sub parse_domain_tab {
                   11004: 	my ($lines) = @_;
                   11005: 	foreach my $line (@$lines) {
                   11006: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11007: 
1.846     albertel 11008: 	    chomp($line);
1.852     albertel 11009: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11010: 	    my %this_domain;
                   11011: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11012: 			       'lang_def', 'city', 'longi', 'lati',
                   11013: 			       'primary') {
                   11014: 		$this_domain{$field} = shift(@elements);
                   11015: 	    }
                   11016: 	    $domain{$name} = \%this_domain;
1.852     albertel 11017: 	}
                   11018:     }
1.864     albertel 11019: 
                   11020:     sub reset_domain_info {
                   11021: 	undef($loaded);
                   11022: 	undef(%domain);
                   11023:     }
                   11024: 
1.852     albertel 11025:     sub load_domain_tab {
1.869     albertel 11026: 	my ($ignore_cache) = @_;
                   11027: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11028: 	my $fh;
                   11029: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11030: 	    my @lines = <$fh>;
                   11031: 	    &parse_domain_tab(\@lines);
1.448     albertel 11032: 	}
1.852     albertel 11033: 	close($fh);
                   11034: 	$loaded = 1;
1.327     albertel 11035:     }
1.846     albertel 11036: 
                   11037:     sub domain {
1.852     albertel 11038: 	&load_domain_tab() if (!$loaded);
                   11039: 
1.846     albertel 11040: 	my ($name,$what) = @_;
                   11041: 	return if ( !exists($domain{$name}) );
                   11042: 
                   11043: 	if (!$what) {
                   11044: 	    return $domain{$name}{'description'};
                   11045: 	}
                   11046: 	return $domain{$name}{$what};
                   11047:     }
1.974     raeburn  11048: 
                   11049:     sub domain_info {
                   11050:         &load_domain_tab() if (!$loaded);
                   11051:         return %domain;
                   11052:     }
                   11053: 
1.327     albertel 11054: }
                   11055: 
                   11056: 
1.1       albertel 11057: # ------------------------------------------------------------- Read hosts file
                   11058: {
1.838     albertel 11059:     my %hostname;
1.844     albertel 11060:     my %hostdom;
1.845     albertel 11061:     my %libserv;
1.852     albertel 11062:     my $loaded;
1.888     albertel 11063:     my %name_to_host;
1.1074    raeburn  11064:     my %internetdom;
1.1107    raeburn  11065:     my %LC_dns_serv;
1.852     albertel 11066: 
                   11067:     sub parse_hosts_tab {
                   11068: 	my ($file) = @_;
                   11069: 	foreach my $configline (@$file) {
                   11070: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11071:             chomp($configline);
                   11072: 	    if ($configline =~ /^\^/) {
                   11073:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11074:                     $LC_dns_serv{$1} = 1;
                   11075:                 }
                   11076:                 next;
                   11077:             }
1.1074    raeburn  11078: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11079: 	    $name=~s/\s//g;
                   11080: 	    if ($id && $domain && $role && $name) {
                   11081: 		$hostname{$id}=$name;
1.888     albertel 11082: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11083: 		$hostdom{$id}=$domain;
                   11084: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11085:                 if (defined($protocol)) {
                   11086:                     if ($protocol eq 'https') {
                   11087:                         $protocol{$id} = $protocol;
                   11088:                     } else {
                   11089:                         $protocol{$id} = 'http'; 
                   11090:                     }
1.968     raeburn  11091:                 } else {
1.969     raeburn  11092:                     $protocol{$id} = 'http';
1.968     raeburn  11093:                 }
1.1074    raeburn  11094:                 if (defined($intdom)) {
                   11095:                     $internetdom{$id} = $intdom;
                   11096:                 }
1.852     albertel 11097: 	    }
                   11098: 	}
                   11099:     }
1.864     albertel 11100:     
                   11101:     sub reset_hosts_info {
1.897     albertel 11102: 	&purge_remembered();
1.864     albertel 11103: 	&reset_domain_info();
                   11104: 	&reset_hosts_ip_info();
1.892     albertel 11105: 	undef(%name_to_host);
1.864     albertel 11106: 	undef(%hostname);
                   11107: 	undef(%hostdom);
                   11108: 	undef(%libserv);
                   11109: 	undef($loaded);
                   11110:     }
1.1       albertel 11111: 
1.852     albertel 11112:     sub load_hosts_tab {
1.869     albertel 11113: 	my ($ignore_cache) = @_;
                   11114: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11115: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11116: 	my @config = <$config>;
                   11117: 	&parse_hosts_tab(\@config);
                   11118: 	close($config);
                   11119: 	$loaded=1;
1.1       albertel 11120:     }
1.852     albertel 11121: 
1.838     albertel 11122:     sub hostname {
1.852     albertel 11123: 	&load_hosts_tab() if (!$loaded);
                   11124: 
1.838     albertel 11125: 	my ($lonid) = @_;
                   11126: 	return $hostname{$lonid};
                   11127:     }
1.845     albertel 11128: 
1.838     albertel 11129:     sub all_hostnames {
1.852     albertel 11130: 	&load_hosts_tab() if (!$loaded);
                   11131: 
1.838     albertel 11132: 	return %hostname;
                   11133:     }
1.845     albertel 11134: 
1.888     albertel 11135:     sub all_names {
                   11136: 	&load_hosts_tab() if (!$loaded);
                   11137: 
                   11138: 	return %name_to_host;
                   11139:     }
                   11140: 
1.974     raeburn  11141:     sub all_host_domain {
                   11142:         &load_hosts_tab() if (!$loaded);
                   11143:         return %hostdom;
                   11144:     }
                   11145: 
1.845     albertel 11146:     sub is_library {
1.852     albertel 11147: 	&load_hosts_tab() if (!$loaded);
                   11148: 
1.845     albertel 11149: 	return exists($libserv{$_[0]});
                   11150:     }
                   11151: 
                   11152:     sub all_library {
1.852     albertel 11153: 	&load_hosts_tab() if (!$loaded);
                   11154: 
1.845     albertel 11155: 	return %libserv;
                   11156:     }
                   11157: 
1.1062    droeschl 11158:     sub unique_library {
                   11159: 	#2x reverse removes all hostnames that appear more than once
                   11160:         my %unique = reverse &all_library();
                   11161:         return reverse %unique;
                   11162:     }
                   11163: 
1.841     albertel 11164:     sub get_servers {
1.852     albertel 11165: 	&load_hosts_tab() if (!$loaded);
                   11166: 
1.841     albertel 11167: 	my ($domain,$type) = @_;
                   11168: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11169: 	                                          : %hostname;
                   11170: 	my %result;
1.842     albertel 11171: 	if (ref($domain) eq 'ARRAY') {
                   11172: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11173: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11174: 		    $result{$host} = $hostname;
                   11175: 		}
                   11176: 	    }
                   11177: 	} else {
                   11178: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11179: 		if ($hostdom{$host} eq $domain) {
                   11180: 		    $result{$host} = $hostname;
                   11181: 		}
1.841     albertel 11182: 	    }
                   11183: 	}
                   11184: 	return %result;
                   11185:     }
1.845     albertel 11186: 
1.1062    droeschl 11187:     sub get_unique_servers {
                   11188:         my %unique = reverse &get_servers(@_);
                   11189: 	return reverse %unique;
                   11190:     }
                   11191: 
1.844     albertel 11192:     sub host_domain {
1.852     albertel 11193: 	&load_hosts_tab() if (!$loaded);
                   11194: 
1.844     albertel 11195: 	my ($lonid) = @_;
                   11196: 	return $hostdom{$lonid};
                   11197:     }
                   11198: 
1.841     albertel 11199:     sub all_domains {
1.852     albertel 11200: 	&load_hosts_tab() if (!$loaded);
                   11201: 
1.841     albertel 11202: 	my %seen;
                   11203: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11204: 	return @uniq;
                   11205:     }
1.1074    raeburn  11206: 
                   11207:     sub internet_dom {
                   11208:         &load_hosts_tab() if (!$loaded);
                   11209: 
                   11210:         my ($lonid) = @_;
                   11211:         return $internetdom{$lonid};
                   11212:     }
1.1107    raeburn  11213: 
                   11214:     sub is_LC_dns {
                   11215:         &load_hosts_tab() if (!$loaded);
                   11216: 
                   11217:         my ($hostname) = @_;
                   11218:         return exists($LC_dns_serv{$hostname});
                   11219:     }
                   11220: 
1.1       albertel 11221: }
                   11222: 
1.847     albertel 11223: { 
                   11224:     my %iphost;
1.856     albertel 11225:     my %name_to_ip;
                   11226:     my %lonid_to_ip;
1.869     albertel 11227: 
1.847     albertel 11228:     sub get_hosts_from_ip {
                   11229: 	my ($ip) = @_;
                   11230: 	my %iphosts = &get_iphost();
                   11231: 	if (ref($iphosts{$ip})) {
                   11232: 	    return @{$iphosts{$ip}};
                   11233: 	}
                   11234: 	return;
1.839     albertel 11235:     }
1.864     albertel 11236:     
                   11237:     sub reset_hosts_ip_info {
                   11238: 	undef(%iphost);
                   11239: 	undef(%name_to_ip);
                   11240: 	undef(%lonid_to_ip);
                   11241:     }
1.856     albertel 11242: 
                   11243:     sub get_host_ip {
                   11244: 	my ($lonid) = @_;
                   11245: 	if (exists($lonid_to_ip{$lonid})) {
                   11246: 	    return $lonid_to_ip{$lonid};
                   11247: 	}
                   11248: 	my $name=&hostname($lonid);
                   11249:    	my $ip = gethostbyname($name);
                   11250: 	return if (!$ip || length($ip) ne 4);
                   11251: 	$ip=inet_ntoa($ip);
                   11252: 	$name_to_ip{$name}   = $ip;
                   11253: 	$lonid_to_ip{$lonid} = $ip;
                   11254: 	return $ip;
                   11255:     }
1.847     albertel 11256:     
                   11257:     sub get_iphost {
1.869     albertel 11258: 	my ($ignore_cache) = @_;
1.894     albertel 11259: 
1.869     albertel 11260: 	if (!$ignore_cache) {
                   11261: 	    if (%iphost) {
                   11262: 		return %iphost;
                   11263: 	    }
                   11264: 	    my ($ip_info,$cached)=
                   11265: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11266: 	    if ($cached) {
                   11267: 		%iphost      = %{$ip_info->[0]};
                   11268: 		%name_to_ip  = %{$ip_info->[1]};
                   11269: 		%lonid_to_ip = %{$ip_info->[2]};
                   11270: 		return %iphost;
                   11271: 	    }
                   11272: 	}
1.894     albertel 11273: 
                   11274: 	# get yesterday's info for fallback
                   11275: 	my %old_name_to_ip;
                   11276: 	my ($ip_info,$cached)=
                   11277: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11278: 	if ($cached) {
                   11279: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11280: 	}
                   11281: 
1.888     albertel 11282: 	my %name_to_host = &all_names();
                   11283: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11284: 	    my $ip;
                   11285: 	    if (!exists($name_to_ip{$name})) {
                   11286: 		$ip = gethostbyname($name);
                   11287: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11288: 		    if (defined($old_name_to_ip{$name})) {
                   11289: 			$ip = $old_name_to_ip{$name};
                   11290: 			&logthis("Can't find $name defaulting to old $ip");
                   11291: 		    } else {
                   11292: 			&logthis("Name $name no IP found");
                   11293: 			next;
                   11294: 		    }
                   11295: 		} else {
                   11296: 		    $ip=inet_ntoa($ip);
1.847     albertel 11297: 		}
                   11298: 		$name_to_ip{$name} = $ip;
                   11299: 	    } else {
                   11300: 		$ip = $name_to_ip{$name};
1.653     albertel 11301: 	    }
1.888     albertel 11302: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11303: 		$lonid_to_ip{$id} = $ip;
                   11304: 	    }
                   11305: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11306: 	}
1.869     albertel 11307: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11308: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11309: 				      48*60*60);
1.869     albertel 11310: 
1.847     albertel 11311: 	return %iphost;
1.598     albertel 11312:     }
                   11313: 
1.992     raeburn  11314:     #
                   11315:     #  Given a DNS returns the loncapa host name for that DNS 
                   11316:     # 
                   11317:     sub host_from_dns {
                   11318:         my ($dns) = @_;
                   11319:         my @hosts;
                   11320:         my $ip;
                   11321: 
1.993     raeburn  11322:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11323:             $ip = $name_to_ip{$dns};
                   11324:         }
                   11325:         if (!$ip) {
                   11326:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11327:             if (length($ip) == 4) { 
                   11328: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11329:             }
                   11330:         }
                   11331:         if ($ip) {
                   11332: 	    @hosts = get_hosts_from_ip($ip);
                   11333: 	    return $hosts[0];
                   11334:         }
                   11335:         return undef;
1.986     foxr     11336:     }
1.992     raeburn  11337: 
1.1074    raeburn  11338:     sub get_internet_names {
                   11339:         my ($lonid) = @_;
                   11340:         return if ($lonid eq '');
                   11341:         my ($idnref,$cached)=
                   11342:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11343:         if ($cached) {
                   11344:             return $idnref;
                   11345:         }
                   11346:         my $ip = &get_host_ip($lonid);
                   11347:         my @hosts = &get_hosts_from_ip($ip);
                   11348:         my %iphost = &get_iphost();
                   11349:         my (@idns,%seen);
                   11350:         foreach my $id (@hosts) {
                   11351:             my $dom = &host_domain($id);
                   11352:             my $prim_id = &domain($dom,'primary');
                   11353:             my $prim_ip = &get_host_ip($prim_id);
                   11354:             next if ($seen{$prim_ip});
                   11355:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11356:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11357:                     my $intdom = &internet_dom($id);
                   11358:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11359:                         push(@idns,$intdom);
                   11360:                     }
                   11361:                 }
                   11362:             }
                   11363:             $seen{$prim_ip} = 1;
                   11364:         }
                   11365:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11366:     }
                   11367: 
1.986     foxr     11368: }
                   11369: 
1.1079    raeburn  11370: sub all_loncaparevs {
                   11371:     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);
                   11372: }
                   11373: 
1.862     albertel 11374: BEGIN {
                   11375: 
                   11376: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11377:     unless ($readit) {
                   11378: {
                   11379:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11380:     %perlvar = (%perlvar,%{$configvars});
                   11381: }
                   11382: 
                   11383: 
1.1       albertel 11384: # ------------------------------------------------------ Read spare server file
                   11385: {
1.448     albertel 11386:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11387: 
                   11388:     while (my $configline=<$config>) {
                   11389:        chomp($configline);
1.284     matthew  11390:        if ($configline) {
1.784     albertel 11391: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11392: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11393: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11394:        }
                   11395:     }
1.448     albertel 11396:     close($config);
1.1       albertel 11397: }
1.11      www      11398: # ------------------------------------------------------------ Read permissions
                   11399: {
1.448     albertel 11400:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11401: 
                   11402:     while (my $configline=<$config>) {
1.448     albertel 11403: 	chomp($configline);
                   11404: 	if ($configline) {
                   11405: 	    my ($role,$perm)=split(/ /,$configline);
                   11406: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11407: 	}
1.11      www      11408:     }
1.448     albertel 11409:     close($config);
1.11      www      11410: }
                   11411: 
                   11412: # -------------------------------------------- Read plain texts for permissions
                   11413: {
1.448     albertel 11414:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11415: 
                   11416:     while (my $configline=<$config>) {
1.448     albertel 11417: 	chomp($configline);
                   11418: 	if ($configline) {
1.742     raeburn  11419: 	    my ($short,@plain)=split(/:/,$configline);
                   11420:             %{$prp{$short}} = ();
                   11421: 	    if (@plain > 0) {
                   11422:                 $prp{$short}{'std'} = $plain[0];
                   11423:                 for (my $i=1; $i<@plain; $i++) {
                   11424:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11425:                 }
                   11426:             }
1.448     albertel 11427: 	}
1.135     www      11428:     }
1.448     albertel 11429:     close($config);
1.135     www      11430: }
                   11431: 
                   11432: # ---------------------------------------------------------- Read package table
                   11433: {
1.448     albertel 11434:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11435: 
                   11436:     while (my $configline=<$config>) {
1.483     albertel 11437: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11438: 	chomp($configline);
                   11439: 	my ($short,$plain)=split(/:/,$configline);
                   11440: 	my ($pack,$name)=split(/\&/,$short);
                   11441: 	if ($plain ne '') {
                   11442: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11443: 	    $packagetab{$short}=$plain; 
                   11444: 	}
1.11      www      11445:     }
1.448     albertel 11446:     close($config);
1.329     matthew  11447: }
                   11448: 
1.1073    raeburn  11449: # ---------------------------------------------------------- Read loncaparev table
                   11450: {
                   11451:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11452:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11453:             while (my $configline=<$config>) {
                   11454:                 chomp($configline);
                   11455:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11456:                 $loncaparevs{$hostid}=$loncaparev;
                   11457:             }
                   11458:             close($config);
                   11459:         }
                   11460:     }
                   11461: }
                   11462: 
1.1074    raeburn  11463: # ---------------------------------------------------------- Read serverhostID table
                   11464: {
                   11465:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11466:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11467:             while (my $configline=<$config>) {
                   11468:                 chomp($configline);
                   11469:                 my ($name,$id)=split(/:/,$configline);
                   11470:                 $serverhomeIDs{$name}=$id;
                   11471:             }
                   11472:             close($config);
                   11473:         }
                   11474:     }
                   11475: }
                   11476: 
1.1079    raeburn  11477: {
                   11478:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11479:     if (-e $file) {
                   11480:         my $parser = HTML::LCParser->new($file);
                   11481:         while (my $token = $parser->get_token()) {
                   11482:             if ($token->[0] eq 'S') {
                   11483:                 my $item = $token->[1];
                   11484:                 my $name = $token->[2]{'name'};
                   11485:                 my $value = $token->[2]{'value'};
                   11486:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11487:                     my $release = $parser->get_text();
                   11488:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11489:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11490:                 }
                   11491:             }
                   11492:         }
                   11493:     }
1.1073    raeburn  11494: }
                   11495: 
1.1138    raeburn  11496: # ---------------------------------------------------------- Read managers table
                   11497: {
                   11498:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11499:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11500:             while (my $configline=<$config>) {
                   11501:                 chomp($configline);
                   11502:                 next if ($configline =~ /^\#/);
                   11503:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11504:                     $managerstab{$configline} = 1;
                   11505:                 }
                   11506:             }
                   11507:             close($config);
                   11508:         }
                   11509:     }
                   11510: }
                   11511: 
1.329     matthew  11512: # ------------- set up temporary directory
                   11513: {
1.1117    foxr     11514:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11515: 
1.11      www      11516: }
                   11517: 
1.794     albertel 11518: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11519: 				'compress_threshold'=> 20_000,
                   11520:  			        });
1.185     www      11521: 
1.281     www      11522: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11523: $dumpcount=0;
1.958     www      11524: $locknum=0;
1.22      www      11525: 
1.163     harris41 11526: &logtouch();
1.672     albertel 11527: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11528: $readit=1;
1.564     albertel 11529:     {
                   11530: 	use integer;
                   11531: 	my $test=(2**32)+1;
1.568     albertel 11532: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11533: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11534:     }
1.195     www      11535: }
1.1       albertel 11536: }
1.179     www      11537: 
1.1       albertel 11538: 1;
1.191     harris41 11539: __END__
                   11540: 
1.243     albertel 11541: =pod
                   11542: 
1.191     harris41 11543: =head1 NAME
                   11544: 
1.243     albertel 11545: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11546: 
                   11547: =head1 SYNOPSIS
                   11548: 
1.243     albertel 11549: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11550: 
                   11551:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11552: 
1.243     albertel 11553: Common parameters:
                   11554: 
                   11555: =over 4
                   11556: 
                   11557: =item *
                   11558: 
                   11559: $uname : an internal username (if $cname expecting a course Id specifically)
                   11560: 
                   11561: =item *
                   11562: 
                   11563: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11564: 
                   11565: =item *
                   11566: 
                   11567: $symb : a resource instance identifier
                   11568: 
                   11569: =item *
                   11570: 
                   11571: $namespace : the name of a .db file that contains the data needed or
                   11572: being set.
                   11573: 
                   11574: =back
                   11575: 
1.394     bowersj2 11576: =head1 OVERVIEW
1.191     harris41 11577: 
1.394     bowersj2 11578: lonnet provides subroutines which interact with the
                   11579: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11580: about classes, users, and resources.
1.243     albertel 11581: 
                   11582: For many of these objects you can also use this to store data about
                   11583: them or modify them in various ways.
1.191     harris41 11584: 
1.394     bowersj2 11585: =head2 Symbs
1.191     harris41 11586: 
1.394     bowersj2 11587: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11588: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11589: map, the resource number of the resource in the map, and the URL of
                   11590: the resource itself. The latter is somewhat redundant, but might help
                   11591: if maps change.
                   11592: 
                   11593: An example is
                   11594: 
                   11595:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11596: 
                   11597: The respective map entry is
                   11598: 
                   11599:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11600:   title="Problem 2">
                   11601:  </resource>
                   11602: 
                   11603: Symbs are used by the random number generator, as well as to store and
                   11604: restore data specific to a certain instance of for example a problem.
                   11605: 
                   11606: =head2 Storing And Retrieving Data
                   11607: 
                   11608: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11609: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11610: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11611: is is the non-critical message twin of cstore. These functions are for
                   11612: handlers to store a perl hash to a user's permanent data space in an
                   11613: easy manner, and to retrieve it again on another call. It is expected
                   11614: that a handler would use this once at the beginning to retrieve data,
                   11615: and then again once at the end to send only the new data back.
                   11616: 
                   11617: The data is stored in the user's data directory on the user's
                   11618: homeserver under the ID of the course.
                   11619: 
                   11620: The hash that is returned by restore will have all of the previous
                   11621: value for all of the elements of the hash.
                   11622: 
                   11623: Example:
                   11624: 
                   11625:  #creating a hash
                   11626:  my %hash;
                   11627:  $hash{'foo'}='bar';
                   11628: 
                   11629:  #storing it
                   11630:  &Apache::lonnet::cstore(\%hash);
                   11631: 
                   11632:  #changing a value
                   11633:  $hash{'foo'}='notbar';
                   11634: 
                   11635:  #adding a new value
                   11636:  $hash{'bar'}='foo';
                   11637:  &Apache::lonnet::cstore(\%hash);
                   11638: 
                   11639:  #retrieving the hash
                   11640:  my %history=&Apache::lonnet::restore();
                   11641: 
                   11642:  #print the hash
                   11643:  foreach my $key (sort(keys(%history))) {
                   11644:    print("\%history{$key} = $history{$key}");
                   11645:  }
                   11646: 
                   11647: Will print out:
1.191     harris41 11648: 
1.394     bowersj2 11649:  %history{1:foo} = bar
                   11650:  %history{1:keys} = foo:timestamp
                   11651:  %history{1:timestamp} = 990455579
                   11652:  %history{2:bar} = foo
                   11653:  %history{2:foo} = notbar
                   11654:  %history{2:keys} = foo:bar:timestamp
                   11655:  %history{2:timestamp} = 990455580
                   11656:  %history{bar} = foo
                   11657:  %history{foo} = notbar
                   11658:  %history{timestamp} = 990455580
                   11659:  %history{version} = 2
                   11660: 
                   11661: Note that the special hash entries C<keys>, C<version> and
                   11662: C<timestamp> were added to the hash. C<version> will be equal to the
                   11663: total number of versions of the data that have been stored. The
                   11664: C<timestamp> attribute will be the UNIX time the hash was
                   11665: stored. C<keys> is available in every historical section to list which
                   11666: keys were added or changed at a specific historical revision of a
                   11667: hash.
                   11668: 
                   11669: B<Warning>: do not store the hash that restore returns directly. This
                   11670: will cause a mess since it will restore the historical keys as if the
                   11671: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11672: 
1.394     bowersj2 11673: Calling convention:
1.191     harris41 11674: 
1.394     bowersj2 11675:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11676:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11677: 
1.394     bowersj2 11678: For more detailed information, see lonnet specific documentation.
1.191     harris41 11679: 
1.394     bowersj2 11680: =head1 RETURN MESSAGES
1.191     harris41 11681: 
1.394     bowersj2 11682: =over 4
1.191     harris41 11683: 
1.394     bowersj2 11684: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11685: 
1.394     bowersj2 11686: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11687: when the connection is brought back up
1.191     harris41 11688: 
1.394     bowersj2 11689: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11690: for later delivery
1.191     harris41 11691: 
1.967     bisitz   11692: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11693: 
1.394     bowersj2 11694: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11695: that was requested
1.191     harris41 11696: 
1.243     albertel 11697: =back
1.191     harris41 11698: 
1.243     albertel 11699: =head1 PUBLIC SUBROUTINES
1.191     harris41 11700: 
1.243     albertel 11701: =head2 Session Environment Functions
1.191     harris41 11702: 
1.243     albertel 11703: =over 4
1.191     harris41 11704: 
1.394     bowersj2 11705: =item * 
                   11706: X<appenv()>
1.949     raeburn  11707: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11708: the user envirnoment file, and will be restored for each access this
1.620     albertel 11709: user makes during this session, also modifies the %env for the current
1.949     raeburn  11710: process. Optional rolesarrayref - if defined contains a reference to an array
                   11711: of roles which are exempt from the restriction on modifying user.role entries 
                   11712: in the user's environment.db and in %env.    
1.191     harris41 11713: 
                   11714: =item *
1.394     bowersj2 11715: X<delenv()>
1.987     raeburn  11716: B<delenv($delthis,$regexp)>: removes all items from the session
                   11717: environment file that begin with $delthis. If the 
                   11718: optional second arg - $regexp - is true, $delthis is treated as a 
                   11719: regular expression, otherwise \Q$delthis\E is used. 
                   11720: The values are also deleted from the current processes %env.
1.191     harris41 11721: 
1.795     albertel 11722: =item * get_env_multiple($name) 
                   11723: 
                   11724: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11725: values may be defined and end up as an array ref.
                   11726: 
                   11727: returns an array of values
                   11728: 
1.243     albertel 11729: =back
                   11730: 
                   11731: =head2 User Information
1.191     harris41 11732: 
1.243     albertel 11733: =over 4
1.191     harris41 11734: 
                   11735: =item *
1.394     bowersj2 11736: X<queryauthenticate()>
                   11737: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11738: authentication scheme
                   11739: 
                   11740: =item *
1.394     bowersj2 11741: X<authenticate()>
1.1073    raeburn  11742: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11743: authenticate user from domain's lib servers (first use the current
                   11744: one). C<$upass> should be the users password.
1.1073    raeburn  11745: $checkdefauth is optional (value is 1 if a check should be made to
                   11746:    authenticate user using default authentication method, and allow
                   11747:    account creation if username does not have account in the domain).
                   11748: $clientcancheckhost is optional (value is 1 if checking whether the
                   11749:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11750: 
                   11751: =item *
1.394     bowersj2 11752: X<homeserver()>
                   11753: B<homeserver($uname,$udom)>: find the server which has
                   11754: the user's directory and files (there must be only one), this caches
                   11755: the answer, and also caches if there is a borken connection.
1.191     harris41 11756: 
                   11757: =item *
1.394     bowersj2 11758: X<idget()>
                   11759: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11760: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11761: username, and only 1 username per ID in a specific domain) (returns
                   11762: hash: id=>name,id=>name)
1.191     harris41 11763: 
                   11764: =item *
1.394     bowersj2 11765: X<idrget()>
                   11766: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11767: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11768: 
                   11769: =item *
1.394     bowersj2 11770: X<idput()>
                   11771: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11772: 
                   11773: =item *
1.394     bowersj2 11774: X<rolesinit()>
1.1169    droeschl 11775: B<rolesinit($udom,$username)>: get user privileges.
                   11776: returns user role, first access and timer interval hashes
1.243     albertel 11777: 
                   11778: =item *
1.1171    droeschl 11779: X<privileged()>
                   11780: B<privileged($username,$domain)>: returns a true if user has a
                   11781: privileged and active role (i.e. su or dc), false otherwise.
                   11782: 
                   11783: =item *
1.551     albertel 11784: X<getsection()>
                   11785: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11786: course $cname, return section name/number or '' for "not in course"
                   11787: and '-1' for "no section"
                   11788: 
                   11789: =item *
1.394     bowersj2 11790: X<userenvironment()>
                   11791: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11792: passed in @what from the requested user's environment, returns a hash
                   11793: 
1.858     raeburn  11794: =item * 
                   11795: X<userlog_query()>
1.859     albertel 11796: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11797: activity.log file. %filters defines filters applied when parsing the
                   11798: log file. These can be start or end timestamps, or the type of action
                   11799: - log to look for Login or Logout events, check for Checkin or
                   11800: Checkout, role for role selection. The response is in the form
                   11801: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11802: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11803: 
1.243     albertel 11804: =back
                   11805: 
                   11806: =head2 User Roles
                   11807: 
                   11808: =over 4
                   11809: 
                   11810: =item *
                   11811: 
1.810     raeburn  11812: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11813:  F: full access
                   11814:  U,I,K: authentication modes (cxx only)
                   11815:  '': forbidden
                   11816:  1: user needs to choose course
                   11817:  2: browse allowed
1.766     albertel 11818:  A: passphrase authentication needed
1.243     albertel 11819: 
                   11820: =item *
                   11821: 
                   11822: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11823: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11824: and course level
                   11825: 
                   11826: =item *
                   11827: 
1.988     raeburn  11828: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11829: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11830: $type is Course (default) or Community.
1.988     raeburn  11831: If $forcedefault evaluates to true, text returned will be default 
                   11832: text for $type. Otherwise, if this is a course, the text returned 
                   11833: will be a custom name for the role (if defined in the course's 
                   11834: environment).  If no custom name is defined the default is returned.
                   11835:    
1.832     raeburn  11836: =item *
                   11837: 
1.935     raeburn  11838: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11839: All arguments are optional. Returns a hash of a roles, either for
                   11840: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11841: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11842: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11843: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11844: For each key, value is set to colon-separated start and end times for
                   11845: the role.  If no username and domain are specified, will default to
1.934     raeburn  11846: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11847: of role statuses (active, future or previous), roles 
                   11848: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11849: to restrict the list of roles reported. If no array ref is 
                   11850: provided for types, will default to return only active roles.
1.834     albertel 11851: 
1.243     albertel 11852: =back
                   11853: 
                   11854: =head2 User Modification
                   11855: 
                   11856: =over 4
                   11857: 
                   11858: =item *
                   11859: 
1.957     raeburn  11860: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11861: user for the level given by URL.  Optional start and end dates (leave empty
                   11862: string or zero for "no date")
1.191     harris41 11863: 
                   11864: =item *
                   11865: 
1.243     albertel 11866: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11867: change a users, password, possible return values are: ok,
                   11868: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11869: refused
1.191     harris41 11870: 
                   11871: =item *
                   11872: 
1.243     albertel 11873: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11874: 
                   11875: =item *
                   11876: 
1.1058    raeburn  11877: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11878:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11879: 
                   11880: will update user information (firstname,middlename,lastname,generation,
                   11881: permanentemail), and if forceid is true, student/employee ID also.
                   11882: A user's institutional affiliation(s) can also be updated.
                   11883: User information fields will not be overwritten with empty entries 
                   11884: unless the field is included in the $candelete array reference.
                   11885: This array is included when a single user is modified via "Manage Users",
                   11886: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11887: 
                   11888: =item *
                   11889: 
1.286     matthew  11890: modifystudent
                   11891: 
1.957     raeburn  11892: modify a student's enrollment and identification information.
1.286     matthew  11893: The course id is resolved based on the current users environment.  
                   11894: This means the envoking user must be a course coordinator or otherwise
                   11895: associated with a course.
                   11896: 
1.297     matthew  11897: This call is essentially a wrapper for lonnet::modifyuser and
                   11898: lonnet::modify_student_enrollment
1.286     matthew  11899: 
                   11900: Inputs: 
                   11901: 
                   11902: =over 4
                   11903: 
1.957     raeburn  11904: =item B<$udom> Student's loncapa domain
1.286     matthew  11905: 
1.957     raeburn  11906: =item B<$uname> Student's loncapa login name
1.286     matthew  11907: 
1.964     bisitz   11908: =item B<$uid> Student/Employee ID
1.286     matthew  11909: 
1.957     raeburn  11910: =item B<$umode> Student's authentication mode
1.286     matthew  11911: 
1.957     raeburn  11912: =item B<$upass> Student's password
1.286     matthew  11913: 
1.957     raeburn  11914: =item B<$first> Student's first name
1.286     matthew  11915: 
1.957     raeburn  11916: =item B<$middle> Student's middle name
1.286     matthew  11917: 
1.957     raeburn  11918: =item B<$last> Student's last name
1.286     matthew  11919: 
1.957     raeburn  11920: =item B<$gene> Student's generation
1.286     matthew  11921: 
1.957     raeburn  11922: =item B<$usec> Student's section in course
1.286     matthew  11923: 
                   11924: =item B<$end> Unix time of the roles expiration
                   11925: 
                   11926: =item B<$start> Unix time of the roles start date
                   11927: 
                   11928: =item B<$forceid> If defined, allow $uid to be changed
                   11929: 
                   11930: =item B<$desiredhome> server to use as home server for student
                   11931: 
1.957     raeburn  11932: =item B<$email> Student's permanent e-mail address
                   11933: 
                   11934: =item B<$type> Type of enrollment (auto or manual)
                   11935: 
1.963     raeburn  11936: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11937: 
                   11938: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11939: 
1.963     raeburn  11940: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11941: 
1.963     raeburn  11942: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11943: 
1.963     raeburn  11944: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11945: 
1.286     matthew  11946: =back
1.297     matthew  11947: 
                   11948: =item *
                   11949: 
                   11950: modify_student_enrollment
                   11951: 
                   11952: Change a students enrollment status in a class.  The environment variable
                   11953: 'role.request.course' must be defined for this function to proceed.
                   11954: 
                   11955: Inputs:
                   11956: 
                   11957: =over 4
                   11958: 
                   11959: =item $udom, students domain
                   11960: 
                   11961: =item $uname, students name
                   11962: 
                   11963: =item $uid, students user id
                   11964: 
                   11965: =item $first, students first name
                   11966: 
                   11967: =item $middle
                   11968: 
                   11969: =item $last
                   11970: 
                   11971: =item $gene
                   11972: 
                   11973: =item $usec
                   11974: 
                   11975: =item $end
                   11976: 
                   11977: =item $start
                   11978: 
1.957     raeburn  11979: =item $type
                   11980: 
                   11981: =item $locktype
                   11982: 
                   11983: =item $cid
                   11984: 
                   11985: =item $selfenroll
                   11986: 
                   11987: =item $context
                   11988: 
1.297     matthew  11989: =back
                   11990: 
1.191     harris41 11991: 
                   11992: =item *
                   11993: 
1.243     albertel 11994: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11995: custom role; give a custom role to a user for the level given by URL.  Specify
                   11996: name and domain of role author, and role name
1.191     harris41 11997: 
                   11998: =item *
                   11999: 
1.243     albertel 12000: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12001: 
                   12002: =item *
                   12003: 
1.243     albertel 12004: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12005: 
                   12006: =back
                   12007: 
                   12008: =head2 Course Infomation
                   12009: 
                   12010: =over 4
1.191     harris41 12011: 
                   12012: =item *
                   12013: 
1.1118    foxr     12014: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12015: specified course id, including all environment settings for the
                   12016: course, the description of the course will be in the hash under the
                   12017: key 'description'
1.191     harris41 12018: 
1.1118    foxr     12019: $options is an optional parameter that if supplied is a hash reference that controls
                   12020: what how this function works.  It has the following key/values:
                   12021: 
                   12022: =over 4
                   12023: 
                   12024: =item freshen_cache
                   12025: 
                   12026: If defined, and the environment cache for the course is valid, it is 
                   12027: returned in the returned hash.
                   12028: 
                   12029: =item one_time
                   12030: 
                   12031: If defined, the last cache time is set to _now_
                   12032: 
                   12033: =item user
                   12034: 
                   12035: If defined, the supplied username is used instead of the current user.
                   12036: 
                   12037: 
                   12038: =back
                   12039: 
1.191     harris41 12040: =item *
                   12041: 
1.624     albertel 12042: resdata($name,$domain,$type,@which) : request for current parameter
                   12043: setting for a specific $type, where $type is either 'course' or 'user',
                   12044: @what should be a list of parameters to ask about. This routine caches
                   12045: answers for 5 minutes.
1.243     albertel 12046: 
1.877     foxr     12047: =item *
                   12048: 
                   12049: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12050: data base, returning a hash that is keyed by the resource name and has
                   12051: values that are the resource value.  I believe that the timestamps and
                   12052: versions are also returned.
                   12053: 
                   12054: 
1.243     albertel 12055: =back
                   12056: 
                   12057: =head2 Course Modification
                   12058: 
                   12059: =over 4
1.191     harris41 12060: 
                   12061: =item *
                   12062: 
1.243     albertel 12063: writecoursepref($courseid,%prefs) : write preferences (environment
                   12064: database) for a course
1.191     harris41 12065: 
                   12066: =item *
                   12067: 
1.1011    raeburn  12068: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12069: 
                   12070: =item *
                   12071: 
1.1038    raeburn  12072: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12073: 
1.1167    droeschl 12074: =item *
                   12075: 
                   12076: is_course($courseid), is_course($cdom, $cnum)
                   12077: 
                   12078: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12079: two component version $cdom, $cnum. It checks if the specified course exists.
                   12080: 
                   12081: Returns:
                   12082:     undef if the course doesn't exist, otherwise
                   12083:     in scalar context the combined courseid.
                   12084:     in list context the two components of the course identifier, domain and 
                   12085:     courseid.    
                   12086: 
1.243     albertel 12087: =back
                   12088: 
                   12089: =head2 Resource Subroutines
                   12090: 
                   12091: =over 4
1.191     harris41 12092: 
                   12093: =item *
                   12094: 
1.243     albertel 12095: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12096: 
                   12097: =item *
                   12098: 
1.243     albertel 12099: repcopy($filename) : subscribes to the requested file, and attempts to
                   12100: replicate from the owning library server, Might return
1.607     raeburn  12101: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12102: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12103: resource. Expects the local filesystem pathname
                   12104: (/home/httpd/html/res/....)
                   12105: 
                   12106: =back
                   12107: 
                   12108: =head2 Resource Information
                   12109: 
                   12110: =over 4
1.191     harris41 12111: 
                   12112: =item *
                   12113: 
1.243     albertel 12114: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12115: a vairety of different possible values, $varname should be a request
                   12116: string, and the other parameters can be used to specify who and what
                   12117: one is asking about.
                   12118: 
                   12119: Possible values for $varname are environment.lastname (or other item
                   12120: from the envirnment hash), user.name (or someother aspect about the
                   12121: user), resource.0.maxtries (or some other part and parameter of a
                   12122: resource)
1.204     albertel 12123: 
                   12124: =item *
                   12125: 
1.243     albertel 12126: directcondval($number) : get current value of a condition; reads from a state
                   12127: string
1.204     albertel 12128: 
                   12129: =item *
                   12130: 
1.243     albertel 12131: condval($condidx) : value of condition index based on state
1.204     albertel 12132: 
                   12133: =item *
                   12134: 
1.243     albertel 12135: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12136: resource's metadata, $what should be either a specific key, or either
                   12137: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12138: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12139: 
                   12140: this function automatically caches all requests
1.191     harris41 12141: 
                   12142: =item *
                   12143: 
1.243     albertel 12144: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12145: network of library servers; returns file handle of where SQL and regex results
                   12146: will be stored for query
1.191     harris41 12147: 
                   12148: =item *
                   12149: 
1.243     albertel 12150: symbread($filename) : return symbolic list entry (filename argument optional);
                   12151: returns the data handle
1.191     harris41 12152: 
                   12153: =item *
                   12154: 
1.243     albertel 12155: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12156: a possible symb for the URL in $thisfn, and if is an encryypted
                   12157: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12158: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12159: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12160: 
1.191     harris41 12161: 
                   12162: =item *
                   12163: 
1.243     albertel 12164: symbclean($symb) : removes versions numbers from a symb, returns the
                   12165: cleaned symb
1.191     harris41 12166: 
                   12167: =item *
                   12168: 
1.243     albertel 12169: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12170: course map, user must be in a course for it to work.
1.191     harris41 12171: 
                   12172: =item *
                   12173: 
1.243     albertel 12174: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12175: 
                   12176: =item *
                   12177: 
1.243     albertel 12178: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12179: a random seed, all arguments are optional, if they aren't sent it uses the
                   12180: environment to derive them. Note: if symb isn't sent and it can't get one
                   12181: from &symbread it will use the current time as its return value
1.191     harris41 12182: 
                   12183: =item *
                   12184: 
1.243     albertel 12185: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12186: unfakeable, receipt
1.191     harris41 12187: 
                   12188: =item *
                   12189: 
1.620     albertel 12190: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12191: 
                   12192: =item *
                   12193: 
1.243     albertel 12194: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12195: 
                   12196: =item *
                   12197: 
1.243     albertel 12198: 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 12199: 
                   12200: =item *
                   12201: 
1.243     albertel 12202: 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 12203: 
                   12204: =item *
                   12205: 
1.243     albertel 12206: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12207: 
                   12208: =item *
                   12209: 
1.243     albertel 12210: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12211: forcing spreadsheet to reevaluate the resource scores next time.
                   12212: 
                   12213: =back
                   12214: 
                   12215: =head2 Storing/Retreiving Data
                   12216: 
                   12217: =over 4
1.191     harris41 12218: 
                   12219: =item *
                   12220: 
1.243     albertel 12221: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12222: for this url; hashref needs to be given and should be a \%hashname; the
                   12223: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12224: be derived from the env
1.191     harris41 12225: 
                   12226: =item *
                   12227: 
1.243     albertel 12228: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12229: uses critical subroutine
1.191     harris41 12230: 
                   12231: =item *
                   12232: 
1.243     albertel 12233: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12234: all args are optional
1.191     harris41 12235: 
                   12236: =item *
                   12237: 
1.717     albertel 12238: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12239: dumps the complete (or key matching regexp) namespace into a hash
                   12240: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12241: normally &store()ed into
                   12242: 
                   12243: $range should be either an integer '100' (give me the first 100
                   12244:                                            matching records)
                   12245:               or be  two integers sperated by a - with no spaces
                   12246:                  '30-50' (give me the 30th through the 50th matching
                   12247:                           records)
                   12248: 
                   12249: 
                   12250: =item *
                   12251: 
                   12252: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12253: replaces a &store() version of data with a replacement set of data
                   12254: for a particular resource in a namespace passed in the $storehash hash 
                   12255: reference
                   12256: 
                   12257: =item *
                   12258: 
1.243     albertel 12259: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12260: works very similar to store/cstore, but all data is stored in a
                   12261: temporary location and can be reset using tmpreset, $storehash should
                   12262: be a hash reference, returns nothing on success
1.191     harris41 12263: 
                   12264: =item *
                   12265: 
1.243     albertel 12266: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12267: similar to restore, but all data is stored in a temporary location and
                   12268: can be reset using tmpreset. Returns a hash of values on success,
                   12269: error string otherwise.
1.191     harris41 12270: 
                   12271: =item *
                   12272: 
1.243     albertel 12273: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12274: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12275: 
                   12276: =item *
                   12277: 
1.243     albertel 12278: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12279: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12280: 
                   12281: =item *
                   12282: 
1.243     albertel 12283: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12284: namesp ($udom and $uname are optional)
1.191     harris41 12285: 
                   12286: =item *
                   12287: 
1.702     albertel 12288: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12289: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12290: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12291: 
1.702     albertel 12292: $range should be either an integer '100' (give me the first 100
                   12293:                                            matching records)
                   12294:               or be  two integers sperated by a - with no spaces
                   12295:                  '30-50' (give me the 30th through the 50th matching
                   12296:                           records)
1.449     matthew  12297: =item *
                   12298: 
                   12299: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12300: $store can be a scalar, an array reference, or if the amount to be 
                   12301: incremented is > 1, a hash reference.
                   12302: 
                   12303: ($udom and $uname are optional)
1.191     harris41 12304: 
                   12305: =item *
                   12306: 
1.243     albertel 12307: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12308: ($udom and $uname are optional)
1.191     harris41 12309: 
                   12310: =item *
                   12311: 
1.243     albertel 12312: cput($namespace,$storehash,$udom,$uname) : critical put
                   12313: ($udom and $uname are optional)
1.191     harris41 12314: 
                   12315: =item *
                   12316: 
1.748     albertel 12317: newput($namespace,$storehash,$udom,$uname) :
                   12318: 
                   12319: Attempts to store the items in the $storehash, but only if they don't
                   12320: currently exist, if this succeeds you can be certain that you have 
                   12321: successfully created a new key value pair in the $namespace db.
                   12322: 
                   12323: 
                   12324: Args:
                   12325:  $namespace: name of database to store values to
                   12326:  $storehash: hashref to store to the db
                   12327:  $udom: (optional) domain of user containing the db
                   12328:  $uname: (optional) name of user caontaining the db
                   12329: 
                   12330: Returns:
                   12331:  'ok' -> succeeded in storing all keys of $storehash
                   12332:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12333:                         least <key> already existed in the db (other
                   12334:                         requested keys may also already exist)
1.967     bisitz   12335:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12336:  'con_lost' -> unable to contact request server
                   12337:  'refused' -> action was not allowed by remote machine
                   12338: 
                   12339: 
                   12340: =item *
                   12341: 
1.243     albertel 12342: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12343: reference filled in from namesp (encrypts the return communication)
                   12344: ($udom and $uname are optional)
1.191     harris41 12345: 
                   12346: =item *
                   12347: 
1.243     albertel 12348: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12349: critical subroutine
                   12350: 
1.806     raeburn  12351: =item *
                   12352: 
1.860     raeburn  12353: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12354: array reference filled in from namespace found in domain level on either
                   12355: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12356: 
                   12357: =item *
                   12358: 
1.860     raeburn  12359: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12360: domain level either on specified domain server ($uhome) or primary domain 
                   12361: server ($udom and $uhome are optional)
1.806     raeburn  12362: 
1.943     raeburn  12363: =item * 
                   12364: 
                   12365: get_domain_defaults($target_domain) : returns hash with defaults for
                   12366: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12367: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12368: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12369: Values are retrieved from cache (if current), or from domain's configuration.db
                   12370: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12371: or lonTabs/domain.tab. 
                   12372: 
                   12373: %domdefaults = &get_auth_defaults($target_domain);
                   12374: 
1.243     albertel 12375: =back
                   12376: 
                   12377: =head2 Network Status Functions
                   12378: 
                   12379: =over 4
1.191     harris41 12380: 
                   12381: =item *
                   12382: 
1.1137    raeburn  12383: dirlist() : return directory list based on URI (first arg).
                   12384: 
                   12385: Inputs: 1 required, 5 optional.
                   12386: 
                   12387: =over
                   12388: 
                   12389: =item 
                   12390: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12391: 
                   12392: =item
                   12393: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12394: 
                   12395: =item
                   12396: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12397: 
                   12398: =item
                   12399: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12400: 
                   12401: =item
                   12402: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12403: 
                   12404: =item 
                   12405: $alternateRoot - path to prepend in place of path from $uri.
                   12406: 
                   12407: =back
                   12408: 
                   12409: Returns: Array of up to two items.
                   12410: 
                   12411: =over
                   12412: 
                   12413: a reference to an array of files/subdirectories
                   12414: 
                   12415: =over
                   12416: 
                   12417: Each element in the array of files/subdirectories is a & separated list of
                   12418: item name and the result of running stat on the item.  If dirlist was requested
                   12419: for a file instead of a directory, the item name will be ''. For a directory 
                   12420: listing, if the item is a metadata file, the element will end &N&M 
                   12421: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12422: default copyright set (1).  
                   12423: 
                   12424: =back
                   12425: 
                   12426: a scalar containing error condition (if encountered).
                   12427: 
                   12428: =over
                   12429: 
                   12430: =item 
                   12431: no_host (no homeserver identified for $username:$domain).
                   12432: 
                   12433: =item 
                   12434: no_such_host (server contacted for listing not identified as valid host).
                   12435: 
                   12436: =item 
                   12437: con_lost (connection to remote server failed).
                   12438: 
                   12439: =item 
                   12440: refused (invalid $username:$domain received on lond side).
                   12441: 
                   12442: =item 
                   12443: no_such_dir (directory at specified path on lond side does not exist). 
                   12444: 
                   12445: =item 
                   12446: empty (directory at specified path on lond side is empty).
                   12447: 
                   12448: =over
                   12449: 
                   12450: This is currently not encountered because the &ls3, &ls2, 
                   12451: &ls (_handler) routines on the lond side do not filter out
                   12452: . and .. from a directory listing. 
                   12453: 
                   12454: =back
                   12455: 
                   12456: =back
                   12457: 
                   12458: =back
1.191     harris41 12459: 
                   12460: =item *
                   12461: 
1.243     albertel 12462: spareserver() : find server with least workload from spare.tab
                   12463: 
1.986     foxr     12464: 
                   12465: =item *
                   12466: 
                   12467: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12468: if there is no corresponding loncapa host.
                   12469: 
1.243     albertel 12470: =back
                   12471: 
1.986     foxr     12472: 
1.243     albertel 12473: =head2 Apache Request
                   12474: 
                   12475: =over 4
1.191     harris41 12476: 
                   12477: =item *
                   12478: 
1.243     albertel 12479: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12480: localhost, posts hash
                   12481: 
                   12482: =back
                   12483: 
                   12484: =head2 Data to String to Data
                   12485: 
                   12486: =over 4
1.191     harris41 12487: 
                   12488: =item *
                   12489: 
1.243     albertel 12490: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12491: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12492: 
                   12493: =item *
                   12494: 
1.243     albertel 12495: hashref2str($hashref) : convert a hashref into a string complete with
                   12496: escaping and '=' and '&' separators, supports elements that are
                   12497: arrayrefs and hashrefs
1.191     harris41 12498: 
                   12499: =item *
                   12500: 
1.243     albertel 12501: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12502: with escaping and '&' separators, supports elements that are arrayrefs
                   12503: and hashrefs
1.191     harris41 12504: 
                   12505: =item *
                   12506: 
1.243     albertel 12507: str2hash($string) : convert string to hash using unescaping and
                   12508: splitting on '=' and '&', supports elements that are arrayrefs and
                   12509: hashrefs
1.191     harris41 12510: 
                   12511: =item *
                   12512: 
1.243     albertel 12513: str2array($string) : convert string to hash using unescaping and
                   12514: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12515: 
                   12516: =back
                   12517: 
                   12518: =head2 Logging Routines
                   12519: 
                   12520: 
                   12521: These routines allow one to make log messages in the lonnet.log and
                   12522: lonnet.perm logfiles.
1.191     harris41 12523: 
1.1119    foxr     12524: =over 4
                   12525: 
1.191     harris41 12526: =item *
                   12527: 
1.243     albertel 12528: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12529: 
                   12530: =item *
                   12531: 
1.243     albertel 12532: logthis() : append message to the normal lonnet.log file, it gets
                   12533: preiodically rolled over and deleted.
1.191     harris41 12534: 
                   12535: =item *
                   12536: 
1.243     albertel 12537: logperm() : append a permanent message to lonnet.perm.log, this log
                   12538: file never gets deleted by any automated portion of the system, only
                   12539: messages of critical importance should go in here.
                   12540: 
1.1119    foxr     12541: 
1.243     albertel 12542: =back
                   12543: 
                   12544: =head2 General File Helper Routines
                   12545: 
                   12546: =over 4
1.191     harris41 12547: 
                   12548: =item *
                   12549: 
1.481     raeburn  12550: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12551: (a) files in /uploaded
                   12552:   (i) If a local copy of the file exists - 
                   12553:       compares modification date of local copy with last-modified date for 
                   12554:       definitive version stored on home server for course. If local copy is 
                   12555:       stale, requests a new version from the home server and stores it. 
                   12556:       If the original has been removed from the home server, then local copy 
                   12557:       is unlinked.
                   12558:   (ii) If local copy does not exist -
                   12559:       requests the file from the home server and stores it. 
                   12560:   
                   12561:   If $caller is 'uploadrep':  
                   12562:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12563:     for request for files originally uploaded via DOCS. 
                   12564:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12565:   
                   12566:   Otherwise:
                   12567:      This indicates a call from the content generation phase of the request.
                   12568:      -  returns the entire contents of the file or -1.
                   12569:      
                   12570: (b) files in /res
                   12571:    - returns the entire contents of a file or -1; 
                   12572:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12573: 
1.712     albertel 12574: 
                   12575: =item *
                   12576: 
                   12577: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12578:                   reference
                   12579: 
                   12580: returns either a stat() list of data about the file or an empty list
                   12581: if the file doesn't exist or couldn't find out about it (connection
                   12582: problems or user unknown)
                   12583: 
1.191     harris41 12584: =item *
                   12585: 
1.243     albertel 12586: filelocation($dir,$file) : returns file system location of a file
                   12587: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12588: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12589: and a file of ../bob will become /a/bob)
1.191     harris41 12590: 
                   12591: =item *
                   12592: 
                   12593: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12594: filelocation except for hrefs
                   12595: 
                   12596: =item *
                   12597: 
                   12598: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12599: 
1.243     albertel 12600: =back
                   12601: 
1.608     albertel 12602: =head2 Usererfile file routines (/uploaded*)
                   12603: 
                   12604: =over 4
                   12605: 
                   12606: =item *
                   12607: 
                   12608: userfileupload(): main rotine for putting a file in a user or course's
                   12609:                   filespace, arguments are,
                   12610: 
1.620     albertel 12611:  formname - required - this is the name of the element in $env where the
1.608     albertel 12612:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12613:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12614:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12615:  context - if coursedoc, store the file in the course of the active role
                   12616:              of the current user; 
                   12617:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12618:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12619:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12620:          if undefined, it will be placed in "unknown"
                   12621: 
                   12622:  (This routine calls clean_filename() to remove any dangerous
                   12623:  characters from the filename, and then calls finuserfileupload() to
                   12624:  complete the transaction)
                   12625: 
                   12626:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12627:  and /adm/notfound.html if unsuccessful
                   12628: 
                   12629: =item *
                   12630: 
                   12631: clean_filename(): routine for cleaing a filename up for storage in
                   12632:                  userfile space, argument is:
                   12633: 
                   12634:  filename - proposed filename
                   12635: 
                   12636: returns: the new clean filename
                   12637: 
                   12638: =item *
                   12639: 
1.1090    raeburn  12640: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12641: userspace, probably shouldn't be called directly
                   12642: 
                   12643:   docuname: username or courseid of destination for the file
                   12644:   docudom: domain of user/course of destination for the file
                   12645:   formname: same as for userfileupload()
1.1090    raeburn  12646:   fname: filename (including subdirectories) for the file
                   12647:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12648:   allfiles: reference to hash used to store objects found by parser
                   12649:   codebase: reference to hash used for codebases of java objects found by parser
                   12650:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12651:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12652:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12653:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12654:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12655:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12656:   mimetype: reference to scalar to accommodate mime type determined
                   12657:             from File::MMagic if $parser = parse.
1.608     albertel 12658: 
                   12659:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12660:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12661:  was 'overwrite').
                   12662:  
1.608     albertel 12663: 
                   12664: =item *
                   12665: 
                   12666: renameuserfile(): renames an existing userfile to a new name
                   12667: 
                   12668:   Args:
                   12669:    docuname: username or courseid of destination for the file
                   12670:    docudom: domain of user/course of destination for the file
                   12671:    old: current file name (including any subdirs under userfiles)
                   12672:    new: desired file name (including any subdirs under userfiles)
                   12673: 
                   12674: =item *
                   12675: 
                   12676: mkdiruserfile(): creates a directory is a userfiles dir
                   12677: 
                   12678:   Args:
                   12679:    docuname: username or courseid of destination for the file
                   12680:    docudom: domain of user/course of destination for the file
                   12681:    dir: dir to create (including any subdirs under userfiles)
                   12682: 
                   12683: =item *
                   12684: 
                   12685: removeuserfile(): removes a file that exists in userfiles
                   12686: 
                   12687:   Args:
                   12688:    docuname: username or courseid of destination for the file
                   12689:    docudom: domain of user/course of destination for the file
                   12690:    fname: filname to delete (including any subdirs under userfiles)
                   12691: 
                   12692: =item *
                   12693: 
                   12694: removeuploadedurl(): convience function for removeuserfile()
                   12695: 
                   12696:   Args:
                   12697:    url:  a full /uploaded/... url to delete
                   12698: 
1.747     albertel 12699: =item * 
                   12700: 
                   12701: get_portfile_permissions():
                   12702:   Args:
                   12703:     domain: domain of user or course contain the portfolio files
                   12704:     user: name of user or num of course contain the portfolio files
                   12705:   Returns:
                   12706:     hashref of a dump of the proper file_permissions.db
                   12707:    
                   12708: 
                   12709: =item * 
                   12710: 
                   12711: get_access_controls():
                   12712: 
                   12713: Args:
                   12714:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12715:   group: (optional) the group you want the files associated with
                   12716:   file: (optional) the file you want access info on
                   12717: 
                   12718: Returns:
1.749     raeburn  12719:     a hash (keys are file names) of hashes containing
                   12720:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12721:         values are XML containing access control settings (see below) 
1.747     albertel 12722: 
                   12723: Internal notes:
                   12724: 
1.749     raeburn  12725:  access controls are stored in file_permissions.db as key=value pairs.
                   12726:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12727:         where scope -> public,guest,course,group,domains or users.
                   12728:               end -> UNIX time for end of access (0 -> no end date)
                   12729:               start -> UNIX time for start of access
                   12730: 
                   12731:     value -> XML description of access control
                   12732:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12733:             <start></start>
                   12734:             <end></end>
                   12735: 
                   12736:             <password></password>  for scope type = guest
                   12737: 
                   12738:             <domain></domain>     for scope type = course or group
                   12739:             <number></number>
                   12740:             <roles id="">
                   12741:              <role></role>
                   12742:              <access></access>
                   12743:              <section></section>
                   12744:              <group></group>
                   12745:             </roles>
                   12746: 
                   12747:             <dom></dom>         for scope type = domains
                   12748: 
                   12749:             <users>             for scope type = users
                   12750:              <user>
                   12751:               <uname></uname>
                   12752:               <udom></udom>
                   12753:              </user>
                   12754:             </users>
                   12755:            </scope> 
                   12756:               
                   12757:  Access data is also aggregated for each file in an additional key=value pair:
                   12758:  key -> path to file/file_name\0accesscontrol 
                   12759:  value -> reference to hash
                   12760:           hash contains key = value pairs
                   12761:           where key = uniqueID:scope_end_start
                   12762:                 value = UNIX time record was last updated
                   12763: 
                   12764:           Used to improve speed of look-ups of access controls for each file.  
                   12765:  
                   12766:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12767: 
                   12768: modify_access_controls():
                   12769: 
                   12770: Modifies access controls for a portfolio file
                   12771: Args
                   12772: 1. file name
                   12773: 2. reference to hash of required changes,
                   12774: 3. domain
                   12775: 4. username
                   12776:   where domain,username are the domain of the portfolio owner 
                   12777:   (either a user or a course) 
                   12778: 
                   12779: Returns:
                   12780: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12781: 2. result of deletions ('ok' or 'error', with error message).
                   12782: 3. reference to hash of any new or updated access controls.
                   12783: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12784:    key = integer (inbound ID)
                   12785:    value = uniqueID  
1.747     albertel 12786: 
1.608     albertel 12787: =back
                   12788: 
1.243     albertel 12789: =head2 HTTP Helper Routines
                   12790: 
                   12791: =over 4
                   12792: 
1.191     harris41 12793: =item *
                   12794: 
                   12795: escape() : unpack non-word characters into CGI-compatible hex codes
                   12796: 
                   12797: =item *
                   12798: 
                   12799: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12800: 
1.243     albertel 12801: =back
                   12802: 
                   12803: =head1 PRIVATE SUBROUTINES
                   12804: 
                   12805: =head2 Underlying communication routines (Shouldn't call)
                   12806: 
                   12807: =over 4
                   12808: 
                   12809: =item *
                   12810: 
                   12811: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12812: 
                   12813: =item *
                   12814: 
                   12815: reply() : uses subreply to send a message to remote machine, logs all failures
                   12816: 
                   12817: =item *
                   12818: 
                   12819: critical() : passes a critical message to another server; if cannot
                   12820: get through then place message in connection buffer directory and
                   12821: returns con_delayed, if incapable of saving message, returns
                   12822: con_failed
                   12823: 
                   12824: =item *
                   12825: 
                   12826: reconlonc() : tries to reconnect lonc client processes.
                   12827: 
                   12828: =back
                   12829: 
                   12830: =head2 Resource Access Logging
                   12831: 
                   12832: =over 4
                   12833: 
                   12834: =item *
                   12835: 
                   12836: flushcourselogs() : flush (save) buffer logs and access logs
                   12837: 
                   12838: =item *
                   12839: 
                   12840: courselog($what) : save message for course in hash
                   12841: 
                   12842: =item *
                   12843: 
                   12844: courseacclog($what) : save message for course using &courselog().  Perform
                   12845: special processing for specific resource types (problems, exams, quizzes, etc).
                   12846: 
1.191     harris41 12847: =item *
                   12848: 
                   12849: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12850: as a PerlChildExitHandler
1.243     albertel 12851: 
                   12852: =back
                   12853: 
                   12854: =head2 Other
                   12855: 
                   12856: =over 4
                   12857: 
                   12858: =item *
                   12859: 
                   12860: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12861: 
                   12862: =back
                   12863: 
                   12864: =cut
1.877     foxr     12865: 

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