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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1161  ! www         4: # $Id: lonnet.pm,v 1.1160 2012/03/16 21:16:46 www 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.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1117    foxr      100: 
1.1090    raeburn   101: use File::Copy;
1.676     albertel  102: 
1.195     www       103: my $readit;
1.550     foxr      104: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  105: 
1.619     albertel  106: require Exporter;
                    107: 
                    108: our @ISA = qw (Exporter);
                    109: our @EXPORT = qw(%env);
                    110: 
1.449     matthew   111: 
1.1       albertel  112: # --------------------------------------------------------------------- Logging
1.729     www       113: {
                    114:     my $logid;
                    115:     sub instructor_log {
1.957     raeburn   116: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if (($cnum eq '') || ($cdom eq '')) {
                    118:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    119:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    120:         }
1.729     www       121: 	$logid++;
1.957     raeburn   122:         my $now = time();
                    123: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       124: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       125: 				    { $id => {
                    126: 					'exe_uname' => $env{'user.name'},
                    127: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   128: 					'exe_time'  => $now,
1.730     www       129: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    130: 					'delflag'   => $delflag,
                    131: 					'logentry'  => $storehash,
                    132: 					'uname'     => $uname,
                    133: 					'udom'      => $udom,
                    134: 				    }
1.957     raeburn   135: 				  },$cdom,$cnum);
1.729     www       136:     }
                    137: }
1.1       albertel  138: 
1.163     harris41  139: sub logtouch {
                    140:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  141:     unless (-e "$execdir/logs/lonnet.log") {	
                    142: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  143: 	close $fh;
                    144:     }
                    145:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    146:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    147: }
                    148: 
1.1       albertel  149: sub logthis {
                    150:     my $message=shift;
                    151:     my $execdir=$perlvar{'lonDaemons'};
                    152:     my $now=time;
                    153:     my $local=localtime($now);
1.448     albertel  154:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      155: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    156: 	print $fh $logstring;
1.448     albertel  157: 	close($fh);
                    158:     }
1.1       albertel  159:     return 1;
                    160: }
                    161: 
                    162: sub logperm {
                    163:     my $message=shift;
                    164:     my $execdir=$perlvar{'lonDaemons'};
                    165:     my $now=time;
                    166:     my $local=localtime($now);
1.448     albertel  167:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    168: 	print $fh "$now:$message:$local\n";
                    169: 	close($fh);
                    170:     }
1.1       albertel  171:     return 1;
                    172: }
                    173: 
1.850     albertel  174: sub create_connection {
1.853     albertel  175:     my ($hostname,$lonid) = @_;
1.851     albertel  176:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  177: 				     Type    => SOCK_STREAM,
                    178: 				     Timeout => 10);
                    179:     return 0 if (!$client);
1.890     albertel  180:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  181:     my $result = <$client>;
                    182:     chomp($result);
                    183:     return 1 if ($result eq 'done');
                    184:     return 0;
                    185: }
                    186: 
1.983     raeburn   187: sub get_server_timezone {
                    188:     my ($cnum,$cdom) = @_;
                    189:     my $home=&homeserver($cnum,$cdom);
                    190:     if ($home ne 'no_host') {
                    191:         my $cachetime = 24*3600;
                    192:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    193:         if (defined($cached)) {
                    194:             return $timezone;
                    195:         } else {
                    196:             my $timezone = &reply('servertimezone',$home);
                    197:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    198:         }
                    199:     }
                    200: }
1.850     albertel  201: 
1.1106    raeburn   202: sub get_server_distarch {
                    203:     my ($lonhost,$ignore_cache) = @_;
                    204:     if (defined($lonhost)) {
                    205:         if (!defined(&hostname($lonhost))) {
                    206:             return;
                    207:         }
                    208:         my $cachetime = 12*3600;
                    209:         if (!$ignore_cache) {
                    210:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    211:             if (defined($cached)) {
                    212:                 return $distarch;
                    213:             }
                    214:         }
                    215:         my $rep = &reply('serverdistarch',$lonhost);
                    216:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    217:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    218:                 $rep eq '') {
                    219:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    220:         }
                    221:     }
                    222:     return;
                    223: }
                    224: 
1.993     raeburn   225: sub get_server_loncaparev {
1.1073    raeburn   226:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   227:     if (defined($lonhost)) {
                    228:         if (!defined(&hostname($lonhost))) {
                    229:             undef($lonhost);
                    230:         }
                    231:     }
                    232:     if (!defined($lonhost)) {
                    233:         if (defined(&domain($dom,'primary'))) {
                    234:             $lonhost=&domain($dom,'primary');
                    235:             if ($lonhost eq 'no_host') {
                    236:                 undef($lonhost);
                    237:             }
                    238:         }
                    239:     }
                    240:     if (defined($lonhost)) {
1.1073    raeburn   241:         my $cachetime = 12*3600;
                    242:         if (!$ignore_cache) {
                    243:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    244:             if (defined($cached)) {
                    245:                 return $loncaparev;
                    246:             }
                    247:         }
                    248:         my ($answer,$loncaparev);
                    249:         my @ids=&current_machine_ids();
                    250:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    251:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   252:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   253:                 $loncaparev = $1;
                    254:             }
                    255:         } else {
                    256:             $answer = &reply('serverloncaparev',$lonhost);
                    257:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    258:                 if ($caller eq 'loncron') {
                    259:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   260:                     $ua->timeout(4);
1.1073    raeburn   261:                     my $protocol = $protocol{$lonhost};
                    262:                     $protocol = 'http' if ($protocol ne 'https');
                    263:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    264:                     my $request=new HTTP::Request('GET',$url);
                    265:                     my $response=$ua->request($request);
                    266:                     unless ($response->is_error()) {
                    267:                         my $content = $response->content;
1.1081    raeburn   268:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   269:                             $loncaparev = $1;
                    270:                         }
                    271:                     }
                    272:                 } else {
                    273:                     $loncaparev = $loncaparevs{$lonhost};
                    274:                 }
1.1081    raeburn   275:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   276:                 $loncaparev = $1;
                    277:             }
1.993     raeburn   278:         }
1.1073    raeburn   279:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   280:     }
                    281: }
                    282: 
1.1074    raeburn   283: sub get_server_homeID {
                    284:     my ($hostname,$ignore_cache,$caller) = @_;
                    285:     unless ($ignore_cache) {
                    286:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    287:         if (defined($cached)) {
                    288:             return $serverhomeID;
                    289:         }
                    290:     }
                    291:     my $cachetime = 12*3600;
                    292:     my $serverhomeID;
                    293:     if ($caller eq 'loncron') { 
                    294:         my @machine_ids = &machine_ids($hostname);
                    295:         foreach my $id (@machine_ids) {
                    296:             my $response = &reply('serverhomeID',$id);
                    297:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    298:                 $serverhomeID = $response;
                    299:                 last;
                    300:             }
                    301:         }
                    302:         if ($serverhomeID eq '') {
                    303:             $serverhomeID = $machine_ids[-1];
                    304:         }
                    305:     } else {
                    306:         $serverhomeID = $serverhomeIDs{$hostname};
                    307:     }
                    308:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    309: }
                    310: 
1.1121    raeburn   311: sub get_remote_globals {
                    312:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   313:     my ($result,%returnhash,%whatneeded);
                    314:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   315:         foreach my $what (sort(keys(%{$whathash}))) {
                    316:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   317:             my ($response,$cached);
1.1121    raeburn   318:             unless ($ignore_cache) {
1.1125    raeburn   319:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   320:             }
                    321:             if (defined($cached)) {
1.1125    raeburn   322:                 $returnhash{$what} = $response;
1.1121    raeburn   323:             } else {
1.1125    raeburn   324:                 $whatneeded{$what} = 1;
1.1121    raeburn   325:             }
                    326:         }
1.1125    raeburn   327:         if (keys(%whatneeded) == 0) {
                    328:             $result = 'ok';
                    329:         } else {
1.1121    raeburn   330:             my $requested = &freeze_escape(\%whatneeded);
                    331:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   332:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    333:                 ($rep eq 'unknown_cmd')) {
                    334:                 $result = $rep;
                    335:             } else {
                    336:                 $result = 'ok';
1.1121    raeburn   337:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   338:                 foreach my $item (@pairs) {
                    339:                     my ($key,$value)=split(/=/,$item,2);
                    340:                     my $what = &unescape($key);
                    341:                     my $hashid = $lonhost.'-'.$what;
                    342:                     $returnhash{$what}=&thaw_unescape($value);
                    343:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   344:                 }
                    345:             }
                    346:         }
                    347:     }
1.1125    raeburn   348:     return ($result,\%returnhash);
1.1121    raeburn   349: }
                    350: 
1.1124    raeburn   351: sub remote_devalidate_cache {
                    352:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   353:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   354:     return $response;
                    355: }
                    356: 
1.1       albertel  357: # -------------------------------------------------- Non-critical communication
                    358: sub subreply {
                    359:     my ($cmd,$server)=@_;
1.838     albertel  360:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      361:     #
                    362:     #  With loncnew process trimming, there's a timing hole between lonc server
                    363:     #  process exit and the master server picking up the listen on the AF_UNIX
                    364:     #  socket.  In that time interval, a lock file will exist:
                    365: 
                    366:     my $lockfile=$peerfile.".lock";
                    367:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    368: 	sleep(1);
                    369:     }
                    370:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      371:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      372:     #
1.550     foxr      373:     #   We'll give the connection a few tries before abandoning it.  If
                    374:     #   connection is not possible, we'll con_lost back to the client.
                    375:     #   
                    376:     my $client;
                    377:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    378: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    379: 				      Type    => SOCK_STREAM,
                    380: 				      Timeout => 10);
1.869     albertel  381: 	if ($client) {
1.550     foxr      382: 	    last;		# Connected!
1.850     albertel  383: 	} else {
1.853     albertel  384: 	    &create_connection(&hostname($server),$server);
1.550     foxr      385: 	}
1.850     albertel  386:         sleep(1);		# Try again later if failed connection.
1.550     foxr      387:     }
                    388:     my $answer;
                    389:     if ($client) {
1.704     albertel  390: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      391: 	$answer=<$client>;
                    392: 	if (!$answer) { $answer="con_lost"; }
                    393: 	chomp($answer);
                    394:     } else {
                    395: 	$answer = 'con_lost';	# Failed connection.
                    396:     }
1.1       albertel  397:     return $answer;
                    398: }
                    399: 
                    400: sub reply {
                    401:     my ($cmd,$server)=@_;
1.838     albertel  402:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  403:     my $answer=subreply($cmd,$server);
1.65      www       404:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  405:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       406:                 " $cmd to $server returned $answer</font>");
                    407:     }
1.1       albertel  408:     return $answer;
                    409: }
                    410: 
                    411: # ----------------------------------------------------------- Send USR1 to lonc
                    412: 
                    413: sub reconlonc {
1.891     albertel  414:     my ($lonid) = @_;
                    415:     my $hostname = &hostname($lonid);
                    416:     if ($lonid) {
                    417: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    418: 	if ($hostname && -e $peerfile) {
                    419: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    420: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    421: 					     Type    => SOCK_STREAM,
                    422: 					     Timeout => 10);
                    423: 	    if ($client) {
                    424: 		print $client ("reset_retries\n");
                    425: 		my $answer=<$client>;
                    426: 		#reset just this one.
                    427: 	    }
                    428: 	}
                    429: 	return;
                    430:     }
                    431: 
1.836     www       432:     &logthis("Trying to reconnect lonc");
1.1       albertel  433:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  434:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  435: 	my $loncpid=<$fh>;
                    436:         chomp($loncpid);
                    437:         if (kill 0 => $loncpid) {
                    438: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    439:             kill USR1 => $loncpid;
                    440:             sleep 1;
1.836     www       441:          } else {
1.12      www       442: 	    &logthis(
1.672     albertel  443:                "<font color=\"blue\">WARNING:".
1.12      www       444:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  445:         }
                    446:     } else {
1.836     www       447: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  448:     }
                    449: }
                    450: 
                    451: # ------------------------------------------------------ Critical communication
1.12      www       452: 
1.1       albertel  453: sub critical {
                    454:     my ($cmd,$server)=@_;
1.838     albertel  455:     unless (&hostname($server)) {
1.672     albertel  456:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       457:                " Critical message to unknown server ($server)</font>");
                    458:         return 'no_such_host';
                    459:     }
1.1       albertel  460:     my $answer=reply($cmd,$server);
                    461:     if ($answer eq 'con_lost') {
                    462: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  463: 	my $answer=reply($cmd,$server);
1.1       albertel  464:         if ($answer eq 'con_lost') {
                    465:             my $now=time;
                    466:             my $middlename=$cmd;
1.5       www       467:             $middlename=substr($middlename,0,16);
1.1       albertel  468:             $middlename=~s/\W//g;
                    469:             my $dfilename=
1.305     www       470:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    471:             $dumpcount++;
1.1       albertel  472:             {
1.448     albertel  473: 		my $dfh;
                    474: 		if (open($dfh,">$dfilename")) {
                    475: 		    print $dfh "$cmd\n"; 
                    476: 		    close($dfh);
                    477: 		}
1.1       albertel  478:             }
                    479:             sleep 2;
                    480:             my $wcmd='';
                    481:             {
1.448     albertel  482: 		my $dfh;
                    483: 		if (open($dfh,"<$dfilename")) {
                    484: 		    $wcmd=<$dfh>; 
                    485: 		    close($dfh);
                    486: 		}
1.1       albertel  487:             }
                    488:             chomp($wcmd);
1.7       www       489:             if ($wcmd eq $cmd) {
1.672     albertel  490: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       491:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  492:                 &logperm("D:$server:$cmd");
                    493: 	        return 'con_delayed';
                    494:             } else {
1.672     albertel  495:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       496:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  497:                 &logperm("F:$server:$cmd");
                    498:                 return 'con_failed';
                    499:             }
                    500:         }
                    501:     }
                    502:     return $answer;
1.405     albertel  503: }
                    504: 
1.755     albertel  505: # ------------------------------------------- check if return value is an error
                    506: 
                    507: sub error {
                    508:     my ($result) = @_;
1.756     albertel  509:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  510: 	if ($2 == 2) { return undef; }
                    511: 	return $1;
                    512:     }
                    513:     return undef;
                    514: }
                    515: 
1.783     albertel  516: sub convert_and_load_session_env {
                    517:     my ($lonidsdir,$handle)=@_;
                    518:     my @profile;
                    519:     {
1.917     albertel  520: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    521: 	if (!$opened) {
1.915     albertel  522: 	    return 0;
                    523: 	}
1.783     albertel  524: 	flock($idf,LOCK_SH);
                    525: 	@profile=<$idf>;
                    526: 	close($idf);
                    527:     }
                    528:     my %temp_env;
                    529:     foreach my $line (@profile) {
1.786     albertel  530: 	if ($line !~ m/=/) {
                    531: 	    return 0;
                    532: 	}
1.783     albertel  533: 	chomp($line);
                    534: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    535: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    536:     }
                    537:     unlink("$lonidsdir/$handle.id");
                    538:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    539: 	    0640)) {
                    540: 	%disk_env = %temp_env;
                    541: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    542: 	untie(%disk_env);
                    543:     }
1.786     albertel  544:     return 1;
1.783     albertel  545: }
                    546: 
1.374     www       547: # ------------------------------------------- Transfer profile into environment
1.780     albertel  548: my $env_loaded;
                    549: sub transfer_profile_to_env {
1.788     albertel  550:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    551:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       552: 
1.720     albertel  553:     if (!defined($lonidsdir)) {
                    554: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    555:     }
                    556:     if (!defined($handle)) {
                    557:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    558:     }
                    559: 
1.786     albertel  560:     my $convert;
                    561:     {
1.917     albertel  562:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    563: 	if (!$opened) {
1.915     albertel  564: 	    return;
                    565: 	}
1.786     albertel  566: 	flock($idf,LOCK_SH);
                    567: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    568: 		&GDBM_READER(),0640)) {
                    569: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    570: 	    untie(%disk_env);
                    571: 	} else {
                    572: 	    $convert = 1;
                    573: 	}
                    574:     }
                    575:     if ($convert) {
                    576: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    577: 	    &logthis("Failed to load session, or convert session.");
                    578: 	}
1.374     www       579:     }
1.783     albertel  580: 
1.786     albertel  581:     my %remove;
1.783     albertel  582:     while ( my $envname = each(%env) ) {
1.433     matthew   583:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    584:             if ($time < time-300) {
1.783     albertel  585:                 $remove{$key}++;
1.433     matthew   586:             }
                    587:         }
                    588:     }
1.783     albertel  589: 
1.619     albertel  590:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  591:     $env_loaded=1;
1.783     albertel  592:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   593:         &delenv($expired_key);
1.374     www       594:     }
1.1       albertel  595: }
                    596: 
1.916     albertel  597: # ---------------------------------------------------- Check for valid session 
                    598: sub check_for_valid_session {
1.1155    raeburn   599:     my ($r,$name) = @_;
1.916     albertel  600:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   601:     if ($name eq '') {
                    602:         $name = 'lonID';
                    603:     }
                    604:     my $lonid=$cookies{$name};
1.916     albertel  605:     return undef if (!$lonid);
                    606: 
                    607:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   608:     my $lonidsdir;
                    609:     if ($name eq 'lonDAV') {
                    610:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    611:     } else {
                    612:         $lonidsdir=$r->dir_config('lonIDsDir');
                    613:     }
1.916     albertel  614:     return undef if (!-e "$lonidsdir/$handle.id");
                    615: 
1.917     albertel  616:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617:     return undef if (!$opened);
1.916     albertel  618: 
                    619:     flock($idf,LOCK_SH);
                    620:     my %disk_env;
                    621:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 	    &GDBM_READER(),0640)) {
                    623: 	return undef;	
                    624:     }
                    625: 
                    626:     if (!defined($disk_env{'user.name'})
                    627: 	|| !defined($disk_env{'user.domain'})) {
                    628: 	return undef;
                    629:     }
                    630:     return $handle;
                    631: }
                    632: 
1.830     albertel  633: sub timed_flock {
                    634:     my ($file,$lock_type) = @_;
                    635:     my $failed=0;
                    636:     eval {
                    637: 	local $SIG{__DIE__}='DEFAULT';
                    638: 	local $SIG{ALRM}=sub {
                    639: 	    $failed=1;
                    640: 	    die("failed lock");
                    641: 	};
                    642: 	alarm(13);
                    643: 	flock($file,$lock_type);
                    644: 	alarm(0);
                    645:     };
                    646:     if ($failed) {
                    647: 	return undef;
                    648:     } else {
                    649: 	return 1;
                    650:     }
                    651: }
                    652: 
1.5       www       653: # ---------------------------------------------------------- Append Environment
                    654: 
                    655: sub appenv {
1.949     raeburn   656:     my ($newenv,$roles) = @_;
                    657:     if (ref($newenv) eq 'HASH') {
                    658:         foreach my $key (keys(%{$newenv})) {
                    659:             my $refused = 0;
                    660: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    661:                 $refused = 1;
                    662:                 if (ref($roles) eq 'ARRAY') {
                    663:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    664:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    665:                         $refused = 0;
                    666:                     }
                    667:                 }
                    668:             }
                    669:             if ($refused) {
                    670:                 &logthis("<font color=\"blue\">WARNING: ".
                    671:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    672:                          .'</font>');
                    673: 	        delete($newenv->{$key});
                    674:             } else {
                    675:                 $env{$key}=$newenv->{$key};
                    676:             }
                    677:         }
                    678:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    679:         if ($opened
                    680: 	    && &timed_flock($env_file,LOCK_EX)
                    681: 	    &&
                    682: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    683: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    684: 	    while (my ($key,$value) = each(%{$newenv})) {
                    685: 	        $disk_env{$key} = $value;
                    686: 	    }
                    687: 	    untie(%disk_env);
1.35      www       688:         }
1.191     harris41  689:     }
1.56      www       690:     return 'ok';
                    691: }
                    692: # ----------------------------------------------------- Delete from Environment
                    693: 
                    694: sub delenv {
1.1104    raeburn   695:     my ($delthis,$regexp,$roles) = @_;
                    696:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    697:         my $refused = 1;
                    698:         if (ref($roles) eq 'ARRAY') {
                    699:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    700:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    701:                 $refused = 0;
                    702:             }
                    703:         }
                    704:         if ($refused) {
                    705:             &logthis("<font color=\"blue\">WARNING: ".
                    706:                      "Attempt to delete from environment ".$delthis);
                    707:             return 'error';
                    708:         }
1.56      www       709:     }
1.917     albertel  710:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    711:     if ($opened
1.915     albertel  712: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  713: 	&&
                    714: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    715: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  716: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   717: 	    if ($regexp) {
                    718:                 if ($key=~/^$delthis/) {
                    719:                     delete($env{$key});
                    720:                     delete($disk_env{$key});
                    721:                 } 
                    722:             } else {
                    723:                 if ($key=~/^\Q$delthis\E/) {
                    724: 		    delete($env{$key});
                    725: 		    delete($disk_env{$key});
                    726: 	        }
                    727:             }
1.448     albertel  728: 	}
1.783     albertel  729: 	untie(%disk_env);
1.5       www       730:     }
                    731:     return 'ok';
1.369     albertel  732: }
                    733: 
1.790     albertel  734: sub get_env_multiple {
                    735:     my ($name) = @_;
                    736:     my @values;
                    737:     if (defined($env{$name})) {
                    738:         # exists is it an array
                    739:         if (ref($env{$name})) {
                    740:             @values=@{ $env{$name} };
                    741:         } else {
                    742:             $values[0]=$env{$name};
                    743:         }
                    744:     }
                    745:     return(@values);
                    746: }
                    747: 
1.958     www       748: # ------------------------------------------------------------------- Locking
                    749: 
                    750: sub set_lock {
                    751:     my ($text)=@_;
                    752:     $locknum++;
                    753:     my $id=$$.'-'.$locknum;
                    754:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    755:              'session.lock.'.$id => $text});
                    756:     return $id;
                    757: }
                    758: 
                    759: sub get_locks {
                    760:     my $num=0;
                    761:     my %texts=();
                    762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    763:        if ($lock=~/\w/) {
                    764:           $num++;
                    765:           $texts{$lock}=$env{'session.lock.'.$lock};
                    766:        }
                    767:    }
                    768:    return ($num,%texts);
                    769: }
                    770: 
                    771: sub remove_lock {
                    772:     my ($id)=@_;
                    773:     my $newlocks='';
                    774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    775:        if (($lock=~/\w/) && ($lock ne $id)) {
                    776:           $newlocks.=','.$lock;
                    777:        }
                    778:     }
                    779:     &appenv({'session.locks' => $newlocks});
                    780:     &delenv('session.lock.'.$id);
                    781: }
                    782: 
                    783: sub remove_all_locks {
                    784:     my $activelocks=$env{'session.locks'};
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if ($lock=~/\w/) {
                    787:           &remove_lock($lock);
                    788:        }
                    789:     }
                    790: }
                    791: 
                    792: 
1.369     albertel  793: # ------------------------------------------ Find out current server userload
                    794: sub userload {
                    795:     my $numusers=0;
                    796:     {
                    797: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    798: 	my $filename;
                    799: 	my $curtime=time;
                    800: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  801: 	    next if ($filename eq '.' || $filename eq '..');
                    802: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  803: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  804: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  805: 	}
                    806: 	closedir(LONIDS);
                    807:     }
                    808:     my $userloadpercent=0;
                    809:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    810:     if ($maxuserload) {
1.371     albertel  811: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  812:     }
1.372     albertel  813:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  814:     return $userloadpercent;
1.283     www       815: }
                    816: 
1.1       albertel  817: # ------------------------------ Find server with least workload from spare.tab
1.11      www       818: 
1.1       albertel  819: sub spareserver {
1.1083    raeburn   820:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  821:     my $spare_server;
1.370     albertel  822:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  823:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    824:                                                      :  $userloadpercent;
1.1083    raeburn   825:     my ($uint_dom,$remotesessions);
                    826:     if (($udom ne '') && (&domain($udom) ne '')) {
                    827:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    828:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    829:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    830:         $remotesessions = $udomdefaults{'remotesessions'};
                    831:     }
1.1123    raeburn   832:     my $spareshash = &this_host_spares($udom);
                    833:     if (ref($spareshash) eq 'HASH') {
                    834:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    835:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    836:                 if ($uint_dom) {
                    837:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    838:                                                  $try_server));
                    839:                 }
                    840: 	        ($spare_server, $lowest_load) =
                    841: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    842:             }
1.1083    raeburn   843:         }
1.784     albertel  844: 
1.1123    raeburn   845:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    846: 
                    847:         if (!$found_server) {
                    848:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    849: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    850:                     if ($uint_dom) {
                    851:                         next unless (&spare_can_host($udom,$uint_dom,
                    852:                                                      $remotesessions,$try_server));
                    853:                     }
                    854: 	            ($spare_server, $lowest_load) =
                    855: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:                 }
                    857: 	    }
                    858:         }
1.784     albertel  859:     }
                    860: 
                    861:     if (!$want_server_name) {
1.968     raeburn   862:         my $protocol = 'http';
                    863:         if ($protocol{$spare_server} eq 'https') {
                    864:             $protocol = $protocol{$spare_server};
                    865:         }
1.1001    raeburn   866:         if (defined($spare_server)) {
                    867:             my $hostname = &hostname($spare_server);
1.1083    raeburn   868:             if (defined($hostname)) {
1.1001    raeburn   869: 	        $spare_server = $protocol.'://'.$hostname;
                    870:             }
                    871:         }
1.784     albertel  872:     }
                    873:     return $spare_server;
                    874: }
                    875: 
                    876: sub compare_server_load {
                    877:     my ($try_server, $spare_server, $lowest_load) = @_;
                    878: 
                    879:     my $loadans     = &reply('load',    $try_server);
                    880:     my $userloadans = &reply('userload',$try_server);
                    881: 
                    882:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   883: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  884:     }
                    885: 
                    886:     my $load;
                    887:     if ($loadans =~ /\d/) {
                    888: 	if ($userloadans =~ /\d/) {
                    889: 	    #both are numbers, pick the bigger one
                    890: 	    $load = ($loadans > $userloadans) ? $loadans 
                    891: 		                              : $userloadans;
1.411     albertel  892: 	} else {
1.784     albertel  893: 	    $load = $loadans;
1.411     albertel  894: 	}
1.784     albertel  895:     } else {
                    896: 	$load = $userloadans;
                    897:     }
                    898: 
                    899:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    900: 	$spare_server = $try_server;
                    901: 	$lowest_load  = $load;
1.370     albertel  902:     }
1.784     albertel  903:     return ($spare_server,$lowest_load);
1.202     matthew   904: }
1.914     albertel  905: 
                    906: # --------------------------- ask offload servers if user already has a session
                    907: sub find_existing_session {
                    908:     my ($udom,$uname) = @_;
1.1123    raeburn   909:     my $spareshash = &this_host_spares($udom);
                    910:     if (ref($spareshash) eq 'HASH') {
                    911:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    912:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    913:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    914:             }
                    915:         }
                    916:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    917:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    918:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    919:             }
                    920:         }
1.914     albertel  921:     }
                    922:     return;
                    923: }
                    924: 
                    925: # -------------------------------- ask if server already has a session for user
                    926: sub has_user_session {
                    927:     my ($lonid,$udom,$uname) = @_;
                    928:     my $result = &reply(join(':','userhassession',
                    929: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    930:     return 1 if ($result eq 'ok');
                    931: 
                    932:     return 0;
                    933: }
                    934: 
1.1076    raeburn   935: # --------- determine least loaded server in a user's domain which allows login
                    936: 
                    937: sub choose_server {
1.1115    raeburn   938:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   939:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   940:     my %servers = &get_servers($udom);
1.1076    raeburn   941:     my $lowest_load = 30000;
1.1151    raeburn   942:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   943:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   944:         my $loginvia;
                    945:         if ($checkloginvia) {
                    946:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   947:             if ($loginvia) {
                    948:                 my ($server,$path) = split(/:/,$loginvia);
                    949:                 ($login_host, $lowest_load) =
                    950:                     &compare_server_load($server, $login_host, $lowest_load);
                    951:                 if ($login_host eq $server) {
                    952:                     $portal_path = $path;
1.1151    raeburn   953:                     $isredirect = 1;
1.1116    raeburn   954:                 }
                    955:             } else {
                    956:                 ($login_host, $lowest_load) =
                    957:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    958:                 if ($login_host eq $lonhost) {
                    959:                     $portal_path = '';
1.1151    raeburn   960:                     $isredirect = ''; 
1.1116    raeburn   961:                 }
                    962:             }
                    963:         } else {
1.1076    raeburn   964:             ($login_host, $lowest_load) =
1.1116    raeburn   965:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   966:         }
                    967:     }
                    968:     if ($login_host ne '') {
1.1116    raeburn   969:         $hostname = &hostname($login_host);
1.1076    raeburn   970:     }
1.1151    raeburn   971:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   972: }
                    973: 
1.202     matthew   974: # --------------------------------------------- Try to change a user's password
                    975: 
                    976: sub changepass {
1.799     raeburn   977:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   978:     $currentpass = &escape($currentpass);
                    979:     $newpass     = &escape($newpass);
1.1030    raeburn   980:     my $lonhost = $perlvar{'lonHostID'};
                    981:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   982: 		       $server);
                    983:     if (! $answer) {
                    984: 	&logthis("No reply on password change request to $server ".
                    985: 		 "by $uname in domain $udom.");
                    986:     } elsif ($answer =~ "^ok") {
                    987:         &logthis("$uname in $udom successfully changed their password ".
                    988: 		 "on $server.");
                    989:     } elsif ($answer =~ "^pwchange_failure") {
                    990: 	&logthis("$uname in $udom was unable to change their password ".
                    991: 		 "on $server.  The action was blocked by either lcpasswd ".
                    992: 		 "or pwchange");
                    993:     } elsif ($answer =~ "^non_authorized") {
                    994:         &logthis("$uname in $udom did not get their password correct when ".
                    995: 		 "attempting to change it on $server.");
                    996:     } elsif ($answer =~ "^auth_mode_error") {
                    997:         &logthis("$uname in $udom attempted to change their password despite ".
                    998: 		 "not being locally or internally authenticated on $server.");
                    999:     } elsif ($answer =~ "^unknown_user") {
                   1000:         &logthis("$uname in $udom attempted to change their password ".
                   1001: 		 "on $server but were unable to because $server is not ".
                   1002: 		 "their home server.");
                   1003:     } elsif ($answer =~ "^refused") {
                   1004: 	&logthis("$server refused to change $uname in $udom password because ".
                   1005: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1006:     } elsif ($answer =~ "invalid_client") {
                   1007:         &logthis("$server refused to change $uname in $udom password because ".
                   1008:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1009:     }
                   1010:     return $answer;
1.1       albertel 1011: }
                   1012: 
1.169     harris41 1013: # ----------------------- Try to determine user's current authentication scheme
                   1014: 
                   1015: sub queryauthenticate {
                   1016:     my ($uname,$udom)=@_;
1.456     albertel 1017:     my $uhome=&homeserver($uname,$udom);
                   1018:     if (!$uhome) {
                   1019: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1020: 	return 'no_host';
                   1021:     }
                   1022:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1023:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1024: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1025:     }
1.456     albertel 1026:     return $answer;
1.169     harris41 1027: }
                   1028: 
1.1       albertel 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1030: 
1.1       albertel 1031: sub authenticate {
1.1073    raeburn  1032:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1033:     $upass=&escape($upass);
                   1034:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1035:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1036:     my $newhome;
1.836     www      1037:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1038: # Maybe the machine was offline and only re-appeared again recently?
                   1039:         &reconlonc();
                   1040: # One more
1.952     raeburn  1041: 	$uhome=&homeserver($uname,$udom,1);
                   1042:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1043:             if (defined(&domain($udom,'primary'))) {
                   1044:                 $newhome=&domain($udom,'primary');
                   1045:             }
                   1046:             if ($newhome ne '') {
                   1047:                 $uhome = $newhome;
                   1048:             }
                   1049:         }
1.836     www      1050: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1051: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1052: 	    return 'no_host';
                   1053:         }
1.1       albertel 1054:     }
1.1073    raeburn  1055:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1056:     if ($answer eq 'authorized') {
1.952     raeburn  1057:         if ($newhome) {
                   1058:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1059:             return 'no_account_on_host'; 
                   1060:         } else {
                   1061:             &logthis("User $uname at $udom authorized by $uhome");
                   1062:             return $uhome;
                   1063:         }
1.471     albertel 1064:     }
                   1065:     if ($answer eq 'non_authorized') {
                   1066: 	&logthis("User $uname at $udom rejected by $uhome");
                   1067: 	return 'no_host'; 
1.9       www      1068:     }
1.471     albertel 1069:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1070:     return 'no_host';
                   1071: }
                   1072: 
1.1073    raeburn  1073: sub can_host_session {
1.1074    raeburn  1074:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1075:     my $canhost = 1;
1.1074    raeburn  1076:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1077:     if (ref($remotesessions) eq 'HASH') {
                   1078:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1079:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1080:                 $canhost = 0;
                   1081:             } else {
                   1082:                 $canhost = 1;
                   1083:             }
                   1084:         }
                   1085:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1087:                 $canhost = 1;
                   1088:             } else {
                   1089:                 $canhost = 0;
                   1090:             }
                   1091:         }
                   1092:         if ($canhost) {
                   1093:             if ($remotesessions->{'version'} ne '') {
                   1094:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1095:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1096:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1097:                         my $major = $1;
                   1098:                         my $minor = $2;
                   1099:                         if (($major < $reqmajor ) ||
                   1100:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1101:                             $canhost = 0;
                   1102:                         }
                   1103:                     } else {
                   1104:                         $canhost = 0;
                   1105:                     }
                   1106:                 }
                   1107:             }
                   1108:         }
                   1109:     }
                   1110:     if ($canhost) {
                   1111:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1112:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1113:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1114:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1115:                 if (($uint_dom ne '') && 
                   1116:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1117:                     $canhost = 0;
                   1118:                 } else {
                   1119:                     $canhost = 1;
                   1120:                 }
                   1121:             }
                   1122:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1123:                 if (($uint_dom ne '') && 
                   1124:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1125:                     $canhost = 1;
                   1126:                 } else {
                   1127:                     $canhost = 0;
                   1128:                 }
                   1129:             }
                   1130:         }
                   1131:     }
                   1132:     return $canhost;
                   1133: }
                   1134: 
1.1083    raeburn  1135: sub spare_can_host {
                   1136:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1137:     my $canhost=1;
                   1138:     my @intdoms;
                   1139:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1140:     if (ref($internet_names) eq 'ARRAY') {
                   1141:         @intdoms = @{$internet_names};
                   1142:     }
                   1143:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1144:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1145:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1146:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1147:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1148:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1149:                                      $remotesessions,
                   1150:                                      $defdomdefaults{'hostedsessions'});
                   1151:     }
                   1152:     return $canhost;
                   1153: }
                   1154: 
1.1123    raeburn  1155: sub this_host_spares {
                   1156:     my ($dom) = @_;
1.1126    raeburn  1157:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1158:     my @hosts = &current_machine_ids();
                   1159:     foreach my $lonhost (@hosts) {
                   1160:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1161:             $dom_in_use = $dom;
                   1162:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1163:             last;
                   1164:         }
                   1165:     }
1.1126    raeburn  1166:     if ($dom_in_use ne '') {
                   1167:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1168:     }
                   1169:     if (ref($result) ne 'HASH') {
                   1170:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1171:         $dom_in_use = &host_domain($lonhost_in_use);
                   1172:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1173:         if (ref($result) ne 'HASH') {
                   1174:             $result = \%spareid;
                   1175:         }
                   1176:     }
                   1177:     return $result;
                   1178: }
                   1179: 
                   1180: sub spares_for_offload  {
                   1181:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1182:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1183:     if (defined($cached)) {
                   1184:         return $result;
                   1185:     } else {
1.1126    raeburn  1186:         my $cachetime = 60*60*24;
                   1187:         my %domconfig =
                   1188:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1189:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1190:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1191:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1192:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1193:                 }
                   1194:             }
                   1195:         }
                   1196:     }
1.1126    raeburn  1197:     return;
1.1123    raeburn  1198: }
                   1199: 
1.1129    raeburn  1200: sub get_lonbalancer_config {
                   1201:     my ($servers) = @_;
                   1202:     my ($currbalancer,$currtargets);
                   1203:     if (ref($servers) eq 'HASH') {
                   1204:         foreach my $server (keys(%{$servers})) {
                   1205:             my %what = (
                   1206:                          spareid => 1,
                   1207:                          perlvar => 1,
                   1208:                        );
                   1209:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1210:             if ($result eq 'ok') {
                   1211:                 if (ref($returnhash) eq 'HASH') {
                   1212:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1213:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1214:                             $currbalancer = $server;
                   1215:                             $currtargets = {};
                   1216:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1217:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1218:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1219:                                 }
                   1220:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1221:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1222:                                 }
                   1223:                             }
                   1224:                             last;
                   1225:                         }
                   1226:                     }
                   1227:                 }
                   1228:             }
                   1229:         }
                   1230:     }
                   1231:     return ($currbalancer,$currtargets);
                   1232: }
                   1233: 
                   1234: sub check_loadbalancing {
                   1235:     my ($uname,$udom) = @_;
                   1236:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1237:         $offloadto,$otherserver);
                   1238:     my $lonhost = $perlvar{'lonHostID'};
                   1239:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1240:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1241:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1242:     my $serverhomedom = &host_domain($lonhost);
                   1243: 
                   1244:     my $cachetime = 60*60*24;
                   1245: 
                   1246:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1247:         $dom_in_use = $udom;
                   1248:         $homeintdom = 1;
                   1249:     } else {
                   1250:         $dom_in_use = $serverhomedom;
                   1251:     }
                   1252:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1253:     unless (defined($cached)) {
                   1254:         my %domconfig =
                   1255:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1256:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1257:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1258:         }
                   1259:     }
                   1260:     if (ref($result) eq 'HASH') {
                   1261:         my $currbalancer = $result->{'lonhost'};
                   1262:         my $currtargets = $result->{'targets'};
                   1263:         my $currrules = $result->{'rules'};
                   1264:         if ($currbalancer ne '') {
                   1265:             my @hosts = &current_machine_ids();
                   1266:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1267:                 $is_balancer = 1;
                   1268:             }
                   1269:         }
                   1270:         if ($is_balancer) {
                   1271:             if (ref($currrules) eq 'HASH') {
                   1272:                 if ($homeintdom) {
                   1273:                     if ($uname ne '') {
                   1274:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1275:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1276:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1277:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1278:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1279:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1280:                             }
                   1281:                         }
                   1282:                         if ($rule_in_effect eq '') {
                   1283:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1284:                             if ($userenv{'inststatus'} ne '') {
                   1285:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1286:                                 my ($othertitle,$usertypes,$types) =
                   1287:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1288:                                 if (ref($types) eq 'ARRAY') {
                   1289:                                     foreach my $type (@{$types}) {
                   1290:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1291:                                             if (exists($currrules->{$type})) {
                   1292:                                                 $rule_in_effect = $currrules->{$type};
                   1293:                                             }
                   1294:                                         }
                   1295:                                     }
                   1296:                                 }
                   1297:                             } else {
                   1298:                                 if (exists($currrules->{'default'})) {
                   1299:                                     $rule_in_effect = $currrules->{'default'};
                   1300:                                 }
                   1301:                             }
                   1302:                         }
                   1303:                     } else {
                   1304:                         if (exists($currrules->{'default'})) {
                   1305:                             $rule_in_effect = $currrules->{'default'};
                   1306:                         }
                   1307:                     }
                   1308:                 } else {
                   1309:                     if ($currrules->{'_LC_external'} ne '') {
                   1310:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1311:                     }
                   1312:                 }
                   1313:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1314:                                                        $uname,$udom);
                   1315:             }
                   1316:         }
                   1317:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1318:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1319:         unless (defined($cached)) {
                   1320:             my %domconfig =
                   1321:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1322:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1323:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1324:             }
                   1325:         }
                   1326:         if (ref($result) eq 'HASH') {
                   1327:             my $currbalancer = $result->{'lonhost'};
                   1328:             my $currtargets = $result->{'targets'};
                   1329:             my $currrules = $result->{'rules'};
                   1330: 
                   1331:             if ($currbalancer eq $lonhost) {
                   1332:                 $is_balancer = 1;
                   1333:                 if (ref($currrules) eq 'HASH') {
                   1334:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1335:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1336:                     }
                   1337:                 }
                   1338:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1339:                                                        $uname,$udom);
                   1340:             }
                   1341:         } else {
                   1342:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1343:                 $is_balancer = 1;
                   1344:                 $offloadto = &this_host_spares($dom_in_use);
                   1345:             }
                   1346:         }
                   1347:     } else {
                   1348:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1349:             $is_balancer = 1;
                   1350:             $offloadto = &this_host_spares($dom_in_use);
                   1351:         }
                   1352:     }
                   1353:     my $lowest_load = 30000;
                   1354:     if (ref($offloadto) eq 'HASH') {
                   1355:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1356:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1357:                 ($otherserver,$lowest_load) =
                   1358:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1359:             }
                   1360:         }
                   1361:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1362: 
                   1363:         if (!$found_server) {
                   1364:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1365:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1366:                     ($otherserver,$lowest_load) =
                   1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1368:                 }
                   1369:             }
                   1370:         }
                   1371:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1372:         if (@{$offloadto} == 1) {
                   1373:             $otherserver = $offloadto->[0];
                   1374:         } elsif (@{$offloadto} > 1) {
                   1375:             foreach my $try_server (@{$offloadto}) {
                   1376:                 ($otherserver,$lowest_load) =
                   1377:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1378:             }
                   1379:         }
                   1380:     }
                   1381:     return ($is_balancer,$otherserver);
                   1382: }
                   1383: 
                   1384: sub get_loadbalancer_targets {
                   1385:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1386:     my $offloadto;
                   1387:     if ($rule_in_effect eq '') {
                   1388:         $offloadto = $currtargets;
                   1389:     } else {
                   1390:         if ($rule_in_effect eq 'homeserver') {
                   1391:             my $homeserver = &homeserver($uname,$udom);
                   1392:             if ($homeserver ne 'no_host') {
                   1393:                 $offloadto = [$homeserver];
                   1394:             }
                   1395:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1396:             my %domconfig =
                   1397:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1398:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1399:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1400:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1401:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1402:                     }
                   1403:                 }
                   1404:             } else {
                   1405:                 my %servers = &dom_servers($udom);
                   1406:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1407:                 if (&hostname($remotebalancer) ne '') {
                   1408:                     $offloadto = [$remotebalancer];
                   1409:                 }
                   1410:             }
                   1411:         } elsif (&hostname($rule_in_effect) ne '') {
                   1412:             $offloadto = [$rule_in_effect];
                   1413:         }
                   1414:     }
                   1415:     return $offloadto;
                   1416: }
                   1417: 
1.1127    raeburn  1418: sub internet_dom_servers {
                   1419:     my ($dom) = @_;
                   1420:     my (%uniqservers,%servers);
                   1421:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1422:     my @machinedoms = &machine_domains($primaryserver);
                   1423:     foreach my $mdom (@machinedoms) {
                   1424:         my %currservers = %servers;
                   1425:         my %server = &get_servers($mdom);
                   1426:         %servers = (%currservers,%server);
                   1427:     }
                   1428:     my %by_hostname;
                   1429:     foreach my $id (keys(%servers)) {
                   1430:         push(@{$by_hostname{$servers{$id}}},$id);
                   1431:     }
                   1432:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1433:         if (@{$by_hostname{$hostname}} > 1) {
                   1434:             my $match = 0;
                   1435:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1436:                 if (&host_domain($id) eq $dom) {
                   1437:                     $uniqservers{$id} = $hostname;
                   1438:                     $match = 1;
                   1439:                 }
                   1440:             }
                   1441:             unless ($match) {
                   1442:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1443:             }
                   1444:         } else {
                   1445:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1446:         }
                   1447:     }
                   1448:     return %uniqservers;
                   1449: }
                   1450: 
1.1       albertel 1451: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1452: 
1.599     albertel 1453: my %homecache;
1.1       albertel 1454: sub homeserver {
1.230     stredwic 1455:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1456:     my $index="$uname:$udom";
1.426     albertel 1457: 
1.599     albertel 1458:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1459: 
                   1460:     my %servers = &get_servers($udom,'library');
                   1461:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1462:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1463: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1464: 
                   1465: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1466: 	if ($answer eq 'found') {
                   1467: 	    delete($badServerCache{$tryserver}); 
                   1468: 	    return $homecache{$index}=$tryserver;
                   1469: 	} elsif ($answer eq 'no_host') {
                   1470: 	    $badServerCache{$tryserver}=1;
                   1471: 	}
1.1       albertel 1472:     }    
                   1473:     return 'no_host';
1.70      www      1474: }
                   1475: 
                   1476: # ------------------------------------- Find the usernames behind a list of IDs
                   1477: 
                   1478: sub idget {
                   1479:     my ($udom,@ids)=@_;
                   1480:     my %returnhash=();
                   1481:     
1.841     albertel 1482:     my %servers = &get_servers($udom,'library');
                   1483:     foreach my $tryserver (keys(%servers)) {
                   1484: 	my $idlist=join('&',@ids);
                   1485: 	$idlist=~tr/A-Z/a-z/; 
                   1486: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1487: 	my @answer=();
                   1488: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1489: 	    @answer=split(/\&/,$reply);
                   1490: 	}                    ;
                   1491: 	my $i;
                   1492: 	for ($i=0;$i<=$#ids;$i++) {
                   1493: 	    if ($answer[$i]) {
                   1494: 		$returnhash{$ids[$i]}=$answer[$i];
                   1495: 	    } 
                   1496: 	}
                   1497:     } 
1.70      www      1498:     return %returnhash;
                   1499: }
                   1500: 
                   1501: # ------------------------------------- Find the IDs behind a list of usernames
                   1502: 
                   1503: sub idrget {
                   1504:     my ($udom,@unames)=@_;
                   1505:     my %returnhash=();
1.800     albertel 1506:     foreach my $uname (@unames) {
                   1507:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1508:     }
1.70      www      1509:     return %returnhash;
                   1510: }
                   1511: 
                   1512: # ------------------------------- Store away a list of names and associated IDs
                   1513: 
                   1514: sub idput {
                   1515:     my ($udom,%ids)=@_;
                   1516:     my %servers=();
1.800     albertel 1517:     foreach my $uname (keys(%ids)) {
                   1518: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1519:         my $uhom=&homeserver($uname,$udom);
1.70      www      1520:         if ($uhom ne 'no_host') {
1.800     albertel 1521:             my $id=&escape($ids{$uname});
1.70      www      1522:             $id=~tr/A-Z/a-z/;
1.800     albertel 1523:             my $esc_unam=&escape($uname);
1.70      www      1524: 	    if ($servers{$uhom}) {
1.800     albertel 1525: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1526:             } else {
1.800     albertel 1527:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1528:             }
                   1529:         }
1.191     harris41 1530:     }
1.800     albertel 1531:     foreach my $server (keys(%servers)) {
                   1532:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1533:     }
1.344     www      1534: }
                   1535: 
1.1023    raeburn  1536: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1537: sub dump_dom {
1.1023    raeburn  1538:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1539:     if (!$udom) {
                   1540:         $udom=$env{'user.domain'};
                   1541:     }
                   1542:     my %returnhash;
1.1023    raeburn  1543:     if ($udom) {
                   1544:         my $uname = &get_domainconfiguser($udom);
                   1545:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1546:     }
                   1547:     return %returnhash;
                   1548: }
                   1549: 
1.1023    raeburn  1550: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1551: 
                   1552: sub get_dom {
1.860     raeburn  1553:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1554:     my $items='';
                   1555:     foreach my $item (@$storearr) {
                   1556:         $items.=&escape($item).'&';
                   1557:     }
                   1558:     $items=~s/\&$//;
1.860     raeburn  1559:     if (!$udom) {
                   1560:         $udom=$env{'user.domain'};
                   1561:         if (defined(&domain($udom,'primary'))) {
                   1562:             $uhome=&domain($udom,'primary');
                   1563:         } else {
1.874     albertel 1564:             undef($uhome);
1.860     raeburn  1565:         }
                   1566:     } else {
                   1567:         if (!$uhome) {
                   1568:             if (defined(&domain($udom,'primary'))) {
                   1569:                 $uhome=&domain($udom,'primary');
                   1570:             }
                   1571:         }
                   1572:     }
                   1573:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1574:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1575:         my %returnhash;
1.875     albertel 1576:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1577:             return %returnhash;
                   1578:         }
1.806     raeburn  1579:         my @pairs=split(/\&/,$rep);
                   1580:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1581:             return @pairs;
                   1582:         }
                   1583:         my $i=0;
                   1584:         foreach my $item (@$storearr) {
                   1585:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1586:             $i++;
                   1587:         }
                   1588:         return %returnhash;
                   1589:     } else {
1.880     banghart 1590:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1591:     }
                   1592: }
                   1593: 
                   1594: # -------------------------------------------- put items in domain db files 
                   1595: 
                   1596: sub put_dom {
1.860     raeburn  1597:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1598:     if (!$udom) {
                   1599:         $udom=$env{'user.domain'};
                   1600:         if (defined(&domain($udom,'primary'))) {
                   1601:             $uhome=&domain($udom,'primary');
                   1602:         } else {
1.874     albertel 1603:             undef($uhome);
1.860     raeburn  1604:         }
                   1605:     } else {
                   1606:         if (!$uhome) {
                   1607:             if (defined(&domain($udom,'primary'))) {
                   1608:                 $uhome=&domain($udom,'primary');
                   1609:             }
                   1610:         }
                   1611:     } 
                   1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1613:         my $items='';
                   1614:         foreach my $item (keys(%$storehash)) {
                   1615:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1616:         }
                   1617:         $items=~s/\&$//;
                   1618:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1619:     } else {
1.860     raeburn  1620:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1621:     }
                   1622: }
                   1623: 
1.1023    raeburn  1624: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1625: sub newput_dom {
1.1023    raeburn  1626:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1627:     my $result;
                   1628:     if (!$udom) {
                   1629:         $udom=$env{'user.domain'};
                   1630:     }
1.1023    raeburn  1631:     if ($udom) {
                   1632:         my $uname = &get_domainconfiguser($udom);
                   1633:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1634:     }
                   1635:     return $result;
                   1636: }
                   1637: 
1.1023    raeburn  1638: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1639: sub del_dom {
1.1023    raeburn  1640:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1641:     if (ref($storearr) eq 'ARRAY') {
                   1642:         if (!$udom) {
                   1643:             $udom=$env{'user.domain'};
                   1644:         }
1.1023    raeburn  1645:         if ($udom) {
                   1646:             my $uname = &get_domainconfiguser($udom); 
                   1647:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1648:         }
                   1649:     }
                   1650: }
                   1651: 
1.1023    raeburn  1652: # ----------------------------------construct domainconfig user for a domain 
                   1653: sub get_domainconfiguser {
                   1654:     my ($udom) = @_;
                   1655:     return $udom.'-domainconfig';
                   1656: }
                   1657: 
1.837     raeburn  1658: sub retrieve_inst_usertypes {
                   1659:     my ($udom) = @_;
                   1660:     my (%returnhash,@order);
1.989     raeburn  1661:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1662:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1663:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1664:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1665:         @order = @{$domdefs{'inststatusorder'}};
                   1666:     } else {
                   1667:         if (defined(&domain($udom,'primary'))) {
                   1668:             my $uhome=&domain($udom,'primary');
                   1669:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1670:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1671:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1672:                 return (\%returnhash,\@order);
                   1673:             }
                   1674:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1675:             my @pairs=split(/\&/,$hashitems);
                   1676:             foreach my $item (@pairs) {
                   1677:                 my ($key,$value)=split(/=/,$item,2);
                   1678:                 $key = &unescape($key);
                   1679:                 next if ($key =~ /^error: 2 /);
                   1680:                 $returnhash{$key}=&thaw_unescape($value);
                   1681:             }
                   1682:             my @esc_order = split(/\&/,$orderitems);
                   1683:             foreach my $item (@esc_order) {
                   1684:                 push(@order,&unescape($item));
                   1685:             }
                   1686:         } else {
                   1687:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1688:         }
                   1689:     }
                   1690:     return (\%returnhash,\@order);
                   1691: }
                   1692: 
1.868     raeburn  1693: sub is_domainimage {
                   1694:     my ($url) = @_;
                   1695:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1696:         if (&domain($1) ne '') {
                   1697:             return '1';
                   1698:         }
                   1699:     }
                   1700:     return;
                   1701: }
                   1702: 
1.899     raeburn  1703: sub inst_directory_query {
                   1704:     my ($srch) = @_;
                   1705:     my $udom = $srch->{'srchdomain'};
                   1706:     my %results;
                   1707:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1708:     my $outcome;
1.899     raeburn  1709:     if ($homeserver ne '') {
1.904     albertel 1710: 	my $queryid=&reply("querysend:instdirsearch:".
                   1711: 			   &escape($srch->{'srchby'}).':'.
                   1712: 			   &escape($srch->{'srchterm'}).':'.
                   1713: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1714: 	my $host=&hostname($homeserver);
                   1715: 	if ($queryid !~/^\Q$host\E\_/) {
                   1716: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1717: 	    return;
                   1718: 	}
                   1719: 	my $response = &get_query_reply($queryid);
                   1720: 	my $maxtries = 5;
                   1721: 	my $tries = 1;
                   1722: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1723: 	    $response = &get_query_reply($queryid);
                   1724: 	    $tries ++;
                   1725: 	}
                   1726: 
                   1727:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1728:             if ($response eq 'unavailable') {
                   1729:                 $outcome = $response;
                   1730:             } else {
                   1731:                 $outcome = 'ok';
                   1732:                 my @matches = split(/\n/,$response);
                   1733:                 foreach my $match (@matches) {
                   1734:                     my ($key,$value) = split(/=/,$match);
                   1735:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1736:                 }
1.899     raeburn  1737:             }
                   1738:         }
                   1739:     }
1.909     raeburn  1740:     return ($outcome,%results);
1.899     raeburn  1741: }
                   1742: 
                   1743: sub usersearch {
                   1744:     my ($srch) = @_;
                   1745:     my $dom = $srch->{'srchdomain'};
                   1746:     my %results;
                   1747:     my %libserv = &all_library();
                   1748:     my $query = 'usersearch';
                   1749:     foreach my $tryserver (keys(%libserv)) {
                   1750:         if (&host_domain($tryserver) eq $dom) {
                   1751:             my $host=&hostname($tryserver);
                   1752:             my $queryid=
1.911     raeburn  1753:                 &reply("querysend:".&escape($query).':'.
                   1754:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1755:                        &escape($srch->{'srchtype'}).':'.
                   1756:                        &escape($srch->{'srchterm'}),$tryserver);
                   1757:             if ($queryid !~/^\Q$host\E\_/) {
                   1758:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1759:                 next;
1.899     raeburn  1760:             }
                   1761:             my $reply = &get_query_reply($queryid);
                   1762:             my $maxtries = 1;
                   1763:             my $tries = 1;
                   1764:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1765:                 $reply = &get_query_reply($queryid);
                   1766:                 $tries ++;
                   1767:             }
                   1768:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1769:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1770:             } else {
1.911     raeburn  1771:                 my @matches;
                   1772:                 if ($reply =~ /\n/) {
                   1773:                     @matches = split(/\n/,$reply);
                   1774:                 } else {
                   1775:                     @matches = split(/\&/,$reply);
                   1776:                 }
1.899     raeburn  1777:                 foreach my $match (@matches) {
                   1778:                     my ($uname,$udom,%userhash);
1.911     raeburn  1779:                     foreach my $entry (split(/:/,$match)) {
                   1780:                         my ($key,$value) =
                   1781:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1782:                         $userhash{$key} = $value;
                   1783:                         if ($key eq 'username') {
                   1784:                             $uname = $value;
                   1785:                         } elsif ($key eq 'domain') {
                   1786:                             $udom = $value;
1.911     raeburn  1787:                         }
1.899     raeburn  1788:                     }
                   1789:                     $results{$uname.':'.$udom} = \%userhash;
                   1790:                 }
                   1791:             }
                   1792:         }
                   1793:     }
                   1794:     return %results;
                   1795: }
                   1796: 
1.912     raeburn  1797: sub get_instuser {
                   1798:     my ($udom,$uname,$id) = @_;
                   1799:     my $homeserver = &domain($udom,'primary');
                   1800:     my ($outcome,%results);
                   1801:     if ($homeserver ne '') {
                   1802:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1803:                            &escape($id).':'.&escape($udom),$homeserver);
                   1804:         my $host=&hostname($homeserver);
                   1805:         if ($queryid !~/^\Q$host\E\_/) {
                   1806:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1807:             return;
                   1808:         }
                   1809:         my $response = &get_query_reply($queryid);
                   1810:         my $maxtries = 5;
                   1811:         my $tries = 1;
                   1812:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1813:             $response = &get_query_reply($queryid);
                   1814:             $tries ++;
                   1815:         }
                   1816:         if (!&error($response) && $response ne 'refused') {
                   1817:             if ($response eq 'unavailable') {
                   1818:                 $outcome = $response;
                   1819:             } else {
                   1820:                 $outcome = 'ok';
                   1821:                 my @matches = split(/\n/,$response);
                   1822:                 foreach my $match (@matches) {
                   1823:                     my ($key,$value) = split(/=/,$match);
                   1824:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1825:                 }
                   1826:             }
                   1827:         }
                   1828:     }
                   1829:     my %userinfo;
                   1830:     if (ref($results{$uname}) eq 'HASH') {
                   1831:         %userinfo = %{$results{$uname}};
                   1832:     } 
                   1833:     return ($outcome,%userinfo);
                   1834: }
                   1835: 
                   1836: sub inst_rulecheck {
1.923     raeburn  1837:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1838:     my %returnhash;
                   1839:     if ($udom ne '') {
                   1840:         if (ref($rules) eq 'ARRAY') {
                   1841:             @{$rules} = map {&escape($_);} (@{$rules});
                   1842:             my $rulestr = join(':',@{$rules});
                   1843:             my $homeserver=&domain($udom,'primary');
                   1844:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1845:                 my $response;
                   1846:                 if ($item eq 'username') {                
                   1847:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1848:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1849:                                               $homeserver));
1.923     raeburn  1850:                 } elsif ($item eq 'id') {
                   1851:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1852:                                               ':'.&escape($id).':'.$rulestr,
                   1853:                                               $homeserver));
1.945     raeburn  1854:                 } elsif ($item eq 'selfcreate') {
                   1855:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1856:                                                &escape($udom).':'.&escape($uname).
                   1857:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1858:                 }
1.912     raeburn  1859:                 if ($response ne 'refused') {
                   1860:                     my @pairs=split(/\&/,$response);
                   1861:                     foreach my $item (@pairs) {
                   1862:                         my ($key,$value)=split(/=/,$item,2);
                   1863:                         $key = &unescape($key);
                   1864:                         next if ($key =~ /^error: 2 /);
                   1865:                         $returnhash{$key}=&thaw_unescape($value);
                   1866:                     }
                   1867:                 }
                   1868:             }
                   1869:         }
                   1870:     }
                   1871:     return %returnhash;
                   1872: }
                   1873: 
                   1874: sub inst_userrules {
1.923     raeburn  1875:     my ($udom,$check) = @_;
1.912     raeburn  1876:     my (%ruleshash,@ruleorder);
                   1877:     if ($udom ne '') {
                   1878:         my $homeserver=&domain($udom,'primary');
                   1879:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1880:             my $response;
                   1881:             if ($check eq 'id') {
                   1882:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1883:                                  $homeserver);
1.943     raeburn  1884:             } elsif ($check eq 'email') {
                   1885:                 $response=&reply('instemailrules:'.&escape($udom),
                   1886:                                  $homeserver);
1.923     raeburn  1887:             } else {
                   1888:                 $response=&reply('instuserrules:'.&escape($udom),
                   1889:                                  $homeserver);
                   1890:             }
1.912     raeburn  1891:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1892:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1893:                 ($response ne 'no_such_host')) {
                   1894:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1895:                 my @pairs=split(/\&/,$hashitems);
                   1896:                 foreach my $item (@pairs) {
                   1897:                     my ($key,$value)=split(/=/,$item,2);
                   1898:                     $key = &unescape($key);
                   1899:                     next if ($key =~ /^error: 2 /);
                   1900:                     $ruleshash{$key}=&thaw_unescape($value);
                   1901:                 }
                   1902:                 my @esc_order = split(/\&/,$orderitems);
                   1903:                 foreach my $item (@esc_order) {
                   1904:                     push(@ruleorder,&unescape($item));
                   1905:                 }
                   1906:             }
                   1907:         }
                   1908:     }
                   1909:     return (\%ruleshash,\@ruleorder);
                   1910: }
                   1911: 
1.976     raeburn  1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1913: 
                   1914: sub get_domain_defaults {
                   1915:     my ($domain) = @_;
                   1916:     my $cachetime = 60*60*24;
                   1917:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1918:     if (defined($cached)) {
                   1919:         if (ref($result) eq 'HASH') {
                   1920:             return %{$result};
                   1921:         }
                   1922:     }
                   1923:     my %domdefaults;
                   1924:     my %domconfig =
1.989     raeburn  1925:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1926:                                   'requestcourses','inststatus',
1.1073    raeburn  1927:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1928:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1929:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1930:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1931:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1932:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1933:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1934:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1935:     } else {
                   1936:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1937:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1938:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1939:     }
1.976     raeburn  1940:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1941:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1943:         } else {
                   1944:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1945:         } 
                   1946:         my @usertools = ('aboutme','blog','portfolio');
                   1947:         foreach my $item (@usertools) {
                   1948:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1949:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1950:             }
                   1951:         }
                   1952:     }
1.985     raeburn  1953:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1954:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1955:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1956:         }
                   1957:     }
1.989     raeburn  1958:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1959:         foreach my $item ('inststatustypes','inststatusorder') {
                   1960:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1961:         }
                   1962:     }
1.1047    raeburn  1963:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1964:         foreach my $item ('canuse_pdfforms') {
                   1965:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1966:         }
                   1967:     }
1.1073    raeburn  1968:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1969:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1970:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1971:         }
                   1972:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1973:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1974:         }
                   1975:     }
1.943     raeburn  1976:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1977:                                   $cachetime);
                   1978:     return %domdefaults;
                   1979: }
                   1980: 
1.344     www      1981: # --------------------------------------------------- Assign a key to a student
                   1982: 
                   1983: sub assign_access_key {
1.364     www      1984: #
                   1985: # a valid key looks like uname:udom#comments
                   1986: # comments are being appended
                   1987: #
1.498     www      1988:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1989:     $kdom=
1.620     albertel 1990:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1991:     $knum=
1.620     albertel 1992:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1993:     $cdom=
1.620     albertel 1994:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1995:     $cnum=
1.620     albertel 1996:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1997:     $udom=$env{'user.name'} unless (defined($udom));
                   1998:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1999:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2000:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2001:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2002:                                                   # assigned to this person
                   2003:                                                   # - this should not happen,
1.345     www      2004:                                                   # unless something went wrong
                   2005:                                                   # the first time around
                   2006: # ready to assign
1.364     www      2007:         $logentry=$1.'; '.$logentry;
1.496     www      2008:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2009:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2010: # key now belongs to user
1.346     www      2011: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2012:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2013:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2014:                 return 'ok';
                   2015:             } else {
                   2016:                 return 
                   2017:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2018: 	    }
                   2019:         } else {
                   2020:             return 'error: Could not assign key, try again later.';
                   2021:         }
1.364     www      2022:     } elsif (!$existing{$ckey}) {
1.345     www      2023: # the key does not exist
                   2024: 	return 'error: The key does not exist';
                   2025:     } else {
                   2026: # the key is somebody else's
                   2027: 	return 'error: The key is already in use';
                   2028:     }
1.344     www      2029: }
                   2030: 
1.364     www      2031: # ------------------------------------------ put an additional comment on a key
                   2032: 
                   2033: sub comment_access_key {
                   2034: #
                   2035: # a valid key looks like uname:udom#comments
                   2036: # comments are being appended
                   2037: #
                   2038:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2039:     $cdom=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2041:     $cnum=
1.620     albertel 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2043:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2044:     if ($existing{$ckey}) {
                   2045:         $existing{$ckey}.='; '.$logentry;
                   2046: # ready to assign
1.367     www      2047:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2048:                                                  $cdom,$cnum) eq 'ok') {
                   2049: 	    return 'ok';
                   2050:         } else {
                   2051: 	    return 'error: Count not store comment.';
                   2052:         }
                   2053:     } else {
                   2054: # the key does not exist
                   2055: 	return 'error: The key does not exist';
                   2056:     }
                   2057: }
                   2058: 
1.344     www      2059: # ------------------------------------------------------ Generate a set of keys
                   2060: 
                   2061: sub generate_access_keys {
1.364     www      2062:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2063:     $cdom=
1.620     albertel 2064:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2065:     $cnum=
1.620     albertel 2066:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2067:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2068:     unless (($cdom) && ($cnum)) { return 0; }
                   2069:     if ($number>10000) { return 0; }
                   2070:     sleep(2); # make sure don't get same seed twice
                   2071:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2072:     my $total=0;
                   2073:     for (my $i=1;$i<=$number;$i++) {
                   2074:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2075:                   sprintf("%lx",int(100000*rand)).'-'.
                   2076:                   sprintf("%lx",int(100000*rand));
                   2077:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2078:        $newkey=~s/0/h/g; # and also 0 and O
                   2079:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2080:        if ($existing{$newkey}) {
                   2081:            $i--;
                   2082:        } else {
1.364     www      2083: 	  if (&put('accesskeys',
                   2084:               { $newkey => '# generated '.localtime().
1.620     albertel 2085:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2086:                            '; '.$logentry },
                   2087: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2088:               $total++;
                   2089: 	  }
                   2090:        }
                   2091:     }
1.620     albertel 2092:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2093:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2094:     return $total;
                   2095: }
                   2096: 
                   2097: # ------------------------------------------------------- Validate an accesskey
                   2098: 
                   2099: sub validate_access_key {
                   2100:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2101:     $cdom=
1.620     albertel 2102:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2103:     $cnum=
1.620     albertel 2104:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2105:     $udom=$env{'user.domain'} unless (defined($udom));
                   2106:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2107:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2108:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2109: }
                   2110: 
                   2111: # ------------------------------------- Find the section of student in a course
1.652     albertel 2112: sub devalidate_getsection_cache {
                   2113:     my ($udom,$unam,$courseid)=@_;
                   2114:     my $hashid="$udom:$unam:$courseid";
                   2115:     &devalidate_cache_new('getsection',$hashid);
                   2116: }
1.298     matthew  2117: 
1.815     albertel 2118: sub courseid_to_courseurl {
                   2119:     my ($courseid) = @_;
                   2120:     #already url style courseid
                   2121:     return $courseid if ($courseid =~ m{^/});
                   2122: 
                   2123:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2124: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2125: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2126: 	return "/$cdom/$cnum";
                   2127:     }
                   2128: 
                   2129:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2130:     if (exists($courseinfo{'num'})) {
                   2131: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2132:     }
                   2133: 
                   2134:     return undef;
                   2135: }
                   2136: 
1.298     matthew  2137: sub getsection {
                   2138:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2139:     my $cachetime=1800;
1.551     albertel 2140: 
                   2141:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2142:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2143:     if (defined($cached)) { return $result; }
                   2144: 
1.298     matthew  2145:     my %Pending; 
                   2146:     my %Expired;
                   2147:     #
                   2148:     # Each role can either have not started yet (pending), be active, 
                   2149:     #    or have expired.
                   2150:     #
                   2151:     # If there is an active role, we are done.
                   2152:     #
                   2153:     # If there is more than one role which has not started yet, 
                   2154:     #     choose the one which will start sooner
                   2155:     # If there is one role which has not started yet, return it.
                   2156:     #
                   2157:     # If there is more than one expired role, choose the one which ended last.
                   2158:     # If there is a role which has expired, return it.
                   2159:     #
1.815     albertel 2160:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  2161:     my $extra = &freeze_escape({'skipcheck' => 1});
                   2162:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  2163:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2164:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2165:         my $section=$1;
                   2166:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2167:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2168:         my $now=time;
1.548     albertel 2169:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2170:             $Expired{$end}=$section;
                   2171:             next;
                   2172:         }
1.548     albertel 2173:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2174:             $Pending{$start}=$section;
                   2175:             next;
                   2176:         }
1.599     albertel 2177:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2178:     }
                   2179:     #
                   2180:     # Presumedly there will be few matching roles from the above
                   2181:     # loop and the sorting time will be negligible.
                   2182:     if (scalar(keys(%Pending))) {
                   2183:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2184:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2185:     } 
                   2186:     if (scalar(keys(%Expired))) {
                   2187:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2188:         my $time = pop(@sorted);
1.599     albertel 2189:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2190:     }
1.599     albertel 2191:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2192: }
1.70      www      2193: 
1.599     albertel 2194: sub save_cache {
                   2195:     &purge_remembered();
1.722     albertel 2196:     #&Apache::loncommon::validate_page();
1.620     albertel 2197:     undef(%env);
1.780     albertel 2198:     undef($env_loaded);
1.599     albertel 2199: }
1.452     albertel 2200: 
1.599     albertel 2201: my $to_remember=-1;
                   2202: my %remembered;
                   2203: my %accessed;
                   2204: my $kicks=0;
                   2205: my $hits=0;
1.849     albertel 2206: sub make_key {
                   2207:     my ($name,$id) = @_;
1.872     albertel 2208:     if (length($id) > 65 
                   2209: 	&& length(&escape($id)) > 200) {
                   2210: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2211:     }
1.849     albertel 2212:     return &escape($name.':'.$id);
                   2213: }
                   2214: 
1.599     albertel 2215: sub devalidate_cache_new {
                   2216:     my ($name,$id,$debug) = @_;
                   2217:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2218:     $id=&make_key($name,$id);
1.599     albertel 2219:     $memcache->delete($id);
                   2220:     delete($remembered{$id});
                   2221:     delete($accessed{$id});
                   2222: }
                   2223: 
                   2224: sub is_cached_new {
                   2225:     my ($name,$id,$debug) = @_;
1.849     albertel 2226:     $id=&make_key($name,$id);
1.599     albertel 2227:     if (exists($remembered{$id})) {
1.1133    foxr     2228: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2229: 	$accessed{$id}=[&gettimeofday()];
                   2230: 	$hits++;
                   2231: 	return ($remembered{$id},1);
                   2232:     }
                   2233:     my $value = $memcache->get($id);
                   2234:     if (!(defined($value))) {
                   2235: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2236: 	return (undef,undef);
1.416     albertel 2237:     }
1.599     albertel 2238:     if ($value eq '__undef__') {
                   2239: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2240: 	$value=undef;
                   2241:     }
                   2242:     &make_room($id,$value,$debug);
                   2243:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2244:     return ($value,1);
                   2245: }
                   2246: 
                   2247: sub do_cache_new {
                   2248:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2249:     $id=&make_key($name,$id);
1.599     albertel 2250:     my $setvalue=$value;
                   2251:     if (!defined($setvalue)) {
                   2252: 	$setvalue='__undef__';
                   2253:     }
1.623     albertel 2254:     if (!defined($time) ) {
                   2255: 	$time=600;
                   2256:     }
1.599     albertel 2257:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2258:     my $result = $memcache->set($id,$setvalue,$time);
                   2259:     if (! $result) {
1.872     albertel 2260: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2261: 	$memcache->disconnect_all();
1.872     albertel 2262:     }
1.600     albertel 2263:     # need to make a copy of $value
1.919     albertel 2264:     &make_room($id,$value,$debug);
1.599     albertel 2265:     return $value;
                   2266: }
                   2267: 
                   2268: sub make_room {
                   2269:     my ($id,$value,$debug)=@_;
1.919     albertel 2270: 
                   2271:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2272:                                     : $value;
1.599     albertel 2273:     if ($to_remember<0) { return; }
                   2274:     $accessed{$id}=[&gettimeofday()];
                   2275:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2276:     my $to_kick;
                   2277:     my $max_time=0;
                   2278:     foreach my $other (keys(%accessed)) {
                   2279: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2280: 	    $to_kick=$other;
                   2281: 	    $max_time=&tv_interval($accessed{$other});
                   2282: 	}
                   2283:     }
                   2284:     delete($remembered{$to_kick});
                   2285:     delete($accessed{$to_kick});
                   2286:     $kicks++;
                   2287:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2288:     return;
                   2289: }
                   2290: 
1.599     albertel 2291: sub purge_remembered {
1.604     albertel 2292:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2293:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2294:     undef(%remembered);
                   2295:     undef(%accessed);
1.428     albertel 2296: }
1.70      www      2297: # ------------------------------------- Read an entry from a user's environment
                   2298: 
                   2299: sub userenvironment {
                   2300:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2301:     my $items;
                   2302:     foreach my $item (@what) {
                   2303:         $items.=&escape($item).'&';
                   2304:     }
                   2305:     $items=~s/\&$//;
1.70      www      2306:     my %returnhash=();
1.1009    raeburn  2307:     my $uhome = &homeserver($unam,$udom);
                   2308:     unless ($uhome eq 'no_host') {
                   2309:         my @answer=split(/\&/, 
                   2310:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2311:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2312:             return %returnhash;
                   2313:         }
1.1009    raeburn  2314:         my $i;
                   2315:         for ($i=0;$i<=$#what;$i++) {
                   2316: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2317:         }
1.70      www      2318:     }
                   2319:     return %returnhash;
1.1       albertel 2320: }
                   2321: 
1.617     albertel 2322: # ---------------------------------------------------------- Get a studentphoto
                   2323: sub studentphoto {
                   2324:     my ($udom,$unam,$ext) = @_;
                   2325:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2326:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2327:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2328:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2329:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2330:             } else {
                   2331:                 my ($result,$perm_reqd)=
1.707     albertel 2332: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2333:                 if ($result eq 'ok') {
                   2334:                     if (!($perm_reqd eq 'yes')) {
                   2335:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2336:                     }
                   2337:                 }
                   2338:             }
                   2339:         }
                   2340:     } else {
                   2341:         my ($result,$perm_reqd) = 
1.707     albertel 2342: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2343:         if ($result eq 'ok') {
                   2344:             if (!($perm_reqd eq 'yes')) {
                   2345:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2346:             }
                   2347:         }
                   2348:     }
                   2349:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2350: }
                   2351: 
                   2352: sub retrievestudentphoto {
                   2353:     my ($udom,$unam,$ext,$type) = @_;
                   2354:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2355:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2356:     if ($ret eq 'ok') {
                   2357:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2358:         if ($type eq 'thumbnail') {
                   2359:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2360:         }
                   2361:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2362:         return $tokenurl;
                   2363:     } else {
                   2364:         if ($type eq 'thumbnail') {
                   2365:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2366:         } else { 
                   2367:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2368:         }
1.617     albertel 2369:     }
                   2370: }
                   2371: 
1.263     www      2372: # -------------------------------------------------------------------- New chat
                   2373: 
                   2374: sub chatsend {
1.724     raeburn  2375:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2376:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2377:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2378:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2379:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2380: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2381: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2382: }
                   2383: 
                   2384: # ------------------------------------------ Find current version of a resource
                   2385: 
                   2386: sub getversion {
                   2387:     my $fname=&clutter(shift);
                   2388:     unless ($fname=~/^\/res\//) { return -1; }
                   2389:     return &currentversion(&filelocation('',$fname));
                   2390: }
                   2391: 
                   2392: sub currentversion {
                   2393:     my $fname=shift;
                   2394:     my $author=$fname;
                   2395:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2396:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2397:     my $home=&homeserver($uname,$udom);
1.292     www      2398:     if ($home eq 'no_host') { 
                   2399:         return -1; 
                   2400:     }
1.1112    www      2401:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2402:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2403: 	return -1;
                   2404:     }
1.1112    www      2405:     return $answer;
1.263     www      2406: }
                   2407: 
1.1111    www      2408: #
                   2409: # Return special version number of resource if set by override, empty otherwise
                   2410: #
                   2411: sub usedversion {
                   2412:     my $fname=shift;
                   2413:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2414:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2415:     if ($urlversion) { return $urlversion; }
                   2416:     return '';
                   2417: }
                   2418: 
1.1       albertel 2419: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2420: 
1.1       albertel 2421: sub subscribe {
                   2422:     my $fname=shift;
1.761     raeburn  2423:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2424:     $fname=~s/[\n\r]//g;
1.1       albertel 2425:     my $author=$fname;
                   2426:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2427:     my ($udom,$uname)=split(/\//,$author);
                   2428:     my $home=homeserver($uname,$udom);
1.335     albertel 2429:     if ($home eq 'no_host') {
                   2430:         return 'not_found';
1.1       albertel 2431:     }
                   2432:     my $answer=reply("sub:$fname",$home);
1.64      www      2433:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2434: 	$answer.=' by '.$home;
                   2435:     }
1.1       albertel 2436:     return $answer;
                   2437: }
                   2438:     
1.8       www      2439: # -------------------------------------------------------------- Replicate file
                   2440: 
                   2441: sub repcopy {
                   2442:     my $filename=shift;
1.23      www      2443:     $filename=~s/\/+/\//g;
1.1142    raeburn  2444:     my $londocroot = $perlvar{'lonDocRoot'};
                   2445:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
                   2446:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
                   2447:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2448: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2449: 	return &repcopy_userfile($filename);
                   2450:     }
1.532     albertel 2451:     $filename=~s/[\n\r]//g;
1.8       www      2452:     my $transname="$filename.in.transfer";
1.828     www      2453: # FIXME: this should flock
1.607     raeburn  2454:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2455:     my $remoteurl=subscribe($filename);
1.64      www      2456:     if ($remoteurl =~ /^con_lost by/) {
                   2457: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2458:            return 'unavailable';
1.8       www      2459:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2460: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2461: 	   return 'not_found';
1.64      www      2462:     } elsif ($remoteurl =~ /^rejected by/) {
                   2463: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2464:            return 'forbidden';
1.20      www      2465:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2466:            return 'ok';
1.8       www      2467:     } else {
1.290     www      2468:         my $author=$filename;
                   2469:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2470:         my ($udom,$uname)=split(/\//,$author);
                   2471:         my $home=homeserver($uname,$udom);
                   2472:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2473:            my @parts=split(/\//,$filename);
                   2474:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2475:            if ($path ne "$londocroot/res") {
1.8       www      2476:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2477: 	       return 'bad_request';
1.8       www      2478:            }
                   2479:            my $count;
                   2480:            for ($count=5;$count<$#parts;$count++) {
                   2481:                $path.="/$parts[$count]";
                   2482:                if ((-e $path)!=1) {
                   2483: 		   mkdir($path,0777);
                   2484:                }
                   2485:            }
                   2486:            my $ua=new LWP::UserAgent;
                   2487:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2488:            my $response=$ua->request($request,$transname);
                   2489:            if ($response->is_error()) {
                   2490: 	       unlink($transname);
                   2491:                my $message=$response->status_line;
1.672     albertel 2492:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2493:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2494:                return 'unavailable';
1.8       www      2495:            } else {
1.16      www      2496: 	       if ($remoteurl!~/\.meta$/) {
                   2497:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2498:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2499:                   if ($mresponse->is_error()) {
                   2500: 		      unlink($filename.'.meta');
                   2501:                       &logthis(
1.672     albertel 2502:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2503:                   }
                   2504: 	       }
1.8       www      2505:                rename($transname,$filename);
1.607     raeburn  2506:                return 'ok';
1.8       www      2507:            }
1.290     www      2508:        }
1.8       www      2509:     }
1.330     www      2510: }
                   2511: 
                   2512: # ------------------------------------------------ Get server side include body
                   2513: sub ssi_body {
1.381     albertel 2514:     my ($filelink,%form)=@_;
1.606     matthew  2515:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2516:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2517:     }
1.953     www      2518:     my $output='';
                   2519:     my $response;
1.980     raeburn  2520:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2521:        ($output,$response)=&externalssi($filelink);
1.953     www      2522:     } else {
1.1004    droeschl 2523:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2524:        $filelink .= 'inhibitmenu=yes';
1.953     www      2525:        ($output,$response)=&ssi($filelink,%form);
                   2526:     }
1.778     albertel 2527:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2528:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2529:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2530:     if (wantarray) {
                   2531:         return ($output, $response);
                   2532:     } else {
                   2533:         return $output;
                   2534:     }
1.8       www      2535: }
                   2536: 
1.15      www      2537: # --------------------------------------------------------- Server Side Include
                   2538: 
1.782     albertel 2539: sub absolute_url {
                   2540:     my ($host_name) = @_;
                   2541:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2542:     if ($host_name eq '') {
                   2543: 	$host_name = $ENV{'SERVER_NAME'};
                   2544:     }
                   2545:     return $protocol.$host_name;
                   2546: }
                   2547: 
1.942     foxr     2548: #
                   2549: #   Server side include.
                   2550: # Parameters:
                   2551: #  fn     Possibly encrypted resource name/id.
                   2552: #  form   Hash that describes how the rendering should be done
                   2553: #         and other things.
1.944     foxr     2554: # Returns:
1.950     raeburn  2555: #   Scalar context: The content of the response.
                   2556: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2557: #     
1.15      www      2558: sub ssi {
                   2559: 
1.944     foxr     2560:     my ($fn,%form)=@_;
1.15      www      2561:     my $ua=new LWP::UserAgent;
1.23      www      2562:     my $request;
1.711     albertel 2563: 
                   2564:     $form{'no_update_last_known'}=1;
1.895     albertel 2565:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2566:     if (%form) {
1.782     albertel 2567:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2568:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2569:     } else {
1.782     albertel 2570:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2571:     }
                   2572: 
1.15      www      2573:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2574:     my $response=$ua->request($request);
                   2575: 
1.944     foxr     2576:     if (wantarray) {
                   2577: 	return ($response->content, $response);
                   2578:     } else {
                   2579: 	return $response->content;
1.942     foxr     2580:     }
1.324     www      2581: }
                   2582: 
                   2583: sub externalssi {
                   2584:     my ($url)=@_;
                   2585:     my $ua=new LWP::UserAgent;
                   2586:     my $request=new HTTP::Request('GET',$url);
                   2587:     my $response=$ua->request($request);
1.954     raeburn  2588:     if (wantarray) {
                   2589:         return ($response->content, $response);
                   2590:     } else {
                   2591:         return $response->content;
                   2592:     }
1.15      www      2593: }
1.254     www      2594: 
1.492     albertel 2595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2596: 
                   2597: sub allowuploaded {
                   2598:     my ($srcurl,$url)=@_;
                   2599:     $url=&clutter(&declutter($url));
                   2600:     my $dir=$url;
                   2601:     $dir=~s/\/[^\/]+$//;
                   2602:     my %httpref=();
                   2603:     my $httpurl=&hreflocation('',$url);
                   2604:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2605:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2606: }
1.477     raeburn  2607: 
1.478     albertel 2608: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2609: # input: action, courseID, current domain, intended
1.637     raeburn  2610: #        path to file, source of file, instruction to parse file for objects,
                   2611: #        ref to hash for embedded objects,
                   2612: #        ref to hash for codebase of java objects.
1.1095    raeburn  2613: #        reference to scalar to accommodate mime type determined
                   2614: #          from File::MMagic if $parser = parse.
1.637     raeburn  2615: #
1.485     raeburn  2616: # output: url to file (if action was uploaddoc), 
                   2617: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2618: #
1.478     albertel 2619: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2620: # course.
1.477     raeburn  2621: #
1.478     albertel 2622: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2623: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2624: #          course's home server.
1.477     raeburn  2625: #
1.478     albertel 2626: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2627: #          be copied from $source (current location) to 
                   2628: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2629: #         and will then be copied to
                   2630: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2631: #         course's home server.
1.485     raeburn  2632: #
1.481     raeburn  2633: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2634: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2635: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2636: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2637: #         in course's home server.
1.637     raeburn  2638: #
1.477     raeburn  2639: 
                   2640: sub process_coursefile {
1.1095    raeburn  2641:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2642:         $mimetype)=@_;
1.477     raeburn  2643:     my $fetchresult;
1.638     albertel 2644:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2645:     if ($action eq 'propagate') {
1.638     albertel 2646:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2647: 			     $home);
1.481     raeburn  2648:     } else {
1.477     raeburn  2649:         my $fpath = '';
                   2650:         my $fname = $file;
1.478     albertel 2651:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2652:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2653:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2654:         if ($action eq 'copy') {
                   2655:             if ($source eq '') {
                   2656:                 $fetchresult = 'no source file';
                   2657:                 return $fetchresult;
                   2658:             } else {
                   2659:                 my $destination = $filepath.'/'.$fname;
                   2660:                 rename($source,$destination);
                   2661:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2662:                                  $home);
1.481     raeburn  2663:             }
                   2664:         } elsif ($action eq 'uploaddoc') {
                   2665:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2666:             print $fh $env{'form.'.$source};
1.481     raeburn  2667:             close($fh);
1.637     raeburn  2668:             if ($parser eq 'parse') {
1.1024    raeburn  2669:                 my $mm = new File::MMagic;
1.1095    raeburn  2670:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2671:                 if ($type eq 'text/html') {
1.1024    raeburn  2672:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2673:                     unless ($parse_result eq 'ok') {
                   2674:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2675:                     }
1.637     raeburn  2676:                 }
1.1095    raeburn  2677:                 if (ref($mimetype)) {
                   2678:                     $$mimetype = $type;
                   2679:                 } 
1.637     raeburn  2680:             }
1.477     raeburn  2681:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2682:                                  $home);
1.481     raeburn  2683:             if ($fetchresult eq 'ok') {
                   2684:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2685:             } else {
                   2686:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2687:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2688:                 return '/adm/notfound.html';
                   2689:             }
1.477     raeburn  2690:         }
                   2691:     }
1.485     raeburn  2692:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2693:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2694:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2695:     }
                   2696:     return $fetchresult;
                   2697: }
                   2698: 
1.637     raeburn  2699: sub build_filepath {
                   2700:     my ($fpath) = @_;
                   2701:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2702:     unless ($fpath eq '') {
                   2703:         my @parts=split('/',$fpath);
                   2704:         foreach my $part (@parts) {
                   2705:             $filepath.= '/'.$part;
                   2706:             if ((-e $filepath)!=1) {
                   2707:                 mkdir($filepath,0777);
                   2708:             }
                   2709:         }
                   2710:     }
                   2711:     return $filepath;
                   2712: }
                   2713: 
                   2714: sub store_edited_file {
1.638     albertel 2715:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2716:     my $file = $primary_url;
                   2717:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2718:     my $fpath = '';
                   2719:     my $fname = $file;
                   2720:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2721:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2722:     my $filepath = &build_filepath($fpath);
                   2723:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2724:     print $fh $content;
                   2725:     close($fh);
1.638     albertel 2726:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2727:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2728: 			  $home);
1.637     raeburn  2729:     if ($$fetchresult eq 'ok') {
                   2730:         return '/uploaded/'.$fpath.'/'.$fname;
                   2731:     } else {
1.638     albertel 2732:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2733: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2734:         return '/adm/notfound.html';
                   2735:     }
                   2736: }
                   2737: 
1.531     albertel 2738: sub clean_filename {
1.831     albertel 2739:     my ($fname,$args)=@_;
1.315     www      2740: # Replace Windows backslashes by forward slashes
1.257     www      2741:     $fname=~s/\\/\//g;
1.831     albertel 2742:     if (!$args->{'keep_path'}) {
                   2743:         # Get rid of everything but the actual filename
                   2744: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2745:     }
1.315     www      2746: # Replace spaces by underscores
                   2747:     $fname=~s/\s+/\_/g;
                   2748: # Replace all other weird characters by nothing
1.831     albertel 2749:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2750: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2751: # numbers
                   2752:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2753:     return $fname;
                   2754: }
1.1051    raeburn  2755: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2756: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2757: # image with the same aspect ratio as the original, but with dimensions which do 
                   2758: # not exceed $resizewidth and $resizeheight.
                   2759:  
1.984     neumanie 2760: sub resizeImage {
1.1051    raeburn  2761:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2762:     my $ima = Image::Magick->new;
                   2763:     my $resized;
                   2764:     if (-e $img_path) {
                   2765:         $ima->Read($img_path);
                   2766:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2767:             my $width = $ima->Get('width');
                   2768:             my $height = $ima->Get('height');
                   2769:             if ($width > $resizewidth) {
                   2770: 	        my $factor = $width/$resizewidth;
                   2771:                 my $newheight = $height/$factor;
                   2772:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2773:                 $resized = 1;
                   2774:             }
                   2775:         }
                   2776:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2777:             my $width = $ima->Get('width');
                   2778:             my $height = $ima->Get('height');
                   2779:             if ($height > $resizeheight) {
                   2780:                 my $factor = $height/$resizeheight;
                   2781:                 my $newwidth = $width/$factor;
                   2782:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2783:                 $resized = 1;
                   2784:             }
                   2785:         }
                   2786:         if ($resized) {
                   2787:             $ima->Write($img_path);
                   2788:         }
                   2789:     }
                   2790:     return;
1.977     amueller 2791: }
                   2792: 
1.608     albertel 2793: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2794: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2795: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2796: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2797: #                                    canceloverwrite, or ''. 
                   2798: #                   if 'coursedoc': upload to the current course
                   2799: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2800: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2801: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2802: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2803: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2804: #        $allfiles - reference to hash for embedded objects
                   2805: #        $codebase - reference to hash for codebase of java objects
                   2806: #        $desuname - username for permanent storage of uploaded file
                   2807: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2808: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2809: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2810: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2811: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2812: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2813: #                    from File::MMagic.
1.858     raeburn  2814: # 
1.686     albertel 2815: # output: url of file in userspace, or error: <message> 
                   2816: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2817: 
1.531     albertel 2818: sub userfileupload {
1.1090    raeburn  2819:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2820:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2821:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2822:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2823:     $fname=&clean_filename($fname);
1.1090    raeburn  2824:     # See if there is anything left
1.257     www      2825:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2826:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2827:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2828:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2829:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2830:         my $now = time;
1.1090    raeburn  2831:         my $filepath;
1.1095    raeburn  2832:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2833:              $filepath = 'tmp/helprequests/'.$now;
                   2834:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2835:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2836:                          '_'.$env{'user.domain'}.'/pending';
                   2837:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2838:             my ($docuname,$docudom);
                   2839:             if ($destudom) {
                   2840:                 $docudom = $destudom;
                   2841:             } else {
                   2842:                 $docudom = $env{'user.domain'};
                   2843:             }
                   2844:             if ($destuname) {
                   2845:                 $docuname = $destuname;
                   2846:             } else {
                   2847:                 $docuname = $env{'user.name'};
                   2848:             }
                   2849:             if (exists($env{'form.group'})) {
                   2850:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2851:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2852:             }
                   2853:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2854:             if ($context eq 'canceloverwrite') {
                   2855:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2856:                 if (-e  $tempfile) {
                   2857:                     my @info = stat($tempfile);
                   2858:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2859:                         unlink($tempfile);
                   2860:                     }
                   2861:                 }
                   2862:                 return;
1.523     raeburn  2863:             }
                   2864:         }
1.1090    raeburn  2865:         # Create the directory if not present
1.741     raeburn  2866:         my @parts=split(/\//,$filepath);
                   2867:         my $fullpath = $perlvar{'lonDaemons'};
                   2868:         for (my $i=0;$i<@parts;$i++) {
                   2869:             $fullpath .= '/'.$parts[$i];
                   2870:             if ((-e $fullpath)!=1) {
                   2871:                 mkdir($fullpath,0777);
                   2872:             }
                   2873:         }
                   2874:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2875:         print $fh $env{'form.'.$formname};
                   2876:         close($fh);
1.1090    raeburn  2877:         if ($context eq 'existingfile') {
                   2878:             my @info = stat($fullpath.'/'.$fname);
                   2879:             return ($fullpath.'/'.$fname,$info[9]);
                   2880:         } else {
                   2881:             return $fullpath.'/'.$fname;
                   2882:         }
1.523     raeburn  2883:     }
1.995     raeburn  2884:     if ($subdir eq 'scantron') {
                   2885:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2886:     } else {
1.995     raeburn  2887:         $fname="$subdir/$fname";
                   2888:     }
1.1090    raeburn  2889:     if ($context eq 'coursedoc') {
1.638     albertel 2890: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2891: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2892:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2893:             return &finishuserfileupload($docuname,$docudom,
                   2894: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2895: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2896:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2897:         } else {
1.620     albertel 2898:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2899:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2900: 				       $fname,$formname,$parser,
1.1095    raeburn  2901: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2902:         }
1.719     banghart 2903:     } elsif (defined($destuname)) {
                   2904:         my $docuname=$destuname;
                   2905:         my $docudom=$destudom;
1.860     raeburn  2906: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2907: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2908:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2909:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2910:     } else {
1.638     albertel 2911:         my $docuname=$env{'user.name'};
                   2912:         my $docudom=$env{'user.domain'};
1.714     raeburn  2913:         if (exists($env{'form.group'})) {
                   2914:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2915:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2916:         }
1.860     raeburn  2917: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2918: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2919:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2920:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2921:     }
1.271     www      2922: }
                   2923: 
                   2924: sub finishuserfileupload {
1.860     raeburn  2925:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2926:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2927:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2928:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2929:   
1.860     raeburn  2930:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2931:     $file=$fname;
                   2932:     if ($fname=~m|/|) {
                   2933:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2934: 	$path.=$fnamepath.'/';
                   2935:     }
1.259     www      2936:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2937:     my $count;
                   2938:     for ($count=4;$count<=$#parts;$count++) {
                   2939:         $filepath.="/$parts[$count]";
                   2940:         if ((-e $filepath)!=1) {
                   2941: 	    mkdir($filepath,0777);
                   2942:         }
                   2943:     }
1.984     neumanie 2944: 
1.258     www      2945: # Save the file
                   2946:     {
1.701     albertel 2947: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2948: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2949: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2950: 	    return '/adm/notfound.html';
                   2951: 	}
1.1090    raeburn  2952:         if ($context eq 'overwrite') {
1.1117    foxr     2953:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2954:             my $target = $filepath.'/'.$file;
                   2955:             if (-e $source) {
                   2956:                 my @info = stat($source);
                   2957:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2958:                     unless (&File::Copy::move($source,$target)) {
                   2959:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2960:                         return "Moving from $source failed";
                   2961:                     }
                   2962:                 } else {
                   2963:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2964:                 }
                   2965:             } else {
                   2966:                 return "Temporary file: $source missing";
                   2967:             }
                   2968:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2969: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2970: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2971: 	    return '/adm/notfound.html';
                   2972: 	}
1.570     albertel 2973: 	close(FH);
1.1051    raeburn  2974:         if ($resizewidth && $resizeheight) {
                   2975:             my $mm = new File::MMagic;
                   2976:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2977:             if ($mime_type =~ m{^image/}) {
                   2978: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2979:             }  
1.977     amueller 2980: 	}
1.258     www      2981:     }
1.1152    raeburn  2982:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2983:         if (ref($mimetype)) {
                   2984:             if ($$mimetype eq '') {
                   2985:                 my $mm = new File::MMagic;
                   2986:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2987:                 $$mimetype = $type;
                   2988:             }
                   2989:         }
                   2990:     }
1.637     raeburn  2991:     if ($parser eq 'parse') {
1.1152    raeburn  2992:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  2993:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2994:                                                        $allfiles,$codebase);
                   2995:             unless ($parse_result eq 'ok') {
                   2996:                 &logthis('Failed to parse '.$filepath.$file.
                   2997: 	   	         ' for embedded media: '.$parse_result); 
                   2998:             }
1.637     raeburn  2999:         }
                   3000:     }
1.860     raeburn  3001:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3002:         my $input = $filepath.'/'.$file;
                   3003:         my $output = $filepath.'/'.'tn-'.$file;
                   3004:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3005:         system("convert -sample $thumbsize $input $output");
                   3006:         if (-e $filepath.'/'.'tn-'.$file) {
                   3007:             $fetchthumb  = 1; 
                   3008:         }
                   3009:     }
1.858     raeburn  3010:  
1.259     www      3011: # Notify homeserver to grep it
                   3012: #
1.984     neumanie 3013:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3014:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3015:     if ($fetchresult eq 'ok') {
1.860     raeburn  3016:         if ($fetchthumb) {
                   3017:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3018:             if ($thumbresult ne 'ok') {
                   3019:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3020:                          $docuhome.': '.$thumbresult);
                   3021:             }
                   3022:         }
1.259     www      3023: #
1.258     www      3024: # Return the URL to it
1.494     albertel 3025:         return '/uploaded/'.$path.$file;
1.263     www      3026:     } else {
1.494     albertel 3027:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3028: 		 ': '.$fetchresult);
1.263     www      3029:         return '/adm/notfound.html';
1.858     raeburn  3030:     }
1.493     albertel 3031: }
                   3032: 
1.637     raeburn  3033: sub extract_embedded_items {
1.961     raeburn  3034:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3035:     my @state = ();
                   3036:     my %javafiles = (
                   3037:                       codebase => '',
                   3038:                       code => '',
                   3039:                       archive => ''
                   3040:                     );
                   3041:     my %mediafiles = (
                   3042:                       src => '',
                   3043:                       movie => '',
                   3044:                      );
1.648     raeburn  3045:     my $p;
                   3046:     if ($content) {
                   3047:         $p = HTML::LCParser->new($content);
                   3048:     } else {
1.961     raeburn  3049:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3050:     }
1.641     albertel 3051:     while (my $t=$p->get_token()) {
1.640     albertel 3052: 	if ($t->[0] eq 'S') {
                   3053: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3054: 	    push(@state, $tagname);
1.648     raeburn  3055:             if (lc($tagname) eq 'allow') {
                   3056:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3057:             }
1.640     albertel 3058: 	    if (lc($tagname) eq 'img') {
                   3059: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3060: 	    }
1.886     albertel 3061: 	    if (lc($tagname) eq 'a') {
                   3062: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3063: 	    }
1.645     raeburn  3064:             if (lc($tagname) eq 'script') {
                   3065:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3066:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3067:                 } else {
                   3068:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   3069:                 }
                   3070:             }
                   3071:             if (lc($tagname) eq 'link') {
                   3072:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3073:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3074:                 }
                   3075:             }
1.640     albertel 3076: 	    if (lc($tagname) eq 'object' ||
                   3077: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3078: 		foreach my $item (keys(%javafiles)) {
                   3079: 		    $javafiles{$item} = '';
                   3080: 		}
                   3081: 	    }
                   3082: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3083: 		my $name = lc($attr->{'name'});
                   3084: 		foreach my $item (keys(%javafiles)) {
                   3085: 		    if ($name eq $item) {
                   3086: 			$javafiles{$item} = $attr->{'value'};
                   3087: 			last;
                   3088: 		    }
                   3089: 		}
                   3090: 		foreach my $item (keys(%mediafiles)) {
                   3091: 		    if ($name eq $item) {
                   3092: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   3093: 			last;
                   3094: 		    }
                   3095: 		}
                   3096: 	    }
                   3097: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3098: 		foreach my $item (keys(%javafiles)) {
                   3099: 		    if ($attr->{$item}) {
                   3100: 			$javafiles{$item} = $attr->{$item};
                   3101: 			last;
                   3102: 		    }
                   3103: 		}
                   3104: 		foreach my $item (keys(%mediafiles)) {
                   3105: 		    if ($attr->{$item}) {
                   3106: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3107: 			last;
                   3108: 		    }
                   3109: 		}
                   3110: 	    }
                   3111: 	} elsif ($t->[0] eq 'E') {
                   3112: 	    my ($tagname) = ($t->[1]);
                   3113: 	    if ($javafiles{'codebase'} ne '') {
                   3114: 		$javafiles{'codebase'} .= '/';
                   3115: 	    }  
                   3116: 	    if (lc($tagname) eq 'applet' ||
                   3117: 		lc($tagname) eq 'object' ||
                   3118: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3119: 		) {
                   3120: 		foreach my $item (keys(%javafiles)) {
                   3121: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3122: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3123: 			&add_filetype($allfiles,$file,$item);
                   3124: 		    }
                   3125: 		}
                   3126: 	    } 
                   3127: 	    pop @state;
                   3128: 	}
                   3129:     }
1.637     raeburn  3130:     return 'ok';
                   3131: }
                   3132: 
1.639     albertel 3133: sub add_filetype {
                   3134:     my ($allfiles,$file,$type)=@_;
                   3135:     if (exists($allfiles->{$file})) {
                   3136: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3137: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3138: 	}
                   3139:     } else {
                   3140: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3141:     }
                   3142: }
                   3143: 
1.493     albertel 3144: sub removeuploadedurl {
1.984     neumanie 3145:     my ($url)=@_;	
                   3146:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3147:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3148: }
                   3149: 
                   3150: sub removeuserfile {
                   3151:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3152:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3153:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3154:     if ($result eq 'ok') {	
1.798     raeburn  3155:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3156:             my $metafile = $fname.'.meta';
                   3157:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3158: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3159:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3160:             my $sqlresult = 
1.823     albertel 3161:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3162:                                         'portfolio_metadata',$group,
                   3163:                                         'delete');
1.798     raeburn  3164:         }
                   3165:     }
                   3166:     return $result;
1.257     www      3167: }
1.15      www      3168: 
1.530     albertel 3169: sub mkdiruserfile {
                   3170:     my ($docuname,$docudom,$dir)=@_;
                   3171:     my $home=&homeserver($docuname,$docudom);
                   3172:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3173: }
                   3174: 
1.531     albertel 3175: sub renameuserfile {
                   3176:     my ($docuname,$docudom,$old,$new)=@_;
                   3177:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3178:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3179:                         &escape("$old").':'.&escape("$new"),$home);
                   3180:     if ($result eq 'ok') {
                   3181:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3182:             my $oldmeta = $old.'.meta';
                   3183:             my $newmeta = $new.'.meta';
                   3184:             my $metaresult = 
                   3185:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3186: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3187:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3188:             my $sqlresult = 
1.823     albertel 3189:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3190:                                         'portfolio_metadata',$group,
                   3191:                                         'delete');
1.798     raeburn  3192:         }
                   3193:     }
                   3194:     return $result;
1.531     albertel 3195: }
                   3196: 
1.14      www      3197: # ------------------------------------------------------------------------- Log
                   3198: 
                   3199: sub log {
                   3200:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3201:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3202: }
                   3203: 
                   3204: # ------------------------------------------------------------------ Course Log
1.352     www      3205: #
                   3206: # This routine flushes several buffers of non-mission-critical nature
                   3207: #
1.157     www      3208: 
                   3209: sub flushcourselogs {
1.352     www      3210:     &logthis('Flushing log buffers');
                   3211: #
                   3212: # course logs
                   3213: # This is a log of all transactions in a course, which can be used
                   3214: # for data mining purposes
                   3215: #
                   3216: # It also collects the courseid database, which lists last transaction
                   3217: # times and course titles for all courseids
                   3218: #
                   3219:     my %courseidbuffer=();
1.921     raeburn  3220:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3221:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3222: 		          &escape($courselogs{$crsid}),
                   3223: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3224: 	    delete $courselogs{$crsid};
                   3225:         } else {
                   3226:             &logthis('Failed to flush log buffer for '.$crsid);
                   3227:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3228:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3229:                         " exceeded maximum size, deleting.</font>");
                   3230:                delete $courselogs{$crsid};
                   3231:             }
1.352     www      3232:         }
1.920     raeburn  3233:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3234:             'description' => $coursedescrbuf{$crsid},
                   3235:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3236:             'type'        => $coursetypebuf{$crsid},
                   3237:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3238:         };
1.191     harris41 3239:     }
1.352     www      3240: #
                   3241: # Write course id database (reverse lookup) to homeserver of courses 
                   3242: # Is used in pickcourse
                   3243: #
1.840     albertel 3244:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3245:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3246:                                     $courseidbuffer{$crs_home},
                   3247:                                     $crs_home,'timeonly');
1.352     www      3248:     }
                   3249: #
                   3250: # File accesses
                   3251: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3252: #
1.449     matthew  3253:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3254:         if ($entry =~ /___count$/) {
                   3255:             my ($dom,$name);
1.807     albertel 3256:             ($dom,$name,undef)=
1.811     albertel 3257: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3258:             if (! defined($dom) || $dom eq '' || 
                   3259:                 ! defined($name) || $name eq '') {
1.620     albertel 3260:                 my $cid = $env{'request.course.id'};
                   3261:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3262:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3263:             }
1.450     matthew  3264:             my $value = $accesshash{$entry};
                   3265:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3266:             my %temphash=($url => $value);
1.449     matthew  3267:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3268:             if ($result eq 'ok') {
                   3269:                 delete $accesshash{$entry};
                   3270:             }
                   3271:         } else {
1.811     albertel 3272:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3273:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3274:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3275:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3276:                 delete $accesshash{$entry};
                   3277:             }
1.185     www      3278:         }
1.191     harris41 3279:     }
1.352     www      3280: #
                   3281: # Roles
                   3282: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3283: #
1.800     albertel 3284:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3285:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3286: 	    split(/\:/,$entry);
                   3287:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3288:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3289:                 $rudom,$runame) eq 'ok') {
                   3290: 	    delete $userrolehash{$entry};
                   3291:         }
                   3292:     }
1.662     raeburn  3293: #
                   3294: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3295: #
                   3296:     my %domrolebuffer = ();
1.1000    raeburn  3297:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3298:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3299:         if ($domrolebuffer{$rudom}) {
                   3300:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3301:                       '='.&escape($domainrolehash{$entry});
                   3302:         } else {
                   3303:             $domrolebuffer{$rudom}.=&escape($entry).
                   3304:                       '='.&escape($domainrolehash{$entry});
                   3305:         }
                   3306:         delete $domainrolehash{$entry};
                   3307:     }
                   3308:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3309: 	my %servers = &get_servers($dom,'library');
                   3310: 	foreach my $tryserver (keys(%servers)) {
                   3311: 	    unless (&reply('domroleput:'.$dom.':'.
                   3312: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3313: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3314: 	    }
1.662     raeburn  3315:         }
                   3316:     }
1.186     www      3317:     $dumpcount++;
1.157     www      3318: }
                   3319: 
                   3320: sub courselog {
                   3321:     my $what=shift;
1.158     www      3322:     $what=time.':'.$what;
1.620     albertel 3323:     unless ($env{'request.course.id'}) { return ''; }
                   3324:     $coursedombuf{$env{'request.course.id'}}=
                   3325:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3326:     $coursenumbuf{$env{'request.course.id'}}=
                   3327:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3328:     $coursehombuf{$env{'request.course.id'}}=
                   3329:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3330:     $coursedescrbuf{$env{'request.course.id'}}=
                   3331:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3332:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3333:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3334:     $courseownerbuf{$env{'request.course.id'}}=
                   3335:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3336:     $coursetypebuf{$env{'request.course.id'}}=
                   3337:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3338:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3339: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3340:     } else {
1.620     albertel 3341: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3342:     }
1.620     albertel 3343:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3344: 	&flushcourselogs();
                   3345:     }
1.158     www      3346: }
                   3347: 
                   3348: sub courseacclog {
                   3349:     my $fnsymb=shift;
1.620     albertel 3350:     unless ($env{'request.course.id'}) { return ''; }
                   3351:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3352:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3353:         $what.=':POST';
1.583     matthew  3354:         # FIXME: Probably ought to escape things....
1.800     albertel 3355: 	foreach my $key (keys(%env)) {
                   3356:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3357:                 my $formitem = $1;
                   3358:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3359:                     $what.=':'.$formitem.'='.$env{$key};
                   3360:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3361:                     $what.=':'.$formitem.'='.$env{$key};
                   3362:                 }
1.158     www      3363:             }
1.191     harris41 3364:         }
1.583     matthew  3365:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3366:         # FIXME: We should not be depending on a form parameter that someone
                   3367:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3368:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3369:             $what.= ':POST';
                   3370:             # FIXME: Probably ought to escape things....
                   3371:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3372:                                  'crsdiscuss') {
1.620     albertel 3373:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3374:             }
                   3375:         }
1.158     www      3376:     }
                   3377:     &courselog($what);
1.149     www      3378: }
                   3379: 
1.185     www      3380: sub countacc {
                   3381:     my $url=&declutter(shift);
1.458     matthew  3382:     return if (! defined($url) || $url eq '');
1.620     albertel 3383:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3384: #
                   3385: # Mark that this url was used in this course
                   3386: #
1.620     albertel 3387:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3388: #
                   3389: # Increase the access count for this resource in this child process
                   3390: #
1.281     www      3391:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3392:     $accesshash{$key}++;
1.185     www      3393: }
1.349     www      3394: 
1.361     www      3395: sub linklog {
                   3396:     my ($from,$to)=@_;
                   3397:     $from=&declutter($from);
                   3398:     $to=&declutter($to);
                   3399:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3400:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3401: }
1.1160    www      3402: 
                   3403: sub statslog {
                   3404:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3405:     if ($users<2) { return; }
                   3406:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3407:             'course'       => $env{'request.course.id'},
                   3408:             'sections'     => '"all"',
                   3409:             'num_students' => $users,
                   3410:             'part'         => $part,
                   3411:             'symb'         => $symb,
                   3412:             'mean_tries'   => $av_attempts,
                   3413:             'deg_of_diff'  => $degdiff});
                   3414:     foreach my $key (keys(%dynstore)) {
                   3415:         $accesshash{$key}=$dynstore{$key};
                   3416:     }
                   3417: }
1.361     www      3418:   
1.349     www      3419: sub userrolelog {
                   3420:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3421:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3422:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3423:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3424:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3425:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3426:        $userrolehash
                   3427:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3428:                     =$tend.':'.$tstart;
1.662     raeburn  3429:     }
1.898     albertel 3430:     if (($env{'request.role'} =~ /dc\./) &&
                   3431: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3432: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3433: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3434:          ($trole=~/^co/))) {
1.898     albertel 3435:        $userrolehash
                   3436:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3437:                     =$tend.':'.$tstart;
                   3438:     }
1.662     raeburn  3439:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3440:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3441:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3442:         ($trole=~/^sc/)) {
                   3443:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3444:        $domainrolehash
                   3445:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3446:                     = $tend.':'.$tstart;
                   3447:     }
1.351     www      3448: }
                   3449: 
1.957     raeburn  3450: sub courserolelog {
                   3451:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3452:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3453:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3454:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3455:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3456:         ($trole eq 'co')) {
1.957     raeburn  3457:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3458:             my $cdom = $1;
                   3459:             my $cnum = $2;
                   3460:             my $sec = $3;
                   3461:             my $namespace = 'rolelog';
                   3462:             my %storehash = (
                   3463:                                role    => $trole,
                   3464:                                start   => $tstart,
                   3465:                                end     => $tend,
                   3466:                                selfenroll => $selfenroll,
                   3467:                                context    => $context,
                   3468:                             );
                   3469:             if ($trole eq 'gr') {
                   3470:                 $namespace = 'groupslog';
                   3471:                 $storehash{'group'} = $sec;
                   3472:             } else {
                   3473:                 $storehash{'section'} = $sec;
                   3474:             }
                   3475:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3476:             if (($trole ne 'st') || ($sec ne '')) {
                   3477:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3478:             }
1.957     raeburn  3479:         }
                   3480:     }
                   3481:     return;
                   3482: }
                   3483: 
1.351     www      3484: sub get_course_adv_roles {
1.948     raeburn  3485:     my ($cid,$codes) = @_;
1.620     albertel 3486:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3487:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3488:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3489:     my %nothide=();
1.800     albertel 3490:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3491:         if ($user !~ /:/) {
                   3492: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3493:         } else {
                   3494:             $nothide{$user}=1;
                   3495:         }
1.470     www      3496:     }
1.351     www      3497:     my %returnhash=();
                   3498:     my %dumphash=
                   3499:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3500:     my $now=time;
1.997     raeburn  3501:     my %privileged;
1.1000    raeburn  3502:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3503: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3504:         if (($tstart) && ($tstart<0)) { next; }
                   3505:         if (($tend) && ($tend<$now)) { next; }
                   3506:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3507:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3508: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3509:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3510:             my %dompersonnel =
1.998     raeburn  3511:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3512:             $privileged{$domain} = {};
                   3513:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3514:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3515:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3516:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3517:                         $privileged{$udom}{$uname} = 1;
                   3518:                     }
                   3519:                 }
                   3520:             }
                   3521:         }
                   3522:         if ((exists($privileged{$domain}{$username})) && 
                   3523:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3524: 	if ($role eq 'cr') { next; }
1.948     raeburn  3525:         if ($codes) {
                   3526:             if ($section) { $role .= ':'.$section; }
                   3527:             if ($returnhash{$role}) {
                   3528:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3529:             } else {
                   3530:                 $returnhash{$role}=$username.':'.$domain;
                   3531:             }
1.351     www      3532:         } else {
1.988     raeburn  3533:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3534:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3535:             if ($returnhash{$key}) {
                   3536: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3537:             } else {
                   3538:                 $returnhash{$key}=$username.':'.$domain;
                   3539:             }
1.351     www      3540:         }
1.948     raeburn  3541:     }
1.400     www      3542:     return %returnhash;
                   3543: }
                   3544: 
                   3545: sub get_my_roles {
1.937     raeburn  3546:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3547:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3548:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3549:     my (%dumphash,%nothide);
1.1086    raeburn  3550:     if ($context eq 'userroles') {
                   3551:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3552:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3553:     } else {
                   3554:         %dumphash=
1.400     www      3555:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3556:         if ($hidepriv) {
                   3557:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3558:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3559:                 if ($user !~ /:/) {
                   3560:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3561:                 } else {
                   3562:                     $nothide{$user} = 1;
                   3563:                 }
                   3564:             }
                   3565:         }
1.858     raeburn  3566:     }
1.400     www      3567:     my %returnhash=();
                   3568:     my $now=time;
1.999     raeburn  3569:     my %privileged;
1.800     albertel 3570:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3571:         my ($role,$tend,$tstart);
                   3572:         if ($context eq 'userroles') {
1.1149    raeburn  3573:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3574: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3575:         } else {
                   3576:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3577:         }
1.400     www      3578:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3579:         my $status = 'active';
1.939     raeburn  3580:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3581:             $status = 'previous';
                   3582:         } 
                   3583:         if (($tstart) && ($now<$tstart)) {
                   3584:             $status = 'future';
                   3585:         }
                   3586:         if (ref($types) eq 'ARRAY') {
                   3587:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3588:                 next;
                   3589:             } 
                   3590:         } else {
                   3591:             if ($status ne 'active') {
                   3592:                 next;
                   3593:             }
                   3594:         }
1.867     raeburn  3595:         my ($rolecode,$username,$domain,$section,$area);
                   3596:         if ($context eq 'userroles') {
                   3597:             ($area,$rolecode) = split(/_/,$entry);
                   3598:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3599:         } else {
                   3600:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3601:         }
1.832     raeburn  3602:         if (ref($roledoms) eq 'ARRAY') {
                   3603:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3604:                 next;
                   3605:             }
                   3606:         }
                   3607:         if (ref($roles) eq 'ARRAY') {
                   3608:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3609:                 if ($role =~ /^cr\//) {
                   3610:                     if (!grep(/^cr$/,@{$roles})) {
                   3611:                         next;
                   3612:                     }
1.1104    raeburn  3613:                 } elsif ($role =~ /^gr\//) {
                   3614:                     if (!grep(/^gr$/,@{$roles})) {
                   3615:                         next;
                   3616:                     }
1.922     raeburn  3617:                 } else {
                   3618:                     next;
                   3619:                 }
1.832     raeburn  3620:             }
1.867     raeburn  3621:         }
1.937     raeburn  3622:         if ($hidepriv) {
1.999     raeburn  3623:             if ($context eq 'userroles') {
                   3624:                 if ((&privileged($username,$domain)) &&
                   3625:                     (!$nothide{$username.':'.$domain})) {
                   3626:                     next;
                   3627:                 }
                   3628:             } else {
                   3629:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3630:                     my %dompersonnel =
                   3631:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3632:                     $privileged{$domain} = {};
                   3633:                     if (keys(%dompersonnel)) {
                   3634:                         foreach my $server (keys(%dompersonnel)) {
                   3635:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3636:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3637:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3638:                                     $privileged{$udom}{$uname} = $trole;
                   3639:                                 }
                   3640:                             }
                   3641:                         }
                   3642:                     }
                   3643:                 }
                   3644:                 if (exists($privileged{$domain}{$username})) {
                   3645:                     if (!$nothide{$username.':'.$domain}) {
                   3646:                         next;
                   3647:                     }
                   3648:                 }
1.937     raeburn  3649:             }
                   3650:         }
1.933     raeburn  3651:         if ($withsec) {
                   3652:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3653:                 $tstart.':'.$tend;
                   3654:         } else {
                   3655:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3656:         }
1.832     raeburn  3657:     }
1.373     www      3658:     return %returnhash;
1.399     www      3659: }
                   3660: 
                   3661: # ----------------------------------------------------- Frontpage Announcements
                   3662: #
                   3663: #
                   3664: 
                   3665: sub postannounce {
                   3666:     my ($server,$text)=@_;
1.844     albertel 3667:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3668:     unless ($text=~/\w/) { $text=''; }
                   3669:     return &reply('setannounce:'.&escape($text),$server);
                   3670: }
                   3671: 
                   3672: sub getannounce {
1.448     albertel 3673: 
                   3674:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3675: 	my $announcement='';
1.800     albertel 3676: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3677: 	close($fh);
1.399     www      3678: 	if ($announcement=~/\w/) { 
                   3679: 	    return 
                   3680:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3681:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3682: 	} else {
                   3683: 	    return '';
                   3684: 	}
                   3685:     } else {
                   3686: 	return '';
                   3687:     }
1.351     www      3688: }
1.353     www      3689: 
                   3690: # ---------------------------------------------------------- Course ID routines
                   3691: # Deal with domain's nohist_courseid.db files
                   3692: #
                   3693: 
                   3694: sub courseidput {
1.921     raeburn  3695:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3696:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3697:     my $outcome;
                   3698:     if ($caller eq 'timeonly') {
                   3699:         my $cids = '';
                   3700:         foreach my $item (keys(%$storehash)) {
                   3701:             $cids.=&escape($item).'&';
                   3702:         }
                   3703:         $cids=~s/\&$//;
                   3704:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3705:                           $coursehome);       
                   3706:     } else {
                   3707:         my $items = '';
                   3708:         foreach my $item (keys(%$storehash)) {
                   3709:             $items.= &escape($item).'='.
                   3710:                      &freeze_escape($$storehash{$item}).'&';
                   3711:         }
                   3712:         $items=~s/\&$//;
                   3713:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3714:                           $coursehome);
1.918     raeburn  3715:     }
                   3716:     if ($outcome eq 'unknown_cmd') {
                   3717:         my $what;
                   3718:         foreach my $cid (keys(%$storehash)) {
                   3719:             $what .= &escape($cid).'=';
1.921     raeburn  3720:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3721:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3722:             }
                   3723:             $what =~ s/\:$/&/;
                   3724:         }
                   3725:         $what =~ s/\&$//;  
                   3726:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3727:     } else {
                   3728:         return $outcome;
                   3729:     }
1.353     www      3730: }
                   3731: 
                   3732: sub courseiddump {
1.921     raeburn  3733:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3734:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3735:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3736:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3737:     my $as_hash = 1;
                   3738:     my %returnhash;
                   3739:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3740:     my %libserv = &all_library();
                   3741:     foreach my $tryserver (keys(%libserv)) {
                   3742:         if ( (  $hostidflag == 1 
                   3743: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3744: 	     || (!defined($hostidflag)) ) {
                   3745: 
1.918     raeburn  3746: 	    if (($domfilter eq '') ||
                   3747: 		(&host_domain($tryserver) eq $domfilter)) {
                   3748:                 my $rep = 
                   3749:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3750:                          $sincefilter.':'.&escape($descfilter).':'.
                   3751:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3752:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3753:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3754:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3755:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3756:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3757:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3758:                          &escape($creationcontext).':'.$domcloner,
                   3759:                          $tryserver);
1.918     raeburn  3760:                 my @pairs=split(/\&/,$rep);
                   3761:                 foreach my $item (@pairs) {
                   3762:                     my ($key,$value)=split(/\=/,$item,2);
                   3763:                     $key = &unescape($key);
                   3764:                     next if ($key =~ /^error: 2 /);
                   3765:                     my $result = &thaw_unescape($value);
                   3766:                     if (ref($result) eq 'HASH') {
                   3767:                         $returnhash{$key}=$result;
                   3768:                     } else {
1.921     raeburn  3769:                         my @responses = split(/:/,$value);
                   3770:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3771:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3772:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3773:                         }
1.1008    raeburn  3774:                     }
1.353     www      3775:                 }
                   3776:             }
                   3777:         }
                   3778:     }
                   3779:     return %returnhash;
                   3780: }
                   3781: 
1.1055    raeburn  3782: sub courselastaccess {
                   3783:     my ($cdom,$cnum,$hostidref) = @_;
                   3784:     my %returnhash;
                   3785:     if ($cdom && $cnum) {
                   3786:         my $chome = &homeserver($cnum,$cdom);
                   3787:         if ($chome ne 'no_host') {
                   3788:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3789:             &extract_lastaccess(\%returnhash,$rep);
                   3790:         }
                   3791:     } else {
                   3792:         if (!$cdom) { $cdom=''; }
                   3793:         my %libserv = &all_library();
                   3794:         foreach my $tryserver (keys(%libserv)) {
                   3795:             if (ref($hostidref) eq 'ARRAY') {
                   3796:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3797:             } 
                   3798:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3799:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3800:                 &extract_lastaccess(\%returnhash,$rep);
                   3801:             }
                   3802:         }
                   3803:     }
                   3804:     return %returnhash;
                   3805: }
                   3806: 
                   3807: sub extract_lastaccess {
                   3808:     my ($returnhash,$rep) = @_;
                   3809:     if (ref($returnhash) eq 'HASH') {
                   3810:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3811:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3812:                  $rep eq '') {
                   3813:             my @pairs=split(/\&/,$rep);
                   3814:             foreach my $item (@pairs) {
                   3815:                 my ($key,$value)=split(/\=/,$item,2);
                   3816:                 $key = &unescape($key);
                   3817:                 next if ($key =~ /^error: 2 /);
                   3818:                 $returnhash->{$key} = &thaw_unescape($value);
                   3819:             }
                   3820:         }
                   3821:     }
                   3822:     return;
                   3823: }
                   3824: 
1.658     raeburn  3825: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3826: 
                   3827: sub dcmailput {
1.685     raeburn  3828:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3829:     my $status = &Apache::lonnet::critical(
1.740     www      3830:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3831:        &escape($message),$server);
1.662     raeburn  3832:     return $status;
                   3833: }
                   3834: 
1.658     raeburn  3835: sub dcmaildump {
                   3836:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3837:     my %returnhash=();
1.846     albertel 3838: 
                   3839:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3840:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3841:                                                          &escape($enddate).':';
                   3842: 	my @esc_senders=map { &escape($_)} @$senders;
                   3843: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3844: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3845:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3846:             if (($key) && ($value)) {
                   3847:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3848:             }
                   3849:         }
                   3850:     }
                   3851:     return %returnhash;
                   3852: }
1.662     raeburn  3853: # ---------------------------------------------------------- Domain roles
                   3854: 
                   3855: sub get_domain_roles {
                   3856:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3857:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3858:         $startdate = '.';
                   3859:     }
1.1018    raeburn  3860:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3861:         $enddate = '.';
                   3862:     }
1.922     raeburn  3863:     my $rolelist;
                   3864:     if (ref($roles) eq 'ARRAY') {
                   3865:         $rolelist = join(':',@{$roles});
                   3866:     }
1.662     raeburn  3867:     my %personnel = ();
1.841     albertel 3868: 
                   3869:     my %servers = &get_servers($dom,'library');
                   3870:     foreach my $tryserver (keys(%servers)) {
                   3871: 	%{$personnel{$tryserver}}=();
                   3872: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3873: 					    &escape($startdate).':'.
                   3874: 					    &escape($enddate).':'.
                   3875: 					    &escape($rolelist), $tryserver))) {
                   3876: 	    my ($key,$value) = split(/\=/,$line,2);
                   3877: 	    if (($key) && ($value)) {
                   3878: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3879: 	    }
                   3880: 	}
1.662     raeburn  3881:     }
                   3882:     return %personnel;
                   3883: }
1.658     raeburn  3884: 
1.1057    www      3885: # ----------------------------------------------------------- Interval timing 
1.149     www      3886: 
1.1153    www      3887: {
                   3888: # Caches needed for speedup of navmaps
                   3889: # We don't want to cache this for very long at all (5 seconds at most)
                   3890: # 
                   3891: # The user for whom we cache
                   3892: my $cachedkey='';
                   3893: # The cached times for this user
                   3894: my %cachedtimes=();
                   3895: # When this was last done
                   3896: my $cachedtime=();
                   3897: 
                   3898: sub load_all_first_access {
1.1154    raeburn  3899:     my ($uname,$udom)=@_;
1.1156    www      3900:     if (($cachedkey eq $uname.':'.$udom) &&
1.1154    raeburn  3901:         (abs($cachedtime-time)<5)) {
                   3902:         return;
                   3903:     }
                   3904:     $cachedtime=time;
                   3905:     $cachedkey=$uname.':'.$udom;
                   3906:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3907: }
                   3908: 
1.504     albertel 3909: sub get_first_access {
                   3910:     my ($type,$argsymb)=@_;
1.790     albertel 3911:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3912:     if ($argsymb) { $symb=$argsymb; }
                   3913:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3914:     if ($type eq 'course') {
                   3915: 	$res='course';
                   3916:     } elsif ($type eq 'map') {
1.588     albertel 3917: 	$res=&symbread($map);
                   3918:     } else {
                   3919: 	$res=$symb;
                   3920:     }
1.1153    www      3921:     &load_all_first_access($uname,$udom);
                   3922:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3923: }
                   3924: 
                   3925: sub set_first_access {
                   3926:     my ($type)=@_;
1.790     albertel 3927:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3928:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3929:     if ($type eq 'course') {
                   3930: 	$res='course';
                   3931:     } elsif ($type eq 'map') {
1.588     albertel 3932: 	$res=&symbread($map);
                   3933:     } else {
                   3934: 	$res=$symb;
                   3935:     }
1.1153    www      3936:     $cachedkey='';
1.588     albertel 3937:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3938:     if (!$firstaccess) {
1.588     albertel 3939: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3940:     }
                   3941:     return 'already_set';
1.504     albertel 3942: }
1.1153    www      3943: }
1.110     www      3944: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3945: 
                   3946: sub expirespread {
                   3947:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3948:     my $cid=$env{'request.course.id'}; 
1.110     www      3949:     if ($cid) {
                   3950:        my $now=time;
                   3951:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3952:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3953:                             $env{'course.'.$cid.'.num'}.
1.110     www      3954: 	        	    ':nohist_expirationdates:'.
                   3955:                             &escape($key).'='.$now,
1.620     albertel 3956:                             $env{'course.'.$cid.'.home'})
1.110     www      3957:     }
                   3958:     return 'ok';
1.14      www      3959: }
                   3960: 
1.109     www      3961: # ----------------------------------------------------- Devalidate Spreadsheets
                   3962: 
                   3963: sub devalidate {
1.325     www      3964:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3965:     my $cid=$env{'request.course.id'}; 
1.109     www      3966:     if ($cid) {
1.391     matthew  3967:         # delete the stored spreadsheets for
                   3968:         # - the student level sheet of this user in course's homespace
                   3969:         # - the assessment level sheet for this resource 
                   3970:         #   for this user in user's homespace
1.553     albertel 3971: 	# - current conditional state info
1.325     www      3972: 	my $key=$uname.':'.$udom.':';
1.109     www      3973:         my $status=
1.299     matthew  3974: 	    &del('nohist_calculatedsheets',
1.391     matthew  3975: 		 [$key.'studentcalc:'],
1.620     albertel 3976: 		 $env{'course.'.$cid.'.domain'},
                   3977: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3978: 		.' '.
                   3979: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3980: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3981:         unless ($status eq 'ok ok') {
                   3982:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3983:                     $uname.' at '.$udom.' for '.
1.109     www      3984: 		    $symb.': '.$status);
1.133     albertel 3985:         }
1.553     albertel 3986: 	&delenv('user.state.'.$cid);
1.109     www      3987:     }
                   3988: }
                   3989: 
1.265     albertel 3990: sub get_scalar {
                   3991:     my ($string,$end) = @_;
                   3992:     my $value;
                   3993:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3994: 	$value = $1;
                   3995:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3996: 	$value = $1;
                   3997:     }
                   3998:     return &unescape($value);
                   3999: }
                   4000: 
                   4001: sub array2str {
                   4002:   my (@array) = @_;
                   4003:   my $result=&arrayref2str(\@array);
                   4004:   $result=~s/^__ARRAY_REF__//;
                   4005:   $result=~s/__END_ARRAY_REF__$//;
                   4006:   return $result;
                   4007: }
                   4008: 
1.204     albertel 4009: sub arrayref2str {
                   4010:   my ($arrayref) = @_;
1.265     albertel 4011:   my $result='__ARRAY_REF__';
1.204     albertel 4012:   foreach my $elem (@$arrayref) {
1.265     albertel 4013:     if(ref($elem) eq 'ARRAY') {
                   4014:       $result.=&arrayref2str($elem).'&';
                   4015:     } elsif(ref($elem) eq 'HASH') {
                   4016:       $result.=&hashref2str($elem).'&';
                   4017:     } elsif(ref($elem)) {
                   4018:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4019:     } else {
                   4020:       $result.=&escape($elem).'&';
                   4021:     }
                   4022:   }
                   4023:   $result=~s/\&$//;
1.265     albertel 4024:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4025:   return $result;
                   4026: }
                   4027: 
1.168     albertel 4028: sub hash2str {
1.204     albertel 4029:   my (%hash) = @_;
                   4030:   my $result=&hashref2str(\%hash);
1.265     albertel 4031:   $result=~s/^__HASH_REF__//;
                   4032:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4033:   return $result;
                   4034: }
                   4035: 
                   4036: sub hashref2str {
                   4037:   my ($hashref)=@_;
1.265     albertel 4038:   my $result='__HASH_REF__';
1.800     albertel 4039:   foreach my $key (sort(keys(%$hashref))) {
                   4040:     if (ref($key) eq 'ARRAY') {
                   4041:       $result.=&arrayref2str($key).'=';
                   4042:     } elsif (ref($key) eq 'HASH') {
                   4043:       $result.=&hashref2str($key).'=';
                   4044:     } elsif (ref($key)) {
1.265     albertel 4045:       $result.='=';
1.800     albertel 4046:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4047:     } else {
1.1132    raeburn  4048: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4049:     }
                   4050: 
1.800     albertel 4051:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4052:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4053:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4054:       $result.=&hashref2str($hashref->{$key}).'&';
                   4055:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4056:        $result.='&';
1.800     albertel 4057:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4058:     } else {
1.800     albertel 4059:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4060:     }
                   4061:   }
1.168     albertel 4062:   $result=~s/\&$//;
1.265     albertel 4063:   $result .= '__END_HASH_REF__';
1.168     albertel 4064:   return $result;
                   4065: }
                   4066: 
                   4067: sub str2hash {
1.265     albertel 4068:     my ($string)=@_;
                   4069:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4070:     return %$hash;
                   4071: }
                   4072: 
                   4073: sub str2hashref {
1.168     albertel 4074:   my ($string) = @_;
1.265     albertel 4075: 
                   4076:   my %hash;
                   4077: 
                   4078:   if($string !~ /^__HASH_REF__/) {
                   4079:       if (! ($string eq '' || !defined($string))) {
                   4080: 	  $hash{'error'}='Not hash reference';
                   4081:       }
                   4082:       return (\%hash, $string);
                   4083:   }
                   4084: 
                   4085:   $string =~ s/^__HASH_REF__//;
                   4086: 
                   4087:   while($string !~ /^__END_HASH_REF__/) {
                   4088:       #key
                   4089:       my $key='';
                   4090:       if($string =~ /^__HASH_REF__/) {
                   4091:           ($key, $string)=&str2hashref($string);
                   4092:           if(defined($key->{'error'})) {
                   4093:               $hash{'error'}='Bad data';
                   4094:               return (\%hash, $string);
                   4095:           }
                   4096:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4097:           ($key, $string)=&str2arrayref($string);
                   4098:           if($key->[0] eq 'Array reference error') {
                   4099:               $hash{'error'}='Bad data';
                   4100:               return (\%hash, $string);
                   4101:           }
                   4102:       } else {
                   4103:           $string =~ s/^(.*?)=//;
1.267     albertel 4104: 	  $key=&unescape($1);
1.265     albertel 4105:       }
                   4106:       $string =~ s/^=//;
                   4107: 
                   4108:       #value
                   4109:       my $value='';
                   4110:       if($string =~ /^__HASH_REF__/) {
                   4111:           ($value, $string)=&str2hashref($string);
                   4112:           if(defined($value->{'error'})) {
                   4113:               $hash{'error'}='Bad data';
                   4114:               return (\%hash, $string);
                   4115:           }
                   4116:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4117:           ($value, $string)=&str2arrayref($string);
                   4118:           if($value->[0] eq 'Array reference error') {
                   4119:               $hash{'error'}='Bad data';
                   4120:               return (\%hash, $string);
                   4121:           }
                   4122:       } else {
                   4123: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4124:       }
                   4125:       $string =~ s/^&//;
                   4126: 
                   4127:       $hash{$key}=$value;
1.204     albertel 4128:   }
1.265     albertel 4129: 
                   4130:   $string =~ s/^__END_HASH_REF__//;
                   4131: 
                   4132:   return (\%hash, $string);
1.204     albertel 4133: }
                   4134: 
                   4135: sub str2array {
1.265     albertel 4136:     my ($string)=@_;
                   4137:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4138:     return @$array;
                   4139: }
                   4140: 
                   4141: sub str2arrayref {
1.204     albertel 4142:   my ($string) = @_;
1.265     albertel 4143:   my @array;
                   4144: 
                   4145:   if($string !~ /^__ARRAY_REF__/) {
                   4146:       if (! ($string eq '' || !defined($string))) {
                   4147: 	  $array[0]='Array reference error';
                   4148:       }
                   4149:       return (\@array, $string);
                   4150:   }
                   4151: 
                   4152:   $string =~ s/^__ARRAY_REF__//;
                   4153: 
                   4154:   while($string !~ /^__END_ARRAY_REF__/) {
                   4155:       my $value='';
                   4156:       if($string =~ /^__HASH_REF__/) {
                   4157:           ($value, $string)=&str2hashref($string);
                   4158:           if(defined($value->{'error'})) {
                   4159:               $array[0] ='Array reference error';
                   4160:               return (\@array, $string);
                   4161:           }
                   4162:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4163:           ($value, $string)=&str2arrayref($string);
                   4164:           if($value->[0] eq 'Array reference error') {
                   4165:               $array[0] ='Array reference error';
                   4166:               return (\@array, $string);
                   4167:           }
                   4168:       } else {
                   4169: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4170:       }
                   4171:       $string =~ s/^&//;
                   4172: 
                   4173:       push(@array, $value);
1.191     harris41 4174:   }
1.265     albertel 4175: 
                   4176:   $string =~ s/^__END_ARRAY_REF__//;
                   4177: 
                   4178:   return (\@array, $string);
1.168     albertel 4179: }
                   4180: 
1.167     albertel 4181: # -------------------------------------------------------------------Temp Store
                   4182: 
1.168     albertel 4183: sub tmpreset {
                   4184:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4185:   if (!$symb) {
                   4186:     $symb=&symbread();
1.620     albertel 4187:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4188:   }
                   4189:   $symb=escape($symb);
                   4190: 
1.620     albertel 4191:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4192:   $namespace=~s/\//\_/g;
                   4193:   $namespace=~s/\W//g;
                   4194: 
1.620     albertel 4195:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4196:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4197:   if ($domain eq 'public' && $stuname eq 'public') {
                   4198:       $stuname=$ENV{'REMOTE_ADDR'};
                   4199:   }
1.1117    foxr     4200:   my $path=LONCAPA::tempdir();
1.168     albertel 4201:   my %hash;
                   4202:   if (tie(%hash,'GDBM_File',
                   4203: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4204: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4205:     foreach my $key (keys(%hash)) {
1.180     albertel 4206:       if ($key=~ /:$symb/) {
1.168     albertel 4207: 	delete($hash{$key});
                   4208:       }
                   4209:     }
                   4210:   }
                   4211: }
                   4212: 
1.167     albertel 4213: sub tmpstore {
1.168     albertel 4214:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4215: 
                   4216:   if (!$symb) {
                   4217:     $symb=&symbread();
1.620     albertel 4218:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4219:   }
                   4220:   $symb=escape($symb);
                   4221: 
                   4222:   if (!$namespace) {
                   4223:     # I don't think we would ever want to store this for a course.
                   4224:     # it seems this will only be used if we don't have a course.
1.620     albertel 4225:     #$namespace=$env{'request.course.id'};
1.168     albertel 4226:     #if (!$namespace) {
1.620     albertel 4227:       $namespace=$env{'request.state'};
1.168     albertel 4228:     #}
                   4229:   }
                   4230:   $namespace=~s/\//\_/g;
                   4231:   $namespace=~s/\W//g;
1.620     albertel 4232:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4233:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4234:   if ($domain eq 'public' && $stuname eq 'public') {
                   4235:       $stuname=$ENV{'REMOTE_ADDR'};
                   4236:   }
1.168     albertel 4237:   my $now=time;
                   4238:   my %hash;
1.1117    foxr     4239:   my $path=LONCAPA::tempdir();
1.168     albertel 4240:   if (tie(%hash,'GDBM_File',
                   4241: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4242: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4243:     $hash{"version:$symb"}++;
                   4244:     my $version=$hash{"version:$symb"};
                   4245:     my $allkeys=''; 
                   4246:     foreach my $key (keys(%$storehash)) {
                   4247:       $allkeys.=$key.':';
1.591     albertel 4248:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4249:     }
                   4250:     $hash{"$version:$symb:timestamp"}=$now;
                   4251:     $allkeys.='timestamp';
                   4252:     $hash{"$version:keys:$symb"}=$allkeys;
                   4253:     if (untie(%hash)) {
                   4254:       return 'ok';
                   4255:     } else {
                   4256:       return "error:$!";
                   4257:     }
                   4258:   } else {
                   4259:     return "error:$!";
                   4260:   }
                   4261: }
1.167     albertel 4262: 
1.168     albertel 4263: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4264: 
1.168     albertel 4265: sub tmprestore {
                   4266:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4267: 
1.168     albertel 4268:   if (!$symb) {
                   4269:     $symb=&symbread();
1.620     albertel 4270:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4271:   }
                   4272:   $symb=escape($symb);
                   4273: 
1.620     albertel 4274:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4275: 
1.620     albertel 4276:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4277:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4278:   if ($domain eq 'public' && $stuname eq 'public') {
                   4279:       $stuname=$ENV{'REMOTE_ADDR'};
                   4280:   }
1.168     albertel 4281:   my %returnhash;
                   4282:   $namespace=~s/\//\_/g;
                   4283:   $namespace=~s/\W//g;
                   4284:   my %hash;
1.1117    foxr     4285:   my $path=LONCAPA::tempdir();
1.168     albertel 4286:   if (tie(%hash,'GDBM_File',
                   4287: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4288: 	  &GDBM_READER(),0640)) {
1.168     albertel 4289:     my $version=$hash{"version:$symb"};
                   4290:     $returnhash{'version'}=$version;
                   4291:     my $scope;
                   4292:     for ($scope=1;$scope<=$version;$scope++) {
                   4293:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4294:       my @keys=split(/:/,$vkeys);
                   4295:       my $key;
                   4296:       $returnhash{"$scope:keys"}=$vkeys;
                   4297:       foreach $key (@keys) {
1.591     albertel 4298: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4299: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4300:       }
                   4301:     }
1.168     albertel 4302:     if (!(untie(%hash))) {
                   4303:       return "error:$!";
                   4304:     }
                   4305:   } else {
                   4306:     return "error:$!";
                   4307:   }
                   4308:   return %returnhash;
1.167     albertel 4309: }
                   4310: 
1.9       www      4311: # ----------------------------------------------------------------------- Store
                   4312: 
                   4313: sub store {
1.124     www      4314:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4315:     my $home='';
                   4316: 
1.168     albertel 4317:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4318: 
1.213     www      4319:     $symb=&symbclean($symb);
1.122     albertel 4320:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4321: 
1.620     albertel 4322:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4323:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4324: 
                   4325:     &devalidate($symb,$stuname,$domain);
1.109     www      4326: 
                   4327:     $symb=escape($symb);
1.187     www      4328:     if (!$namespace) { 
1.620     albertel 4329:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4330:           return ''; 
                   4331:        } 
                   4332:     }
1.620     albertel 4333:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4334: 
                   4335:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4336:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4337: 
1.12      www      4338:     my $namevalue='';
1.800     albertel 4339:     foreach my $key (keys(%$storehash)) {
                   4340:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4341:     }
1.12      www      4342:     $namevalue=~s/\&$//;
1.187     www      4343:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4344:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4345: }
                   4346: 
1.47      www      4347: # -------------------------------------------------------------- Critical Store
                   4348: 
                   4349: sub cstore {
1.124     www      4350:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4351:     my $home='';
                   4352: 
1.168     albertel 4353:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4354: 
1.213     www      4355:     $symb=&symbclean($symb);
1.122     albertel 4356:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4357: 
1.620     albertel 4358:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4359:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4360: 
                   4361:     &devalidate($symb,$stuname,$domain);
1.109     www      4362: 
                   4363:     $symb=escape($symb);
1.187     www      4364:     if (!$namespace) { 
1.620     albertel 4365:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4366:           return ''; 
                   4367:        } 
                   4368:     }
1.620     albertel 4369:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4370: 
                   4371:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4372:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4373: 
1.47      www      4374:     my $namevalue='';
1.800     albertel 4375:     foreach my $key (keys(%$storehash)) {
                   4376:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4377:     }
1.47      www      4378:     $namevalue=~s/\&$//;
1.187     www      4379:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4380:     return critical
                   4381:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4382: }
                   4383: 
1.9       www      4384: # --------------------------------------------------------------------- Restore
                   4385: 
                   4386: sub restore {
1.124     www      4387:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4388:     my $home='';
                   4389: 
1.168     albertel 4390:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4391: 
1.122     albertel 4392:     if (!$symb) {
                   4393:       unless ($symb=escape(&symbread())) { return ''; }
                   4394:     } else {
1.213     www      4395:       $symb=&escape(&symbclean($symb));
1.122     albertel 4396:     }
1.188     www      4397:     if (!$namespace) { 
1.620     albertel 4398:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4399:           return ''; 
                   4400:        } 
                   4401:     }
1.620     albertel 4402:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4403:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4404:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4405:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4406: 
1.12      www      4407:     my %returnhash=();
1.800     albertel 4408:     foreach my $line (split(/\&/,$answer)) {
                   4409: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4410:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4411:     }
1.75      www      4412:     my $version;
                   4413:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4414:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4415:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4416:        }
1.75      www      4417:     }
1.13      www      4418:     return %returnhash;
1.34      www      4419: }
                   4420: 
                   4421: # ---------------------------------------------------------- Course Description
1.1118    foxr     4422: #
                   4423: #  
1.34      www      4424: 
                   4425: sub coursedescription {
1.731     albertel 4426:     my ($courseid,$args)=@_;
1.34      www      4427:     $courseid=~s/^\///;
1.49      www      4428:     $courseid=~s/\_/\//g;
1.34      www      4429:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4430:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4431:     my $normalid=$cdomain.'_'.$cnum;
                   4432:     # need to always cache even if we get errors otherwise we keep 
                   4433:     # trying and trying and trying to get the course description.
                   4434:     my %envhash=();
                   4435:     my %returnhash=();
1.731     albertel 4436:     
                   4437:     my $expiretime=600;
                   4438:     if ($env{'request.course.id'} eq $normalid) {
                   4439: 	$expiretime=120;
                   4440:     }
                   4441: 
                   4442:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4443:     if (!$args->{'freshen_cache'}
                   4444: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4445: 	foreach my $key (keys(%env)) {
                   4446: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4447: 	    my ($setting) = $1;
                   4448: 	    $returnhash{$setting} = $env{$key};
                   4449: 	}
                   4450: 	return %returnhash;
                   4451:     }
                   4452: 
1.1118    foxr     4453:     # get the data again
                   4454: 
1.731     albertel 4455:     if (!$args->{'one_time'}) {
                   4456: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4457:     }
1.811     albertel 4458: 
1.34      www      4459:     if ($chome ne 'no_host') {
1.302     albertel 4460:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4461:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4462: 	   my $username = $env{'user.name'}; # Defult username
                   4463: 	   if(defined $args->{'user'}) {
                   4464: 	       $username = $args->{'user'};
                   4465: 	   }
1.129     albertel 4466:            $returnhash{'home'}= $chome;
                   4467: 	   $returnhash{'domain'} = $cdomain;
                   4468: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4469:            if (!defined($returnhash{'type'})) {
                   4470:                $returnhash{'type'} = 'Course';
                   4471:            }
1.130     albertel 4472:            while (my ($name,$value) = each %returnhash) {
1.53      www      4473:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4474:            }
1.270     www      4475:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4476:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4477: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4478:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4479:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4480:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4481:        }
                   4482:     }
1.731     albertel 4483:     if (!$args->{'one_time'}) {
1.949     raeburn  4484: 	&appenv(\%envhash);
1.731     albertel 4485:     }
1.302     albertel 4486:     return %returnhash;
1.461     www      4487: }
                   4488: 
1.1080    raeburn  4489: sub update_released_required {
                   4490:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4491:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4492:         $cid = $env{'request.course.id'};
                   4493:         $cdom = $env{'course.'.$cid.'.domain'};
                   4494:         $cnum = $env{'course.'.$cid.'.num'};
                   4495:         $chome = $env{'course.'.$cid.'.home'};
                   4496:     }
                   4497:     if ($needsrelease) {
                   4498:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4499:         my $needsupdate;
                   4500:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4501:             $needsupdate = 1;
                   4502:         } else {
                   4503:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4504:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4505:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4506:                 $needsupdate = 1;
                   4507:             }
                   4508:         }
                   4509:         if ($needsupdate) {
                   4510:             my %needshash = (
                   4511:                              'internal.releaserequired' => $needsrelease,
                   4512:                             );
                   4513:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4514:             if ($putresult eq 'ok') {
                   4515:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4516:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4517:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4518:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4519:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4520:                 }
                   4521:             }
                   4522:         }
                   4523:     }
                   4524:     return;
                   4525: }
                   4526: 
1.461     www      4527: # -------------------------------------------------See if a user is privileged
                   4528: 
                   4529: sub privileged {
                   4530:     my ($username,$domain)=@_;
                   4531:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4532: 			&homeserver($username,$domain));
1.1033    raeburn  4533:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4534:         ($rolesdump =~ /^error:/)) {
                   4535:         return 0;
                   4536:     }
1.461     www      4537:     my $now=time;
                   4538:     if ($rolesdump ne '') {
1.800     albertel 4539:         foreach my $entry (split(/&/,$rolesdump)) {
                   4540: 	    if ($entry!~/^rolesdef_/) {
                   4541: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4542: 		$area=~s/\_\w\w$//;
                   4543: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4544: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4545: 		    my $active=1;
                   4546: 		    if ($tend) {
                   4547: 			if ($tend<$now) { $active=0; }
                   4548: 		    }
                   4549: 		    if ($tstart) {
                   4550: 			if ($tstart>$now) { $active=0; }
                   4551: 		    }
                   4552: 		    if ($active) { return 1; }
                   4553: 		}
                   4554: 	    }
                   4555: 	}
                   4556:     }
                   4557:     return 0;
1.9       www      4558: }
1.1       albertel 4559: 
1.103     harris41 4560: # -------------------------------------------------------- Get user privileges
1.11      www      4561: 
                   4562: sub rolesinit {
                   4563:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4564:     my $now=time;
                   4565:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4566:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4567:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4568:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4569:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4570:         return \%userroles;
                   4571:     }
1.11      www      4572:     my %allroles=();
1.678     raeburn  4573:     my %allgroups=();   
1.11      www      4574: 
                   4575:     if ($rolesdump ne '') {
1.800     albertel 4576:         foreach my $entry (split(/&/,$rolesdump)) {
                   4577: 	  if ($entry!~/^rolesdef_/) {
                   4578:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4579: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4580:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4581: 	    if ($role=~/^cr/) { 
1.807     albertel 4582: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4583: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4584: 		    ($tend,$tstart)=split('_',$trest);
                   4585: 		} else {
                   4586: 		    $trole=$role;
                   4587: 		}
1.678     raeburn  4588:             } elsif ($role =~ m|^gr/|) {
                   4589:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4590:                 next if ($tstart eq '-1');
1.678     raeburn  4591:                 ($trole,$group_privs) = split(/\//,$trole);
                   4592:                 $group_privs = &unescape($group_privs);
1.587     albertel 4593: 	    } else {
                   4594: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4595: 	    }
1.743     albertel 4596: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4597: 					 $username);
                   4598: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4599:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4600:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4601:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4602: 		my $spec=$trole.'.'.$area;
                   4603: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4604: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4605:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4606:                 } elsif ($trole eq 'gr') {
                   4607:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4608: 		} else {
1.567     raeburn  4609:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4610: 		}
1.12      www      4611:             }
1.662     raeburn  4612:           }
1.191     harris41 4613:         }
1.743     albertel 4614:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4615:         $userroles{'user.adv'}    = $adv;
                   4616: 	$userroles{'user.author'} = $author;
1.620     albertel 4617:         $env{'user.adv'}=$adv;
1.11      www      4618:     }
1.743     albertel 4619:     return \%userroles;  
1.11      www      4620: }
                   4621: 
1.567     raeburn  4622: sub set_arearole {
                   4623:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4624: # log the associated role with the area
                   4625:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4626:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4627: }
                   4628: 
                   4629: sub custom_roleprivs {
                   4630:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4631:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4632:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4633:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4634:         my ($rdummy,$roledef)=
                   4635:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4636:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4637:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4638:             if (defined($syspriv)) {
1.1043    raeburn  4639:                 if ($trest =~ /^$match_community$/) {
                   4640:                     $syspriv =~ s/bre\&S//; 
                   4641:                 }
1.567     raeburn  4642:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4643:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4644:             }
                   4645:             if ($tdomain ne '') {
                   4646:                 if (defined($dompriv)) {
                   4647:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4648:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4649:                 }
                   4650:                 if (($trest ne '') && (defined($coursepriv))) {
                   4651:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4652:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4653:                 }
                   4654:             }
                   4655:         }
                   4656:     }
                   4657: }
                   4658: 
1.678     raeburn  4659: sub group_roleprivs {
                   4660:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4661:     my $access = 1;
                   4662:     my $now = time;
                   4663:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4664:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4665:     if ($access) {
1.811     albertel 4666:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4667:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4668:     }
                   4669: }
1.567     raeburn  4670: 
                   4671: sub standard_roleprivs {
                   4672:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4673:     if (defined($pr{$trole.':s'})) {
                   4674:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4675:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4676:     }
                   4677:     if ($tdomain ne '') {
                   4678:         if (defined($pr{$trole.':d'})) {
                   4679:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4680:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4681:         }
                   4682:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4683:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4684:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4685:         }
                   4686:     }
                   4687: }
                   4688: 
                   4689: sub set_userprivs {
1.1064    raeburn  4690:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4691:     my $author=0;
                   4692:     my $adv=0;
1.678     raeburn  4693:     my %grouproles = ();
                   4694:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4695:         my @groupkeys; 
1.1000    raeburn  4696:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4697:             push(@groupkeys,$role);
                   4698:         }
                   4699:         if (ref($groups_roles) eq 'HASH') {
                   4700:             foreach my $key (keys(%{$groups_roles})) {
                   4701:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4702:                     push(@groupkeys,$key);
                   4703:                 }
                   4704:             }
                   4705:         }
                   4706:         if (@groupkeys > 0) {
                   4707:             foreach my $role (@groupkeys) {
                   4708:                 my ($trole,$area,$sec,$extendedarea);
                   4709:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4710:                     $trole = $1;
                   4711:                     $area = $2;
                   4712:                     $sec = $3;
                   4713:                     $extendedarea = $area.$sec;
                   4714:                     if (exists($$allgroups{$area})) {
                   4715:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4716:                             my $spec = $trole.'.'.$extendedarea;
                   4717:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4718:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4719:                         }
1.678     raeburn  4720:                     }
                   4721:                 }
                   4722:             }
                   4723:         }
                   4724:     }
1.800     albertel 4725:     foreach my $group (keys(%grouproles)) {
                   4726:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4727:     }
1.800     albertel 4728:     foreach my $role (keys(%{$allroles})) {
                   4729:         my %thesepriv;
1.941     raeburn  4730:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4731:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4732:             if ($item ne '') {
                   4733:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4734:                 if ($restrictions eq '') {
                   4735:                     $thesepriv{$privilege}='F';
                   4736:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4737:                     $thesepriv{$privilege}.=$restrictions;
                   4738:                 }
                   4739:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4740:             }
                   4741:         }
                   4742:         my $thesestr='';
1.1104    raeburn  4743:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4744: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4745: 	}
                   4746:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4747:     }
                   4748:     return ($author,$adv);
                   4749: }
                   4750: 
1.994     raeburn  4751: sub role_status {
1.1104    raeburn  4752:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4753:     my @pwhere = ();
                   4754:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4755:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4756:         unless (!defined($$role) || $$role eq '') {
                   4757:             $$where=join('.',@pwhere);
                   4758:             $$trolecode=$$role.'.'.$$where;
                   4759:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4760:             $$tstatus='is';
1.1104    raeburn  4761:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4762:                 $$tstatus='future';
1.1034    raeburn  4763:                 if ($$tstart<$now) {
                   4764:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4765:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4766:                             my (%allroles,%allgroups,$group_privs,
                   4767:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4768:                             my %userroles = (
                   4769:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4770:                             );
1.1064    raeburn  4771:                             @rolecodes = ('cm'); 
1.1002    raeburn  4772:                             my $spec=$$role.'.'.$$where;
                   4773:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4774:                             if ($$role =~ /^cr\//) {
                   4775:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4776:                                 push(@rolecodes,'cr');
1.1002    raeburn  4777:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4778:                                 push(@rolecodes,$$role);
1.1002    raeburn  4779:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4780:                                                     $env{'user.name'});
1.1064    raeburn  4781:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4782:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4783:                                 $group_privs = &unescape($group_privs);
                   4784:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4785:                                 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  4786:                                 &get_groups_roles($tdomain,$trest,
                   4787:                                                   \%course_roles,\@rolecodes,
                   4788:                                                   \%groups_roles);
1.1002    raeburn  4789:                             } else {
1.1064    raeburn  4790:                                 push(@rolecodes,$$role);
1.1002    raeburn  4791:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4792:                             }
1.1064    raeburn  4793:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4794:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4795:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4796:                         }
                   4797:                     }
1.1034    raeburn  4798:                     $$tstatus = 'is';
1.1002    raeburn  4799:                 }
1.994     raeburn  4800:             }
                   4801:             if ($$tend) {
1.1104    raeburn  4802:                 if ($$tend<$update) {
1.994     raeburn  4803:                     $$tstatus='expired';
                   4804:                 } elsif ($$tend<$now) {
                   4805:                     $$tstatus='will_not';
                   4806:                 }
                   4807:             }
                   4808:         }
                   4809:     }
                   4810: }
                   4811: 
1.1104    raeburn  4812: sub get_groups_roles {
                   4813:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4814:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4815:                   (ref($rolecodes) eq 'ARRAY') && 
                   4816:                   (ref($groups_roles) eq 'HASH')); 
                   4817:     if (keys(%{$cdom_courseroles}) > 0) {
                   4818:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4819:         if ($cdom ne '' && $cnum ne '') {
                   4820:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4821:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4822:                     my $crsrole = $1;
                   4823:                     my $crssec = $2;
                   4824:                     if ($crsrole =~ /^cr/) {
                   4825:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4826:                             push(@{$rolecodes},'cr');
                   4827:                         }
                   4828:                     } else {
                   4829:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4830:                             push(@{$rolecodes},$crsrole);
                   4831:                         }
                   4832:                     }
                   4833:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4834:                     if ($crssec ne '') {
                   4835:                         $rolekey .= "/$crssec";
                   4836:                     }
                   4837:                     $rolekey .= './';
                   4838:                     $groups_roles->{$rolekey} = $rolecodes;
                   4839:                 }
                   4840:             }
                   4841:         }
                   4842:     }
                   4843:     return;
                   4844: }
                   4845: 
                   4846: sub delete_env_groupprivs {
                   4847:     my ($where,$courseroles,$possroles) = @_;
                   4848:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4849:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4850:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4851:         %{$courseroles->{$udom}} =
                   4852:             &get_my_roles('','','userroles',['active'],
                   4853:                           $possroles,[$udom],1);
                   4854:     }
                   4855:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4856:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4857:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4858:             my $area = '/'.$cdom.'/'.$cnum;
                   4859:             my $privkey = "user.priv.$crsrole.$area";
                   4860:             if ($crssec ne '') {
                   4861:                 $privkey .= '/'.$crssec;
                   4862:             }
                   4863:             $privkey .= ".$area/$group";
                   4864:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4865:         }
                   4866:     }
                   4867:     return;
                   4868: }
                   4869: 
1.994     raeburn  4870: sub check_adhoc_privs {
1.1104    raeburn  4871:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4872:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4873:     if ($env{$cckey}) {
                   4874:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4875:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4876:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4877:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4878:         }
                   4879:     } else {
1.1088    raeburn  4880:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4881:     }
                   4882: }
                   4883: 
                   4884: sub set_adhoc_privileges {
                   4885: # role can be cc or ca
1.1088    raeburn  4886:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4887:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4888:     my $spec = $role.'.'.$area;
                   4889:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4890:                                   $env{'user.name'});
                   4891:     my %ccrole = ();
                   4892:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4893:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4894:     &appenv(\%userroles,[$role,'cm']);
                   4895:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4896:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4897:         &appenv( {'request.role'        => $spec,
                   4898:                   'request.role.domain' => $dcdom,
                   4899:                   'request.course.sec'  => ''
                   4900:                  }
                   4901:                );
                   4902:         my $tadv=0;
                   4903:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4904:         &appenv({'request.role.adv'    => $tadv});
                   4905:     }
1.994     raeburn  4906: }
                   4907: 
1.12      www      4908: # --------------------------------------------------------------- get interface
                   4909: 
                   4910: sub get {
1.131     albertel 4911:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4912:    my $items='';
1.800     albertel 4913:    foreach my $item (@$storearr) {
                   4914:        $items.=&escape($item).'&';
1.191     harris41 4915:    }
1.12      www      4916:    $items=~s/\&$//;
1.620     albertel 4917:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4918:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4919:    my $uhome=&homeserver($uname,$udomain);
                   4920: 
1.133     albertel 4921:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4922:    my @pairs=split(/\&/,$rep);
1.273     albertel 4923:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4924:      return @pairs;
                   4925:    }
1.15      www      4926:    my %returnhash=();
1.42      www      4927:    my $i=0;
1.800     albertel 4928:    foreach my $item (@$storearr) {
                   4929:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4930:       $i++;
1.191     harris41 4931:    }
1.15      www      4932:    return %returnhash;
1.27      www      4933: }
                   4934: 
                   4935: # --------------------------------------------------------------- del interface
                   4936: 
                   4937: sub del {
1.133     albertel 4938:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4939:    my $items='';
1.800     albertel 4940:    foreach my $item (@$storearr) {
                   4941:        $items.=&escape($item).'&';
1.191     harris41 4942:    }
1.984     neumanie 4943: 
1.27      www      4944:    $items=~s/\&$//;
1.620     albertel 4945:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4946:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4947:    my $uhome=&homeserver($uname,$udomain);
                   4948:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4949: }
                   4950: 
                   4951: # -------------------------------------------------------------- dump interface
                   4952: 
                   4953: sub dump {
1.1086    raeburn  4954:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4955:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4956:     if (!$uname) { $uname=$env{'user.name'}; }
                   4957:     my $uhome=&homeserver($uname,$udomain);
                   4958:     if ($regexp) {
                   4959: 	$regexp=&escape($regexp);
                   4960:     } else {
                   4961: 	$regexp='.';
                   4962:     }
1.1086    raeburn  4963:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4964:     my @pairs=split(/\&/,$rep);
                   4965:     my %returnhash=();
1.1098    foxr     4966:     if (!($rep =~ /^error/ )) {
                   4967: 	foreach my $item (@pairs) {
                   4968: 	    my ($key,$value)=split(/=/,$item,2);
                   4969: 	    $key = &unescape($key);
                   4970: 	    next if ($key =~ /^error: 2 /);
                   4971: 	    $returnhash{$key}=&thaw_unescape($value);
                   4972: 	}
1.755     albertel 4973:     }
                   4974:     return %returnhash;
1.407     www      4975: }
                   4976: 
1.1098    foxr     4977: 
1.717     albertel 4978: # --------------------------------------------------------- dumpstore interface
                   4979: 
                   4980: sub dumpstore {
                   4981:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4982:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4983:    if (!$uname) { $uname=$env{'user.name'}; }
                   4984:    my $uhome=&homeserver($uname,$udomain);
                   4985:    if ($regexp) {
                   4986:        $regexp=&escape($regexp);
                   4987:    } else {
                   4988:        $regexp='.';
                   4989:    }
                   4990:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4991:    my @pairs=split(/\&/,$rep);
                   4992:    my %returnhash=();
                   4993:    foreach my $item (@pairs) {
                   4994:        my ($key,$value)=split(/=/,$item,2);
                   4995:        next if ($key =~ /^error: 2 /);
                   4996:        $returnhash{$key}=&thaw_unescape($value);
                   4997:    }
                   4998:    return %returnhash;
1.717     albertel 4999: }
                   5000: 
1.407     www      5001: # -------------------------------------------------------------- keys interface
                   5002: 
                   5003: sub getkeys {
                   5004:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5005:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5006:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5007:    my $uhome=&homeserver($uname,$udomain);
                   5008:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5009:    my @keyarray=();
1.800     albertel 5010:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5011:       next if ($key =~ /^error: 2 /);
1.800     albertel 5012:       push(@keyarray,&unescape($key));
1.407     www      5013:    }
                   5014:    return @keyarray;
1.318     matthew  5015: }
                   5016: 
1.319     matthew  5017: # --------------------------------------------------------------- currentdump
                   5018: sub currentdump {
1.328     matthew  5019:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5020:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5021:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5022:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5023:    my $uhome = &homeserver($sname,$sdom);
                   5024:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5025:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5026:    #
1.318     matthew  5027:    my %returnhash=();
1.319     matthew  5028:    #
                   5029:    if ($rep eq "unknown_cmd") { 
                   5030:        # an old lond will not know currentdump
                   5031:        # Do a dump and make it look like a currentdump
1.822     albertel 5032:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5033:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5034:        my %hash = @tmp;
                   5035:        @tmp=();
1.424     matthew  5036:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5037:    } else {
                   5038:        my @pairs=split(/\&/,$rep);
1.800     albertel 5039:        foreach my $pair (@pairs) {
                   5040:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5041:            my ($symb,$param) = split(/:/,$key);
                   5042:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5043:                                                         &thaw_unescape($value);
1.319     matthew  5044:        }
1.191     harris41 5045:    }
1.12      www      5046:    return %returnhash;
1.424     matthew  5047: }
                   5048: 
                   5049: sub convert_dump_to_currentdump{
                   5050:     my %hash = %{shift()};
                   5051:     my %returnhash;
                   5052:     # Code ripped from lond, essentially.  The only difference
                   5053:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5054:     # we might run in to problems with parameter names =~ /^v\./
                   5055:     while (my ($key,$value) = each(%hash)) {
                   5056:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5057: 	$symb  = &unescape($symb);
                   5058: 	$param = &unescape($param);
1.424     matthew  5059:         next if ($v eq 'version' || $symb eq 'keys');
                   5060:         next if (exists($returnhash{$symb}) &&
                   5061:                  exists($returnhash{$symb}->{$param}) &&
                   5062:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5063:         $returnhash{$symb}->{$param}=$value;
                   5064:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5065:     }
                   5066:     #
                   5067:     # Remove all of the keys in the hashes which keep track of
                   5068:     # the version of the parameter.
                   5069:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5070:         # use a foreach because we are going to delete from the hash.
                   5071:         foreach my $key (keys(%$param_hash)) {
                   5072:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5073:         }
                   5074:     }
                   5075:     return \%returnhash;
1.12      www      5076: }
                   5077: 
1.627     albertel 5078: # ------------------------------------------------------ critical inc interface
                   5079: 
                   5080: sub cinc {
                   5081:     return &inc(@_,'critical');
                   5082: }
                   5083: 
1.449     matthew  5084: # --------------------------------------------------------------- inc interface
                   5085: 
                   5086: sub inc {
1.627     albertel 5087:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5088:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5089:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5090:     my $uhome=&homeserver($uname,$udomain);
                   5091:     my $items='';
                   5092:     if (! ref($store)) {
                   5093:         # got a single value, so use that instead
                   5094:         $items = &escape($store).'=&';
                   5095:     } elsif (ref($store) eq 'SCALAR') {
                   5096:         $items = &escape($$store).'=&';        
                   5097:     } elsif (ref($store) eq 'ARRAY') {
                   5098:         $items = join('=&',map {&escape($_);} @{$store});
                   5099:     } elsif (ref($store) eq 'HASH') {
                   5100:         while (my($key,$value) = each(%{$store})) {
                   5101:             $items.= &escape($key).'='.&escape($value).'&';
                   5102:         }
                   5103:     }
                   5104:     $items=~s/\&$//;
1.627     albertel 5105:     if ($critical) {
                   5106: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5107:     } else {
                   5108: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5109:     }
1.449     matthew  5110: }
                   5111: 
1.12      www      5112: # --------------------------------------------------------------- put interface
                   5113: 
                   5114: sub put {
1.134     albertel 5115:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5117:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5118:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5119:    my $items='';
1.800     albertel 5120:    foreach my $item (keys(%$storehash)) {
                   5121:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5122:    }
1.12      www      5123:    $items=~s/\&$//;
1.134     albertel 5124:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5125: }
                   5126: 
1.631     albertel 5127: # ------------------------------------------------------------ newput interface
                   5128: 
                   5129: sub newput {
                   5130:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5132:    if (!$uname) { $uname=$env{'user.name'}; }
                   5133:    my $uhome=&homeserver($uname,$udomain);
                   5134:    my $items='';
                   5135:    foreach my $key (keys(%$storehash)) {
                   5136:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5137:    }
                   5138:    $items=~s/\&$//;
                   5139:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5140: }
                   5141: 
                   5142: # ---------------------------------------------------------  putstore interface
                   5143: 
1.524     raeburn  5144: sub putstore {
1.715     albertel 5145:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5146:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5147:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5148:    my $uhome=&homeserver($uname,$udomain);
                   5149:    my $items='';
1.715     albertel 5150:    foreach my $key (keys(%$storehash)) {
                   5151:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5152:    }
1.715     albertel 5153:    $items=~s/\&$//;
1.716     albertel 5154:    my $esc_symb=&escape($symb);
                   5155:    my $esc_v=&escape($version);
1.715     albertel 5156:    my $reply =
1.716     albertel 5157:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5158: 	      $uhome);
                   5159:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5160:        # gfall back to way things use to be done
1.715     albertel 5161:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5162: 			    $uname);
1.524     raeburn  5163:    }
1.715     albertel 5164:    return $reply;
                   5165: }
                   5166: 
                   5167: sub old_putstore {
1.716     albertel 5168:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5169:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5170:     if (!$uname) { $uname=$env{'user.name'}; }
                   5171:     my $uhome=&homeserver($uname,$udomain);
                   5172:     my %newstorehash;
1.800     albertel 5173:     foreach my $item (keys(%$storehash)) {
                   5174: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5175: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5176:     }
                   5177:     my $items='';
                   5178:     my %allitems = ();
1.800     albertel 5179:     foreach my $item (keys(%newstorehash)) {
                   5180: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5181: 	    my $key = $1.':keys:'.$2;
                   5182: 	    $allitems{$key} .= $3.':';
                   5183: 	}
1.800     albertel 5184: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5185:     }
1.800     albertel 5186:     foreach my $item (keys(%allitems)) {
                   5187: 	$allitems{$item} =~ s/\:$//;
                   5188: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5189:     }
                   5190:     $items=~s/\&$//;
                   5191:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5192: }
                   5193: 
1.47      www      5194: # ------------------------------------------------------ critical put interface
                   5195: 
                   5196: sub cput {
1.134     albertel 5197:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5198:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5199:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5200:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5201:    my $items='';
1.800     albertel 5202:    foreach my $item (keys(%$storehash)) {
                   5203:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5204:    }
1.47      www      5205:    $items=~s/\&$//;
1.134     albertel 5206:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5207: }
                   5208: 
                   5209: # -------------------------------------------------------------- eget interface
                   5210: 
                   5211: sub eget {
1.133     albertel 5212:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5213:    my $items='';
1.800     albertel 5214:    foreach my $item (@$storearr) {
                   5215:        $items.=&escape($item).'&';
1.191     harris41 5216:    }
1.12      www      5217:    $items=~s/\&$//;
1.620     albertel 5218:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5219:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5220:    my $uhome=&homeserver($uname,$udomain);
                   5221:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5222:    my @pairs=split(/\&/,$rep);
                   5223:    my %returnhash=();
1.42      www      5224:    my $i=0;
1.800     albertel 5225:    foreach my $item (@$storearr) {
                   5226:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5227:       $i++;
1.191     harris41 5228:    }
1.12      www      5229:    return %returnhash;
                   5230: }
                   5231: 
1.667     albertel 5232: # ------------------------------------------------------------ tmpput interface
                   5233: sub tmpput {
1.802     raeburn  5234:     my ($storehash,$server,$context)=@_;
1.667     albertel 5235:     my $items='';
1.800     albertel 5236:     foreach my $item (keys(%$storehash)) {
                   5237: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5238:     }
                   5239:     $items=~s/\&$//;
1.802     raeburn  5240:     if (defined($context)) {
                   5241:         $items .= ':'.&escape($context);
                   5242:     }
1.667     albertel 5243:     return &reply("tmpput:$items",$server);
                   5244: }
                   5245: 
                   5246: # ------------------------------------------------------------ tmpget interface
                   5247: sub tmpget {
1.688     albertel 5248:     my ($token,$server)=@_;
                   5249:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5250:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5251:     my %returnhash;
                   5252:     foreach my $item (split(/\&/,$rep)) {
                   5253: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5254:         next if ($key =~ /^error: 2 /);
1.667     albertel 5255: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5256:     }
                   5257:     return %returnhash;
                   5258: }
                   5259: 
1.1113    raeburn  5260: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5261: sub tmpdel {
                   5262:     my ($token,$server)=@_;
                   5263:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5264:     return &reply("tmpdel:$token",$server);
                   5265: }
                   5266: 
1.765     albertel 5267: # -------------------------------------------------- portfolio access checking
                   5268: 
                   5269: sub portfolio_access {
1.766     albertel 5270:     my ($requrl) = @_;
1.765     albertel 5271:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5272:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5273:     if ($result) {
                   5274:         my %setters;
                   5275:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5276:             my ($startblock,$endblock) =
                   5277:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5278:             if ($startblock && $endblock) {
                   5279:                 return 'B';
                   5280:             }
                   5281:         } else {
                   5282:             my ($startblock,$endblock) =
                   5283:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5284:             if ($startblock && $endblock) {
                   5285:                 return 'B';
                   5286:             }
                   5287:         }
                   5288:     }
1.765     albertel 5289:     if ($result eq 'ok') {
1.766     albertel 5290:        return 'F';
1.765     albertel 5291:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5292:        return 'A';
1.765     albertel 5293:     }
1.766     albertel 5294:     return '';
1.765     albertel 5295: }
                   5296: 
                   5297: sub get_portfolio_access {
1.767     albertel 5298:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5299: 
                   5300:     if (!ref($access_hash)) {
                   5301: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5302: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5303: 						   $file_name);
                   5304: 	$access_hash = $access_controls{$file_name};
                   5305:     }
                   5306: 
1.765     albertel 5307:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5308:     my $now = time;
                   5309:     if (ref($access_hash) eq 'HASH') {
                   5310:         foreach my $key (keys(%{$access_hash})) {
                   5311:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5312:             if ($start > $now) {
                   5313:                 next;
                   5314:             }
                   5315:             if ($end && $end<$now) {
                   5316:                 next;
                   5317:             }
                   5318:             if ($scope eq 'public') {
                   5319:                 $public = $key;
                   5320:                 last;
                   5321:             } elsif ($scope eq 'guest') {
                   5322:                 $guest = $key;
                   5323:             } elsif ($scope eq 'domains') {
                   5324:                 push(@domains,$key);
                   5325:             } elsif ($scope eq 'users') {
                   5326:                 push(@users,$key);
                   5327:             } elsif ($scope eq 'course') {
                   5328:                 push(@courses,$key);
                   5329:             } elsif ($scope eq 'group') {
                   5330:                 push(@groups,$key);
                   5331:             }
                   5332:         }
                   5333:         if ($public) {
                   5334:             return 'ok';
                   5335:         }
                   5336:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5337:             if ($guest) {
                   5338:                 return $guest;
                   5339:             }
                   5340:         } else {
                   5341:             if (@domains > 0) {
                   5342:                 foreach my $domkey (@domains) {
                   5343:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5344:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5345:                             return 'ok';
                   5346:                         }
                   5347:                     }
                   5348:                 }
                   5349:             }
                   5350:             if (@users > 0) {
                   5351:                 foreach my $userkey (@users) {
1.865     raeburn  5352:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5353:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5354:                             if (ref($item) eq 'HASH') {
                   5355:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5356:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5357:                                     return 'ok';
                   5358:                                 }
                   5359:                             }
                   5360:                         }
                   5361:                     } 
1.765     albertel 5362:                 }
                   5363:             }
                   5364:             my %roleshash;
                   5365:             my @courses_and_groups = @courses;
                   5366:             push(@courses_and_groups,@groups); 
                   5367:             if (@courses_and_groups > 0) {
                   5368:                 my (%allgroups,%allroles); 
                   5369:                 my ($start,$end,$role,$sec,$group);
                   5370:                 foreach my $envkey (%env) {
1.1060    raeburn  5371:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5372:                         my $cid = $2.'_'.$3; 
                   5373:                         if ($1 eq 'gr') {
                   5374:                             $group = $4;
                   5375:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5376:                         } else {
                   5377:                             if ($4 eq '') {
                   5378:                                 $sec = 'none';
                   5379:                             } else {
                   5380:                                 $sec = $4;
                   5381:                             }
                   5382:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5383:                         }
1.811     albertel 5384:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5385:                         my $cid = $2.'_'.$3;
                   5386:                         if ($4 eq '') {
                   5387:                             $sec = 'none';
                   5388:                         } else {
                   5389:                             $sec = $4;
                   5390:                         }
                   5391:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5392:                     }
                   5393:                 }
                   5394:                 if (keys(%allroles) == 0) {
                   5395:                     return;
                   5396:                 }
                   5397:                 foreach my $key (@courses_and_groups) {
                   5398:                     my %content = %{$$access_hash{$key}};
                   5399:                     my $cnum = $content{'number'};
                   5400:                     my $cdom = $content{'domain'};
                   5401:                     my $cid = $cdom.'_'.$cnum;
                   5402:                     if (!exists($allroles{$cid})) {
                   5403:                         next;
                   5404:                     }    
                   5405:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5406:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5407:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5408:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5409:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5410:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5411:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5412:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5413:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5414:                                         if (grep/^all$/,@sections) {
                   5415:                                             return 'ok';
                   5416:                                         } else {
                   5417:                                             if (grep/^$sec$/,@sections) {
                   5418:                                                 return 'ok';
                   5419:                                             }
                   5420:                                         }
                   5421:                                     }
                   5422:                                 }
                   5423:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5424:                                     if (grep/^none$/,@groups) {
                   5425:                                         return 'ok';
                   5426:                                     }
                   5427:                                 } else {
                   5428:                                     if (grep/^all$/,@groups) {
                   5429:                                         return 'ok';
                   5430:                                     } 
                   5431:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5432:                                         if (grep/^$group$/,@groups) {
                   5433:                                             return 'ok';
                   5434:                                         }
                   5435:                                     }
                   5436:                                 } 
                   5437:                             }
                   5438:                         }
                   5439:                     }
                   5440:                 }
                   5441:             }
                   5442:             if ($guest) {
                   5443:                 return $guest;
                   5444:             }
                   5445:         }
                   5446:     }
                   5447:     return;
                   5448: }
                   5449: 
                   5450: sub course_group_datechecker {
                   5451:     my ($dates,$now,$status) = @_;
                   5452:     my ($start,$end) = split(/\./,$dates);
                   5453:     if (!$start && !$end) {
                   5454:         return 'ok';
                   5455:     }
                   5456:     if (grep/^active$/,@{$status}) {
                   5457:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5458:             return 'ok';
                   5459:         }
                   5460:     }
                   5461:     if (grep/^previous$/,@{$status}) {
                   5462:         if ($end > $now ) {
                   5463:             return 'ok';
                   5464:         }
                   5465:     }
                   5466:     if (grep/^future$/,@{$status}) {
                   5467:         if ($start > $now) {
                   5468:             return 'ok';
                   5469:         }
                   5470:     }
                   5471:     return; 
                   5472: }
                   5473: 
                   5474: sub parse_portfolio_url {
                   5475:     my ($url) = @_;
                   5476: 
                   5477:     my ($type,$udom,$unum,$group,$file_name);
                   5478:     
1.823     albertel 5479:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5480: 	$type = 1;
                   5481:         $udom = $1;
                   5482:         $unum = $2;
                   5483:         $file_name = $3;
1.823     albertel 5484:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5485: 	$type = 2;
                   5486:         $udom = $1;
                   5487:         $unum = $2;
                   5488:         $group = $3;
                   5489:         $file_name = $3.'/'.$4;
                   5490:     }
                   5491:     if (wantarray) {
                   5492: 	return ($type,$udom,$unum,$file_name,$group);
                   5493:     }
                   5494:     return $type;
                   5495: }
                   5496: 
                   5497: sub is_portfolio_url {
                   5498:     my ($url) = @_;
                   5499:     return scalar(&parse_portfolio_url($url));
                   5500: }
                   5501: 
1.798     raeburn  5502: sub is_portfolio_file {
                   5503:     my ($file) = @_;
1.820     raeburn  5504:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5505:         return 1;
                   5506:     }
                   5507:     return;
                   5508: }
                   5509: 
1.976     raeburn  5510: sub usertools_access {
1.1084    raeburn  5511:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5512:     my ($access,%tools);
                   5513:     if ($context eq '') {
                   5514:         $context = 'tools';
                   5515:     }
                   5516:     if ($context eq 'requestcourses') {
                   5517:         %tools = (
                   5518:                       official   => 1,
                   5519:                       unofficial => 1,
1.1006    raeburn  5520:                       community  => 1,
1.985     raeburn  5521:                  );
                   5522:     } else {
                   5523:         %tools = (
                   5524:                       aboutme   => 1,
                   5525:                       blog      => 1,
                   5526:                       portfolio => 1,
                   5527:                  );
                   5528:     }
1.976     raeburn  5529:     return if (!defined($tools{$tool}));
                   5530: 
                   5531:     if ((!defined($udom)) || (!defined($uname))) {
                   5532:         $udom = $env{'user.domain'};
                   5533:         $uname = $env{'user.name'};
                   5534:     }
                   5535: 
1.978     raeburn  5536:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5537:         if ($action ne 'reload') {
1.985     raeburn  5538:             if ($context eq 'requestcourses') {
                   5539:                 return $env{'environment.canrequest.'.$tool};
                   5540:             } else {
                   5541:                 return $env{'environment.availabletools.'.$tool};
                   5542:             }
                   5543:         }
1.976     raeburn  5544:     }
                   5545: 
                   5546:     my ($toolstatus,$inststatus);
                   5547: 
1.985     raeburn  5548:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5549:          ($action ne 'reload')) {
                   5550:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5551:         $inststatus = $env{'environment.inststatus'};
                   5552:     } else {
1.1084    raeburn  5553:         if (ref($userenvref) eq 'HASH') {
                   5554:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5555:             $inststatus = $userenvref->{'inststatus'};
                   5556:         } else {
                   5557:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5558:             $toolstatus = $userenv{$context.'.'.$tool};
                   5559:             $inststatus = $userenv{'inststatus'};
                   5560:         }
1.976     raeburn  5561:     }
                   5562: 
                   5563:     if ($toolstatus ne '') {
                   5564:         if ($toolstatus) {
                   5565:             $access = 1;
                   5566:         } else {
                   5567:             $access = 0;
                   5568:         }
                   5569:         return $access;
                   5570:     }
                   5571: 
1.1084    raeburn  5572:     my ($is_adv,%domdef);
                   5573:     if (ref($is_advref) eq 'HASH') {
                   5574:         $is_adv = $is_advref->{'is_adv'};
                   5575:     } else {
                   5576:         $is_adv = &is_advanced_user($udom,$uname);
                   5577:     }
                   5578:     if (ref($domdefref) eq 'HASH') {
                   5579:         %domdef = %{$domdefref};
                   5580:     } else {
                   5581:         %domdef = &get_domain_defaults($udom);
                   5582:     }
1.976     raeburn  5583:     if (ref($domdef{$tool}) eq 'HASH') {
                   5584:         if ($is_adv) {
                   5585:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5586:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5587:                     $access = 1;
                   5588:                 } else {
                   5589:                     $access = 0;
                   5590:                 }
                   5591:                 return $access;
                   5592:             }
                   5593:         }
                   5594:         if ($inststatus ne '') {
                   5595:             my ($hasaccess,$hasnoaccess);
                   5596:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5597:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5598:                     if ($domdef{$tool}{$affiliation}) {
                   5599:                         $hasaccess = 1;
                   5600:                     } else {
                   5601:                         $hasnoaccess = 1;
                   5602:                     }
                   5603:                 }
                   5604:             }
                   5605:             if ($hasaccess || $hasnoaccess) {
                   5606:                 if ($hasaccess) {
                   5607:                     $access = 1;
                   5608:                 } elsif ($hasnoaccess) {
                   5609:                     $access = 0; 
                   5610:                 }
                   5611:                 return $access;
                   5612:             }
                   5613:         } else {
                   5614:             if ($domdef{$tool}{'default'} ne '') {
                   5615:                 if ($domdef{$tool}{'default'}) {
                   5616:                     $access = 1;
                   5617:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5618:                     $access = 0;
                   5619:                 }
                   5620:                 return $access;
                   5621:             }
                   5622:         }
                   5623:     } else {
1.985     raeburn  5624:         if ($context eq 'tools') {
                   5625:             $access = 1;
                   5626:         } else {
                   5627:             $access = 0;
                   5628:         }
1.976     raeburn  5629:         return $access;
                   5630:     }
                   5631: }
                   5632: 
1.1050    raeburn  5633: sub is_course_owner {
                   5634:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5635:     if (($udom eq '') || ($uname eq '')) {
                   5636:         $udom = $env{'user.domain'};
                   5637:         $uname = $env{'user.name'};
                   5638:     }
                   5639:     unless (($udom eq '') || ($uname eq '')) {
                   5640:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5641:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5642:                 return 1;
                   5643:             } else {
                   5644:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5645:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5646:                     return 1;
                   5647:                 }
                   5648:             }
                   5649:         }
                   5650:     }
                   5651:     return;
                   5652: }
                   5653: 
1.976     raeburn  5654: sub is_advanced_user {
                   5655:     my ($udom,$uname) = @_;
1.1085    raeburn  5656:     if ($udom ne '' && $uname ne '') {
                   5657:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5658:             if (wantarray) {
                   5659:                 return ($env{'user.adv'},$env{'user.author'});
                   5660:             } else {
                   5661:                 return $env{'user.adv'};
                   5662:             }
1.1085    raeburn  5663:         }
                   5664:     }
1.976     raeburn  5665:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5666:     my %allroles;
1.1128    raeburn  5667:     my ($is_adv,$is_author);
1.976     raeburn  5668:     foreach my $role (keys(%roleshash)) {
                   5669:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5670:         my $area = '/'.$tdomain.'/'.$trest;
                   5671:         if ($sec ne '') {
                   5672:             $area .= '/'.$sec;
                   5673:         }
                   5674:         if (($area ne '') && ($trole ne '')) {
                   5675:             my $spec=$trole.'.'.$area;
                   5676:             if ($trole =~ /^cr\//) {
                   5677:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5678:             } elsif ($trole ne 'gr') {
                   5679:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5680:             }
1.1128    raeburn  5681:             if ($trole eq 'au') {
                   5682:                 $is_author = 1;
                   5683:             }
1.976     raeburn  5684:         }
                   5685:     }
                   5686:     foreach my $role (keys(%allroles)) {
                   5687:         last if ($is_adv);
                   5688:         foreach my $item (split(/:/,$allroles{$role})) {
                   5689:             if ($item ne '') {
                   5690:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5691:                 if ($privilege eq 'adv') {
                   5692:                     $is_adv = 1;
                   5693:                     last;
                   5694:                 }
                   5695:             }
                   5696:         }
                   5697:     }
1.1128    raeburn  5698:     if (wantarray) {
                   5699:         return ($is_adv,$is_author);
                   5700:     }
1.976     raeburn  5701:     return $is_adv;
                   5702: }
1.798     raeburn  5703: 
1.1035    raeburn  5704: sub check_can_request {
1.1036    raeburn  5705:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5706:     my $canreq = 0;
                   5707:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5708:     my @options = ('approval','validate','autolimit');
                   5709:     my $optregex = join('|',@options);
                   5710:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5711:         foreach my $type (@{$types}) {
                   5712:             if (&usertools_access($env{'user.name'},
                   5713:                                   $env{'user.domain'},
                   5714:                                   $type,undef,'requestcourses')) {
                   5715:                 $canreq ++;
1.1036    raeburn  5716:                 if (ref($request_domains) eq 'HASH') {
                   5717:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5718:                 }
1.1035    raeburn  5719:                 if ($dom eq $env{'user.domain'}) {
                   5720:                     $can_request->{$type} = 1;
                   5721:                 }
                   5722:             }
                   5723:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5724:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5725:                 if (@curr > 0) {
1.1036    raeburn  5726:                     foreach my $item (@curr) {
                   5727:                         if (ref($request_domains) eq 'HASH') {
                   5728:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5729:                             if ($otherdom ne '') {
                   5730:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5731:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5732:                                         push(@{$request_domains->{$type}},$otherdom);
                   5733:                                     }
                   5734:                                 } else {
                   5735:                                     push(@{$request_domains->{$type}},$otherdom);
                   5736:                                 }
                   5737:                             }
                   5738:                         }
                   5739:                     }
                   5740:                     unless($dom eq $env{'user.domain'}) {
                   5741:                         $canreq ++;
1.1035    raeburn  5742:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5743:                             $can_request->{$type} = 1;
                   5744:                         }
                   5745:                     }
                   5746:                 }
                   5747:             }
                   5748:         }
                   5749:     }
                   5750:     return $canreq;
                   5751: }
                   5752: 
1.341     www      5753: # ---------------------------------------------- Custom access rule evaluation
                   5754: 
                   5755: sub customaccess {
                   5756:     my ($priv,$uri)=@_;
1.807     albertel 5757:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5758:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5759:     $udom = &LONCAPA::clean_domain($udom);
                   5760:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5761:     my $access=0;
1.800     albertel 5762:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5763: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5764: 	if ($type eq 'user') {
                   5765: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5766: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5767: 		if ($tdom) {
                   5768: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5769: 		}
1.896     albertel 5770: 		if ($tuname) {
                   5771: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5772: 		}
                   5773: 		$access=($effect eq 'allow');
                   5774: 		last;
                   5775: 	    }
                   5776: 	} else {
                   5777: 	    if ($role) {
                   5778: 		if ($role ne $urole) { next; }
                   5779: 	    }
                   5780: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5781: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5782: 		if ($tdom) {
                   5783: 		    if ($tdom ne $udom) { next; }
                   5784: 		}
                   5785: 		if ($tcrs) {
                   5786: 		    if ($tcrs ne $ucrs) { next; }
                   5787: 		}
                   5788: 		if ($tsec) {
                   5789: 		    if ($tsec ne $usec) { next; }
                   5790: 		}
                   5791: 		$access=($effect eq 'allow');
                   5792: 		last;
                   5793: 	    }
                   5794: 	    if ($realm eq '' && $role eq '') {
                   5795: 		$access=($effect eq 'allow');
                   5796: 	    }
1.402     bowersj2 5797: 	}
1.341     www      5798:     }
                   5799:     return $access;
                   5800: }
                   5801: 
1.103     harris41 5802: # ------------------------------------------------- Check for a user privilege
1.12      www      5803: 
                   5804: sub allowed {
1.810     raeburn  5805:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5806:     my $ver_orguri=$uri;
1.439     www      5807:     $uri=&deversion($uri);
1.152     www      5808:     my $orguri=$uri;
1.52      www      5809:     $uri=&declutter($uri);
1.809     raeburn  5810: 
1.810     raeburn  5811:     if ($priv eq 'evb') {
                   5812: # Evade communication block restrictions for specified role in a course
                   5813:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5814:             return $1;
                   5815:         } else {
                   5816:             return;
                   5817:         }
                   5818:     }
                   5819: 
1.620     albertel 5820:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5821: # Free bre access to adm and meta resources
1.775     albertel 5822:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5823: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5824: 	&& ($priv eq 'bre')) {
1.14      www      5825: 	return 'F';
1.159     www      5826:     }
                   5827: 
1.545     banghart 5828: # Free bre access to user's own portfolio contents
1.714     raeburn  5829:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5830:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5831: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5832:         my %setters;
                   5833:         my ($startblock,$endblock) = 
                   5834:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5835:         if ($startblock && $endblock) {
                   5836:             return 'B';
                   5837:         } else {
                   5838:             return 'F';
                   5839:         }
1.545     banghart 5840:     }
                   5841: 
1.762     raeburn  5842: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5843:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5844:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5845:         if (exists($env{'request.course.id'})) {
                   5846:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5847:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5848:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5849:                 my $courseprivid=$env{'request.course.id'};
                   5850:                 $courseprivid=~s/\_/\//;
                   5851:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5852:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5853:                     return $1; 
1.762     raeburn  5854:                 } else {
                   5855:                     if ($env{'request.course.sec'}) {
                   5856:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5857:                     }
                   5858:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5859:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5860:                         return $2;
                   5861:                     }
1.714     raeburn  5862:                 }
                   5863:             }
                   5864:         }
                   5865:     }
                   5866: 
1.159     www      5867: # Free bre to public access
                   5868: 
                   5869:     if ($priv eq 'bre') {
1.238     www      5870:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5871: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5872:            return 'F'; 
                   5873:         }
1.238     www      5874:         if ($copyright eq 'priv') {
                   5875:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5876: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5877: 		return '';
                   5878:             }
                   5879:         }
                   5880:         if ($copyright eq 'domain') {
                   5881:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5882: 	    unless (($env{'user.domain'} eq $1) ||
                   5883:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5884: 		return '';
                   5885:             }
1.262     matthew  5886:         }
1.620     albertel 5887:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5888:             # Library role, so allow browsing of resources in this domain.
                   5889:             return 'F';
1.238     www      5890:         }
1.341     www      5891:         if ($copyright eq 'custom') {
                   5892: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5893:         }
1.14      www      5894:     }
1.264     matthew  5895:     # Domain coordinator is trying to create a course
1.620     albertel 5896:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5897:         # uri is the requested domain in this case.
                   5898:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5899:         # a role of dc for the domain in question.
1.620     albertel 5900:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5901:     }
1.29      www      5902: 
1.52      www      5903:     my $thisallowed='';
                   5904:     my $statecond=0;
                   5905:     my $courseprivid='';
                   5906: 
1.1039    raeburn  5907:     my $ownaccess;
1.1043    raeburn  5908:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5909:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5910:         if ($uri eq '') {
                   5911:             $ownaccess = 1;
                   5912:         } else {
                   5913:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5914:                 my $udom = $env{'user.domain'};
                   5915:                 my $uname = $env{'user.name'};
                   5916:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5917:                     $ownaccess = 1;
1.1040    raeburn  5918:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5919:                     unless ($uri =~ m{\.\./}) {
                   5920:                         $ownaccess = 1;
                   5921:                     }
                   5922:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5923:                     my $now = time;
                   5924:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5925:                         my $adom = $1;
                   5926:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5927:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5928:                                 my ($start,$end) = split('.',$env{$key});
                   5929:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5930:                                     $ownaccess = 1;
                   5931:                                     last;
                   5932:                                 }
                   5933:                             }
                   5934:                         }
                   5935:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5936:                         my $adom = $1;
                   5937:                         my $aname = $2;
1.1042    raeburn  5938:                         foreach my $role ('ca','aa') { 
                   5939:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5940:                                 my ($start,$end) =
                   5941:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5942:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5943:                                     $ownaccess = 1;
                   5944:                                     last;
                   5945:                                 }
1.1039    raeburn  5946:                             }
                   5947:                         }
                   5948:                     }
                   5949:                 }
                   5950:             }
                   5951:         }
                   5952:     }
                   5953: 
1.52      www      5954: # Course
                   5955: 
1.620     albertel 5956:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5957:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5958:             $thisallowed.=$1;
                   5959:         }
1.52      www      5960:     }
1.29      www      5961: 
1.52      www      5962: # Domain
                   5963: 
1.620     albertel 5964:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5965:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5966:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5967:             $thisallowed.=$1;
                   5968:         }
1.12      www      5969:     }
1.52      www      5970: 
1.1141    raeburn  5971: # User who is not author or co-author might still be able to edit
                   5972: # resource of an author in the domain (e.g., if Domain Coordinator).
                   5973:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   5974:         (&allowed('mdc',$env{'request.course.id'}))) {
                   5975:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   5976:             $thisallowed.=$1;
                   5977:         }
                   5978:     }
                   5979: 
1.52      www      5980: # Course: uri itself is a course
1.66      www      5981:     my $courseuri=$uri;
                   5982:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5983:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5984: 
1.620     albertel 5985:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5986:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5987:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5988:             $thisallowed.=$1;
                   5989:         }
1.12      www      5990:     }
1.29      www      5991: 
1.665     albertel 5992: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5993: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5994:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5995: 	$thisallowed='';
1.671     raeburn  5996:         my ($match)=&is_on_map($uri);
                   5997:         if ($match) {
                   5998:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5999:                   =~/\Q$priv\E\&([^\:]*)/) {
                   6000:                 $thisallowed.=$1;
                   6001:             }
                   6002:         } else {
1.705     albertel 6003:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6004:             if ($refuri) {
                   6005:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6006:                     $thisallowed='F';
1.671     raeburn  6007:                 } else {
                   6008:                     $refuri=&declutter($refuri);
                   6009:                     my ($match) = &is_on_map($refuri);
                   6010:                     if ($match) {
                   6011:                         $thisallowed='F';
                   6012:                     }
1.669     raeburn  6013:                 }
1.671     raeburn  6014:             }
                   6015:         }
1.314     www      6016:     }
1.492     albertel 6017: 
1.766     albertel 6018:     if ($priv eq 'bre'
                   6019: 	&& $thisallowed ne 'F' 
                   6020: 	&& $thisallowed ne '2'
                   6021: 	&& &is_portfolio_url($uri)) {
                   6022: 	$thisallowed = &portfolio_access($uri);
                   6023:     }
                   6024:     
1.52      www      6025: # Full access at system, domain or course-wide level? Exit.
1.29      www      6026:     if ($thisallowed=~/F/) {
                   6027: 	return 'F';
                   6028:     }
                   6029: 
1.52      www      6030: # If this is generating or modifying users, exit with special codes
1.29      www      6031: 
1.643     www      6032:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6033: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6034: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6035: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6036: 	    unless ($auname) { return $thisallowed; }
                   6037: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6038: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6039: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6040: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6041: 	}
1.52      www      6042: 	return $thisallowed;
                   6043:     }
                   6044: #
1.103     harris41 6045: # Gathered so far: system, domain and course wide privileges
1.52      www      6046: #
                   6047: # Course: See if uri or referer is an individual resource that is part of 
                   6048: # the course
                   6049: 
1.620     albertel 6050:     if ($env{'request.course.id'}) {
1.232     www      6051: 
1.620     albertel 6052:        $courseprivid=$env{'request.course.id'};
                   6053:        if ($env{'request.course.sec'}) {
                   6054:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6055:        }
                   6056:        $courseprivid=~s/\_/\//;
                   6057:        my $checkreferer=1;
1.232     www      6058:        my ($match,$cond)=&is_on_map($uri);
                   6059:        if ($match) {
                   6060:            $statecond=$cond;
1.620     albertel 6061:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6062:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6063:                $thisallowed.=$1;
                   6064:                $checkreferer=0;
                   6065:            }
1.29      www      6066:        }
1.83      www      6067:        
1.148     www      6068:        if ($checkreferer) {
1.620     albertel 6069: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6070:             unless ($refuri) {
1.800     albertel 6071:                 foreach my $key (keys(%env)) {
                   6072: 		    if ($key=~/^httpref\..*\*/) {
                   6073: 			my $pattern=$key;
1.156     www      6074:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6075:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6076:                         $pattern=~s/\//\\\//g;
1.152     www      6077:                         if ($orguri=~/$pattern/) {
1.800     albertel 6078: 			    $refuri=$env{$key};
1.148     www      6079:                         }
                   6080:                     }
1.191     harris41 6081:                 }
1.148     www      6082:             }
1.232     www      6083: 
1.148     www      6084:          if ($refuri) { 
1.152     www      6085: 	  $refuri=&declutter($refuri);
1.232     www      6086:           my ($match,$cond)=&is_on_map($refuri);
                   6087:             if ($match) {
                   6088:               my $refstatecond=$cond;
1.620     albertel 6089:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6090:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6091:                   $thisallowed.=$1;
1.53      www      6092:                   $uri=$refuri;
                   6093:                   $statecond=$refstatecond;
1.52      www      6094:               }
                   6095:           }
1.148     www      6096:         }
1.29      www      6097:        }
1.52      www      6098:    }
1.29      www      6099: 
1.52      www      6100: #
1.103     harris41 6101: # Gathered now: all privileges that could apply, and condition number
1.52      www      6102: # 
                   6103: #
                   6104: # Full or no access?
                   6105: #
1.29      www      6106: 
1.52      www      6107:     if ($thisallowed=~/F/) {
                   6108: 	return 'F';
                   6109:     }
1.29      www      6110: 
1.52      www      6111:     unless ($thisallowed) {
                   6112:         return '';
                   6113:     }
1.29      www      6114: 
1.52      www      6115: # Restrictions exist, deal with them
                   6116: #
                   6117: #   C:according to course preferences
                   6118: #   R:according to resource settings
                   6119: #   L:unless locked
                   6120: #   X:according to user session state
                   6121: #
                   6122: 
                   6123: # Possibly locked functionality, check all courses
1.54      www      6124: # Locks might take effect only after 10 minutes cache expiration for other
                   6125: # courses, and 2 minutes for current course
1.52      www      6126: 
                   6127:     my $envkey;
                   6128:     if ($thisallowed=~/L/) {
1.1000    raeburn  6129:         foreach $envkey (keys(%env)) {
1.54      www      6130:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6131:                my $courseid=$2;
                   6132:                my $roleid=$1.'.'.$2;
1.92      www      6133:                $courseid=~s/^\///;
1.54      www      6134:                my $expiretime=600;
1.620     albertel 6135:                if ($env{'request.role'} eq $roleid) {
1.54      www      6136: 		  $expiretime=120;
                   6137:                }
                   6138: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6139:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6140:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6141: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6142:                }
1.620     albertel 6143:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6144:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6145: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6146:                        &log($env{'user.domain'},$env{'user.name'},
                   6147:                             $env{'user.home'},
1.57      www      6148:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6149:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6150:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6151: 		       return '';
                   6152:                    }
                   6153:                }
1.620     albertel 6154:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6155:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6156: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6157:                        &log($env{'user.domain'},$env{'user.name'},
                   6158:                             $env{'user.home'},
1.57      www      6159:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6160:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6161:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6162: 		       return '';
                   6163:                    }
                   6164:                }
                   6165: 	   }
1.29      www      6166:        }
1.52      www      6167:     }
                   6168:    
                   6169: #
                   6170: # Rest of the restrictions depend on selected course
                   6171: #
                   6172: 
1.620     albertel 6173:     unless ($env{'request.course.id'}) {
1.766     albertel 6174: 	if ($thisallowed eq 'A') {
                   6175: 	    return 'A';
1.814     raeburn  6176:         } elsif ($thisallowed eq 'B') {
                   6177:             return 'B';
1.766     albertel 6178: 	} else {
                   6179: 	    return '1';
                   6180: 	}
1.52      www      6181:     }
1.29      www      6182: 
1.52      www      6183: #
                   6184: # Now user is definitely in a course
                   6185: #
1.53      www      6186: 
                   6187: 
                   6188: # Course preferences
                   6189: 
                   6190:    if ($thisallowed=~/C/) {
1.620     albertel 6191:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6192:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6193:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6194: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6195: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6196: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6197: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6198: 			$env{'request.course.id'});
                   6199: 	   }
1.237     www      6200:            return '';
                   6201:        }
                   6202: 
1.620     albertel 6203:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6204: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6205: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6206: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6207: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6208: 			$env{'request.course.id'});
                   6209: 	   }
1.54      www      6210:            return '';
                   6211:        }
1.53      www      6212:    }
                   6213: 
                   6214: # Resource preferences
                   6215: 
                   6216:    if ($thisallowed=~/R/) {
1.620     albertel 6217:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6218:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6219: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6220: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6221: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6222: 	   }
                   6223: 	   return '';
1.54      www      6224:        }
1.53      www      6225:    }
1.30      www      6226: 
1.246     www      6227: # Restricted by state or randomout?
1.30      www      6228: 
1.52      www      6229:    if ($thisallowed=~/X/) {
1.620     albertel 6230:       if ($env{'acc.randomout'}) {
1.579     albertel 6231: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6232:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6233:             return ''; 
                   6234:          }
1.247     www      6235:       }
                   6236:       if (&condval($statecond)) {
1.52      www      6237: 	 return '2';
                   6238:       } else {
                   6239:          return '';
                   6240:       }
                   6241:    }
1.30      www      6242: 
1.766     albertel 6243:     if ($thisallowed eq 'A') {
                   6244: 	return 'A';
1.814     raeburn  6245:     } elsif ($thisallowed eq 'B') {
                   6246:         return 'B';
1.766     albertel 6247:     }
1.52      www      6248:    return 'F';
1.232     www      6249: }
1.1133    foxr     6250: #
                   6251: #   Removes the versino from a URI and
                   6252: #   splits it in to its filename and path to the filename.
                   6253: #   Seems like File::Basename could have done this more clearly.
                   6254: #   Parameters:
                   6255: #      $uri   - input URI
                   6256: #   Returns:
                   6257: #     Two element list consisting of 
                   6258: #     $pathname  - the URI up to and excluding the trailing /
                   6259: #     $filename  - The part of the URI following the last /
                   6260: #  NOTE:
                   6261: #    Another realization of this is simply:
                   6262: #    use File::Basename;
                   6263: #    ...
                   6264: #    $uri = shift;
                   6265: #    $filename = basename($uri);
                   6266: #    $path     = dirname($uri);
                   6267: #    return ($filename, $path);
                   6268: #
                   6269: #     The implementation below is probably faster however.
                   6270: #
1.710     albertel 6271: sub split_uri_for_cond {
                   6272:     my $uri=&deversion(&declutter(shift));
                   6273:     my @uriparts=split(/\//,$uri);
                   6274:     my $filename=pop(@uriparts);
                   6275:     my $pathname=join('/',@uriparts);
                   6276:     return ($pathname,$filename);
                   6277: }
1.232     www      6278: # --------------------------------------------------- Is a resource on the map?
                   6279: 
                   6280: sub is_on_map {
1.710     albertel 6281:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6282:     #Trying to find the conditional for the file
1.620     albertel 6283:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6284: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6285:     if ($match) {
1.289     bowersj2 6286: 	return (1,$1);
                   6287:     } else {
1.434     www      6288: 	return (0,0);
1.289     bowersj2 6289:     }
1.12      www      6290: }
                   6291: 
1.427     www      6292: # --------------------------------------------------------- Get symb from alias
                   6293: 
                   6294: sub get_symb_from_alias {
                   6295:     my $symb=shift;
                   6296:     my ($map,$resid,$url)=&decode_symb($symb);
                   6297: # Already is a symb
                   6298:     if ($url) { return $symb; }
                   6299: # Must be an alias
                   6300:     my $aliassymb='';
                   6301:     my %bighash;
1.620     albertel 6302:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6303:                             &GDBM_READER(),0640)) {
                   6304:         my $rid=$bighash{'mapalias_'.$symb};
                   6305: 	if ($rid) {
                   6306: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6307: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6308: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6309: 	}
                   6310:         untie %bighash;
                   6311:     }
                   6312:     return $aliassymb;
                   6313: }
                   6314: 
1.12      www      6315: # ----------------------------------------------------------------- Define Role
                   6316: 
                   6317: sub definerole {
                   6318:   if (allowed('mcr','/')) {
                   6319:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6320:     foreach my $role (split(':',$sysrole)) {
                   6321: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6322:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6323:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6324: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6325:                return "refused:s:$crole&$cqual"; 
                   6326:             }
                   6327:         }
1.191     harris41 6328:     }
1.800     albertel 6329:     foreach my $role (split(':',$domrole)) {
                   6330: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6331:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6332:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6333: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6334:                return "refused:d:$crole&$cqual"; 
                   6335:             }
                   6336:         }
1.191     harris41 6337:     }
1.800     albertel 6338:     foreach my $role (split(':',$courole)) {
                   6339: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6340:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6341:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6342: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6343:                return "refused:c:$crole&$cqual"; 
                   6344:             }
                   6345:         }
1.191     harris41 6346:     }
1.620     albertel 6347:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6348:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6349: 	        "rolesdef_$rolename=".
                   6350:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6351:     return reply($command,$env{'user.home'});
1.12      www      6352:   } else {
                   6353:     return 'refused';
                   6354:   }
1.105     harris41 6355: }
                   6356: 
                   6357: # ---------------- Make a metadata query against the network of library servers
                   6358: 
                   6359: sub metadata_query {
1.244     matthew  6360:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6361:     my %rhash;
1.845     albertel 6362:     my %libserv = &all_library();
1.244     matthew  6363:     my @server_list = (defined($server_array) ? @$server_array
                   6364:                                               : keys(%libserv) );
                   6365:     for my $server (@server_list) {
1.118     harris41 6366: 	unless ($custom or $customshow) {
                   6367: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6368: 	    $rhash{$server}=$reply;
                   6369: 	}
                   6370: 	else {
                   6371: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6372: 			     &escape($custom).':'.&escape($customshow),
                   6373: 			     $server);
                   6374: 	    $rhash{$server}=$reply;
                   6375: 	}
1.112     harris41 6376:     }
1.118     harris41 6377:     return \%rhash;
1.240     www      6378: }
                   6379: 
                   6380: # ----------------------------------------- Send log queries and wait for reply
                   6381: 
                   6382: sub log_query {
                   6383:     my ($uname,$udom,$query,%filters)=@_;
                   6384:     my $uhome=&homeserver($uname,$udom);
                   6385:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6386:     my $uhost=&hostname($uhome);
1.800     albertel 6387:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6388:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6389:                        $uhome);
1.479     albertel 6390:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6391:     return get_query_reply($queryid);
                   6392: }
                   6393: 
1.818     raeburn  6394: # -------------------------- Update MySQL table for portfolio file
                   6395: 
                   6396: sub update_portfolio_table {
1.821     raeburn  6397:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6398:     if ($group ne '') {
                   6399:         $file_name =~s /^\Q$group\E//;
                   6400:     }
1.818     raeburn  6401:     my $homeserver = &homeserver($uname,$udom);
                   6402:     my $queryid=
1.821     raeburn  6403:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6404:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6405:     my $reply = &get_query_reply($queryid);
                   6406:     return $reply;
                   6407: }
                   6408: 
1.899     raeburn  6409: # -------------------------- Update MySQL allusers table
                   6410: 
                   6411: sub update_allusers_table {
                   6412:     my ($uname,$udom,$names) = @_;
                   6413:     my $homeserver = &homeserver($uname,$udom);
                   6414:     my $queryid=
                   6415:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6416:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6417:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6418:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6419:                'generation='.&escape($names->{'generation'}).'%%'.
                   6420:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6421:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6422:     return;
1.899     raeburn  6423: }
                   6424: 
1.508     raeburn  6425: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6426: 
                   6427: sub fetch_enrollment_query {
1.511     raeburn  6428:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6429:     my $homeserver;
1.547     raeburn  6430:     my $maxtries = 1;
1.508     raeburn  6431:     if ($context eq 'automated') {
                   6432:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6433:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6434:     } else {
                   6435:         $homeserver = &homeserver($cnum,$dom);
                   6436:     }
1.838     albertel 6437:     my $host=&hostname($homeserver);
1.506     raeburn  6438:     my $cmd = '';
1.1000    raeburn  6439:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6440:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6441:     }
                   6442:     $cmd =~ s/%%$//;
                   6443:     $cmd = &escape($cmd);
                   6444:     my $query = 'fetchenrollment';
1.620     albertel 6445:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6446:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6447:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6448:         return 'error: '.$queryid;
                   6449:     }
1.506     raeburn  6450:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6451:     my $tries = 1;
                   6452:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6453:         $reply = &get_query_reply($queryid);
                   6454:         $tries ++;
                   6455:     }
1.526     raeburn  6456:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6457:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6458:     } else {
1.901     albertel 6459:         my @responses = split(/:/,$reply);
1.515     raeburn  6460:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6461:             foreach my $line (@responses) {
                   6462:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6463:                 $$replyref{$key} = $value;
                   6464:             }
                   6465:         } else {
1.1117    foxr     6466:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6467:             foreach my $line (@responses) {
                   6468:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6469:                 $$replyref{$key} = $value;
                   6470:                 if ($value > 0) {
1.800     albertel 6471:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6472:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6473:                         my $destname = $pathname.'/'.$filename;
                   6474:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6475:                         if ($xml_classlist =~ /^error/) {
                   6476:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6477:                         } else {
1.506     raeburn  6478:                             if ( open(FILE,">$destname") ) {
                   6479:                                 print FILE &unescape($xml_classlist);
                   6480:                                 close(FILE);
1.526     raeburn  6481:                             } else {
                   6482:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6483:                             }
                   6484:                         }
                   6485:                     }
                   6486:                 }
                   6487:             }
                   6488:         }
                   6489:         return 'ok';
                   6490:     }
                   6491:     return 'error';
                   6492: }
                   6493: 
1.242     www      6494: sub get_query_reply {
                   6495:     my $queryid=shift;
1.1117    foxr     6496:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6497:     my $reply='';
                   6498:     for (1..100) {
                   6499: 	sleep 2;
                   6500:         if (-e $replyfile.'.end') {
1.448     albertel 6501: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6502: 		$reply = join('',<$fh>);
                   6503: 		close($fh);
1.240     www      6504: 	   } else { return 'error: reply_file_error'; }
1.242     www      6505:            return &unescape($reply);
                   6506: 	}
1.240     www      6507:     }
1.242     www      6508:     return 'timeout:'.$queryid;
1.240     www      6509: }
                   6510: 
                   6511: sub courselog_query {
1.241     www      6512: #
                   6513: # possible filters:
                   6514: # url: url or symb
                   6515: # username
                   6516: # domain
                   6517: # action: view, submit, grade
                   6518: # start: timestamp
                   6519: # end: timestamp
                   6520: #
1.240     www      6521:     my (%filters)=@_;
1.620     albertel 6522:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6523:     if ($filters{'url'}) {
                   6524: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6525:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6526:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6527:     }
1.620     albertel 6528:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6530:     return &log_query($cname,$cdom,'courselog',%filters);
                   6531: }
                   6532: 
                   6533: sub userlog_query {
1.858     raeburn  6534: #
                   6535: # possible filters:
                   6536: # action: log check role
                   6537: # start: timestamp
                   6538: # end: timestamp
                   6539: #
1.240     www      6540:     my ($uname,$udom,%filters)=@_;
                   6541:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6542: }
                   6543: 
1.506     raeburn  6544: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6545: 
                   6546: sub auto_run {
1.508     raeburn  6547:     my ($cnum,$cdom) = @_;
1.876     raeburn  6548:     my $response = 0;
                   6549:     my $settings;
                   6550:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6551:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6552:         $settings = $domconfig{'autoenroll'};
                   6553:         if ($settings->{'run'} eq '1') {
                   6554:             $response = 1;
                   6555:         }
                   6556:     } else {
1.934     raeburn  6557:         my $homeserver;
                   6558:         if (&is_course($cdom,$cnum)) {
                   6559:             $homeserver = &homeserver($cnum,$cdom);
                   6560:         } else {
                   6561:             $homeserver = &domain($cdom,'primary');
                   6562:         }
                   6563:         if ($homeserver ne 'no_host') {
                   6564:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6565:         }
1.876     raeburn  6566:     }
1.506     raeburn  6567:     return $response;
                   6568: }
1.776     albertel 6569: 
1.506     raeburn  6570: sub auto_get_sections {
1.508     raeburn  6571:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6572:     my $homeserver;
                   6573:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6574:         $homeserver = &homeserver($cnum,$cdom);
                   6575:     }
                   6576:     if (!defined($homeserver)) { 
                   6577:         if ($cdom =~ /^$match_domain$/) {
                   6578:             $homeserver = &domain($cdom,'primary');
                   6579:         }
                   6580:     }
                   6581:     my @secs;
                   6582:     if (defined($homeserver)) {
                   6583:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6584:         unless ($response eq 'refused') {
                   6585:             @secs = split(/:/,$response);
                   6586:         }
1.506     raeburn  6587:     }
                   6588:     return @secs;
                   6589: }
1.776     albertel 6590: 
1.506     raeburn  6591: sub auto_new_course {
1.1099    raeburn  6592:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6593:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6594:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6595:     return $response;
                   6596: }
1.776     albertel 6597: 
1.506     raeburn  6598: sub auto_validate_courseID {
1.508     raeburn  6599:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6600:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6601:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6602:     return $response;
                   6603: }
1.776     albertel 6604: 
1.1007    raeburn  6605: sub auto_validate_instcode {
1.1020    raeburn  6606:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6607:     my ($homeserver,$response);
                   6608:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6609:         $homeserver = &homeserver($cnum,$cdom);
                   6610:     }
                   6611:     if (!defined($homeserver)) {
                   6612:         if ($cdom =~ /^$match_domain$/) {
                   6613:             $homeserver = &domain($cdom,'primary');
                   6614:         }
                   6615:     }
1.1065    raeburn  6616:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6617:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6618:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6619:     return ($outcome,$description);
1.1007    raeburn  6620: }
                   6621: 
1.506     raeburn  6622: sub auto_create_password {
1.873     raeburn  6623:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6624:     my ($homeserver,$response);
1.506     raeburn  6625:     my $create_passwd = 0;
                   6626:     my $authchk = '';
1.873     raeburn  6627:     if ($udom =~ /^$match_domain$/) {
                   6628:         $homeserver = &domain($udom,'primary');
                   6629:     }
                   6630:     if ($homeserver eq '') {
                   6631:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6632:             $homeserver = &homeserver($cnum,$cdom);
                   6633:         }
                   6634:     }
                   6635:     if ($homeserver eq '') {
                   6636:         $authchk = 'nodomain';
1.506     raeburn  6637:     } else {
1.873     raeburn  6638:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6639:         if ($response eq 'refused') {
                   6640:             $authchk = 'refused';
                   6641:         } else {
1.901     albertel 6642:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6643:         }
1.506     raeburn  6644:     }
                   6645:     return ($authparam,$create_passwd,$authchk);
                   6646: }
                   6647: 
1.706     raeburn  6648: sub auto_photo_permission {
                   6649:     my ($cnum,$cdom,$students) = @_;
                   6650:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6651:     my ($outcome,$perm_reqd,$conditions) = 
                   6652: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6653:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6654: 	return (undef,undef);
                   6655:     }
1.706     raeburn  6656:     return ($outcome,$perm_reqd,$conditions);
                   6657: }
                   6658: 
                   6659: sub auto_checkphotos {
                   6660:     my ($uname,$udom,$pid) = @_;
                   6661:     my $homeserver = &homeserver($uname,$udom);
                   6662:     my ($result,$resulttype);
                   6663:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6664: 				   &escape($uname).':'.&escape($pid),
                   6665: 				   $homeserver));
1.709     albertel 6666:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6667: 	return (undef,undef);
                   6668:     }
1.706     raeburn  6669:     if ($outcome) {
                   6670:         ($result,$resulttype) = split(/:/,$outcome);
                   6671:     } 
                   6672:     return ($result,$resulttype);
                   6673: }
                   6674: 
                   6675: sub auto_photochoice {
                   6676:     my ($cnum,$cdom) = @_;
                   6677:     my $homeserver = &homeserver($cnum,$cdom);
                   6678:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6679: 						       &escape($cdom),
                   6680: 						       $homeserver)));
1.709     albertel 6681:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6682: 	return (undef,undef);
                   6683:     }
1.706     raeburn  6684:     return ($update,$comment);
                   6685: }
                   6686: 
                   6687: sub auto_photoupdate {
                   6688:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6689:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6690:     my $host=&hostname($homeserver);
1.706     raeburn  6691:     my $cmd = '';
                   6692:     my $maxtries = 1;
1.800     albertel 6693:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6694:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6695:     }
                   6696:     $cmd =~ s/%%$//;
                   6697:     $cmd = &escape($cmd);
                   6698:     my $query = 'institutionalphotos';
                   6699:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6700:     unless ($queryid=~/^\Q$host\E\_/) {
                   6701:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6702:         return 'error: '.$queryid;
                   6703:     }
                   6704:     my $reply = &get_query_reply($queryid);
                   6705:     my $tries = 1;
                   6706:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6707:         $reply = &get_query_reply($queryid);
                   6708:         $tries ++;
                   6709:     }
                   6710:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6711:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6712:     } else {
                   6713:         my @responses = split(/:/,$reply);
                   6714:         my $outcome = shift(@responses); 
                   6715:         foreach my $item (@responses) {
                   6716:             my ($key,$value) = split(/=/,$item);
                   6717:             $$photo{$key} = $value;
                   6718:         }
                   6719:         return $outcome;
                   6720:     }
                   6721:     return 'error';
                   6722: }
                   6723: 
1.521     raeburn  6724: sub auto_instcode_format {
1.793     albertel 6725:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6726: 	$cat_order) = @_;
1.521     raeburn  6727:     my $courses = '';
1.772     raeburn  6728:     my @homeservers;
1.521     raeburn  6729:     if ($caller eq 'global') {
1.841     albertel 6730: 	my %servers = &get_servers($codedom,'library');
                   6731: 	foreach my $tryserver (keys(%servers)) {
                   6732: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6733: 		push(@homeservers,$tryserver);
                   6734: 	    }
1.584     raeburn  6735:         }
1.1022    raeburn  6736:     } elsif ($caller eq 'requests') {
                   6737:         if ($codedom =~ /^$match_domain$/) {
                   6738:             my $chome = &domain($codedom,'primary');
                   6739:             unless ($chome eq 'no_host') {
                   6740:                 push(@homeservers,$chome);
                   6741:             }
                   6742:         }
1.521     raeburn  6743:     } else {
1.772     raeburn  6744:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6745:     }
1.793     albertel 6746:     foreach my $code (keys(%{$instcodes})) {
                   6747:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6748:     }
                   6749:     chop($courses);
1.772     raeburn  6750:     my $ok_response = 0;
                   6751:     my $response;
                   6752:     while (@homeservers > 0 && $ok_response == 0) {
                   6753:         my $server = shift(@homeservers); 
                   6754:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6755:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6756:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6757: 		split(/:/,$response);
1.772     raeburn  6758:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6759:             push(@{$codetitles},&str2array($codetitles_str));
                   6760:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6761:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6762:             $ok_response = 1;
                   6763:         }
                   6764:     }
                   6765:     if ($ok_response) {
1.521     raeburn  6766:         return 'ok';
1.772     raeburn  6767:     } else {
                   6768:         return $response;
1.521     raeburn  6769:     }
                   6770: }
                   6771: 
1.792     raeburn  6772: sub auto_instcode_defaults {
                   6773:     my ($domain,$returnhash,$code_order) = @_;
                   6774:     my @homeservers;
1.841     albertel 6775: 
                   6776:     my %servers = &get_servers($domain,'library');
                   6777:     foreach my $tryserver (keys(%servers)) {
                   6778: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6779: 	    push(@homeservers,$tryserver);
                   6780: 	}
1.792     raeburn  6781:     }
1.841     albertel 6782: 
1.792     raeburn  6783:     my $response;
1.841     albertel 6784:     foreach my $server (@homeservers) {
1.792     raeburn  6785:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6786:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6787: 	
                   6788: 	foreach my $pair (split(/\&/,$response)) {
                   6789: 	    my ($name,$value)=split(/\=/,$pair);
                   6790: 	    if ($name eq 'code_order') {
                   6791: 		@{$code_order} = split(/\&/,&unescape($value));
                   6792: 	    } else {
                   6793: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6794: 	    }
                   6795: 	}
                   6796: 	return 'ok';
1.792     raeburn  6797:     }
1.841     albertel 6798: 
                   6799:     return $response;
1.1003    raeburn  6800: }
                   6801: 
                   6802: sub auto_possible_instcodes {
1.1007    raeburn  6803:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6804:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6805:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6806:         return;
                   6807:     }
1.1003    raeburn  6808:     my (@homeservers,$uhome);
                   6809:     if (defined(&domain($domain,'primary'))) {
                   6810:         $uhome=&domain($domain,'primary');
                   6811:         push(@homeservers,&domain($domain,'primary'));
                   6812:     } else {
                   6813:         my %servers = &get_servers($domain,'library');
                   6814:         foreach my $tryserver (keys(%servers)) {
                   6815:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6816:                 push(@homeservers,$tryserver);
                   6817:             }
                   6818:         }
                   6819:     }
                   6820:     my $response;
                   6821:     foreach my $server (@homeservers) {
                   6822:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6823:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6824:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6825:             split(':',$response);
                   6826:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6827:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6828:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6829:             my ($name,$value)=split('=',$item);
                   6830:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6831:         }
                   6832:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6833:             my ($name,$value)=split('=',$item);
                   6834:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6835:         }
                   6836:         return 'ok';
                   6837:     }
                   6838:     return $response;
                   6839: }
1.792     raeburn  6840: 
1.1010    raeburn  6841: sub auto_courserequest_checks {
                   6842:     my ($dom) = @_;
1.1020    raeburn  6843:     my ($homeserver,%validations);
                   6844:     if ($dom =~ /^$match_domain$/) {
                   6845:         $homeserver = &domain($dom,'primary');
                   6846:     }
                   6847:     unless ($homeserver eq 'no_host') {
                   6848:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6849:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6850:             my @items = split(/&/,$response);
                   6851:             foreach my $item (@items) {
                   6852:                 my ($key,$value) = split('=',$item);
                   6853:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6854:             }
                   6855:         }
                   6856:     }
1.1010    raeburn  6857:     return %validations; 
                   6858: }
                   6859: 
1.1020    raeburn  6860: sub auto_courserequest_validation {
                   6861:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6862:     my ($homeserver,$response);
                   6863:     if ($dom =~ /^$match_domain$/) {
                   6864:         $homeserver = &domain($dom,'primary');
                   6865:     }
                   6866:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6867:           
1.1020    raeburn  6868:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6869:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6870:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6871:                                     $homeserver));
                   6872:     }
                   6873:     return $response;
                   6874: }
                   6875: 
1.777     albertel 6876: sub auto_validate_class_sec {
1.918     raeburn  6877:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6878:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6879:     my $ownerlist;
                   6880:     if (ref($owners) eq 'ARRAY') {
                   6881:         $ownerlist = join(',',@{$owners});
                   6882:     } else {
                   6883:         $ownerlist = $owners;
                   6884:     }
1.773     raeburn  6885:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6886:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6887:     return $response;
                   6888: }
                   6889: 
1.679     raeburn  6890: # ------------------------------------------------------- Course Group routines
                   6891: 
                   6892: sub get_coursegroups {
1.809     raeburn  6893:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6894:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6895: }
                   6896: 
1.679     raeburn  6897: sub modify_coursegroup {
                   6898:     my ($cdom,$cnum,$groupsettings) = @_;
                   6899:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6900: }
                   6901: 
1.809     raeburn  6902: sub toggle_coursegroup_status {
                   6903:     my ($cdom,$cnum,$group,$action) = @_;
                   6904:     my ($from_namespace,$to_namespace);
                   6905:     if ($action eq 'delete') {
                   6906:         $from_namespace = 'coursegroups';
                   6907:         $to_namespace = 'deleted_groups';
                   6908:     } else {
                   6909:         $from_namespace = 'deleted_groups';
                   6910:         $to_namespace = 'coursegroups';
                   6911:     }
                   6912:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6913:     if (my $tmp = &error(%curr_group)) {
                   6914:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6915:         return ('read error',$tmp);
                   6916:     } else {
                   6917:         my %savedsettings = %curr_group; 
1.809     raeburn  6918:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6919:         my $deloutcome;
                   6920:         if ($result eq 'ok') {
1.809     raeburn  6921:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6922:         } else {
                   6923:             return ('write error',$result);
                   6924:         }
                   6925:         if ($deloutcome eq 'ok') {
                   6926:             return 'ok';
                   6927:         } else {
                   6928:             return ('delete error',$deloutcome);
                   6929:         }
                   6930:     }
                   6931: }
                   6932: 
1.679     raeburn  6933: sub modify_group_roles {
1.957     raeburn  6934:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6935:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6936:     my $role = 'gr/'.&escape($userprivs);
                   6937:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6938:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6939:     if ($result eq 'ok') {
                   6940:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6941:     }
1.679     raeburn  6942:     return $result;
                   6943: }
                   6944: 
                   6945: sub modify_coursegroup_membership {
                   6946:     my ($cdom,$cnum,$membership) = @_;
                   6947:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6948:     return $result;
                   6949: }
                   6950: 
1.682     raeburn  6951: sub get_active_groups {
                   6952:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6953:     my $now = time;
                   6954:     my %groups = ();
                   6955:     foreach my $key (keys(%env)) {
1.811     albertel 6956:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6957:             my ($start,$end) = split(/\./,$env{$key});
                   6958:             if (($end!=0) && ($end<$now)) { next; }
                   6959:             if (($start!=0) && ($start>$now)) { next; }
                   6960:             if ($1 eq $cdom && $2 eq $cnum) {
                   6961:                 $groups{$3} = $env{$key} ;
                   6962:             }
                   6963:         }
                   6964:     }
                   6965:     return %groups;
                   6966: }
                   6967: 
1.683     raeburn  6968: sub get_group_membership {
                   6969:     my ($cdom,$cnum,$group) = @_;
                   6970:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6971: }
                   6972: 
                   6973: sub get_users_groups {
                   6974:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6975:     my @usersgroups;
1.683     raeburn  6976:     my $cachetime=1800;
                   6977: 
                   6978:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6979:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6980:     if (defined($cached)) {
1.734     albertel 6981:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6982:     } else {  
                   6983:         $grouplist = '';
1.816     raeburn  6984:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6985:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6986:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6987:         my $access_end = $env{'course.'.$courseid.
                   6988:                               '.default_enrollment_end_date'};
                   6989:         my $now = time;
                   6990:         foreach my $key (keys(%roleshash)) {
                   6991:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6992:                 my $group = $1;
                   6993:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6994:                     my $start = $2;
                   6995:                     my $end = $1;
                   6996:                     if ($start == -1) { next; } # deleted from group
                   6997:                     if (($start!=0) && ($start>$now)) { next; }
                   6998:                     if (($end!=0) && ($end<$now)) {
                   6999:                         if ($access_end && $access_end < $now) {
                   7000:                             if ($access_end - $end < 86400) {
                   7001:                                 push(@usersgroups,$group);
1.733     raeburn  7002:                             }
                   7003:                         }
1.817     raeburn  7004:                         next;
1.733     raeburn  7005:                     }
1.817     raeburn  7006:                     push(@usersgroups,$group);
1.683     raeburn  7007:                 }
                   7008:             }
                   7009:         }
1.817     raeburn  7010:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7011:         $grouplist = join(':',@usersgroups);
                   7012:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7013:     }
1.733     raeburn  7014:     return @usersgroups;
1.683     raeburn  7015: }
                   7016: 
                   7017: sub devalidate_getgroups_cache {
                   7018:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7019:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7020: 
1.683     raeburn  7021:     my $hashid="$udom:$uname:$courseid";
                   7022:     &devalidate_cache_new('getgroups',$hashid);
                   7023: }
                   7024: 
1.12      www      7025: # ------------------------------------------------------------------ Plain Text
                   7026: 
                   7027: sub plaintext {
1.988     raeburn  7028:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7029:     if ($short =~ m{^cr/}) {
1.758     albertel 7030: 	return (split('/',$short))[-1];
                   7031:     }
1.742     raeburn  7032:     if (!defined($cid)) {
                   7033:         $cid = $env{'request.course.id'};
                   7034:     }
                   7035:     my %rolenames = (
1.1008    raeburn  7036:                       Course    => 'std',
                   7037:                       Community => 'alt1',
1.742     raeburn  7038:                     );
1.1037    raeburn  7039:     if ($cid ne '') {
                   7040:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7041:             unless ($forcedefault) {
                   7042:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7043:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7044:                 return &Apache::lonlocal::mt($roletext);
                   7045:             }
                   7046:         }
                   7047:     }
                   7048:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7049:         (defined($rolenames{$type})) && 
                   7050:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7051:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7052:     } elsif ($cid ne '') {
                   7053:         my $crstype = $env{'course.'.$cid.'.type'};
                   7054:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7055:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7056:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7057:         }
1.742     raeburn  7058:     }
1.1037    raeburn  7059:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7060: }
                   7061: 
                   7062: # ----------------------------------------------------------------- Assign Role
                   7063: 
                   7064: sub assignrole {
1.957     raeburn  7065:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7066:         $context)=@_;
1.21      www      7067:     my $mrole;
                   7068:     if ($role =~ /^cr\//) {
1.393     www      7069:         my $cwosec=$url;
1.811     albertel 7070:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7071: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7072:            my $refused = 1;
                   7073:            if ($context eq 'requestcourses') {
                   7074:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7075:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7076:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7077:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7078:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7079:                            if ($crsenv{'internal.courseowner'} eq
                   7080:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7081:                                $refused = '';
                   7082:                            }
                   7083:                        }
                   7084:                    }
                   7085:                }
                   7086:            }
                   7087:            if ($refused) {
                   7088:                &logthis('Refused custom assignrole: '.
                   7089:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7090:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7091:                return 'refused';
                   7092:            }
1.104     www      7093:         }
1.21      www      7094:         $mrole='cr';
1.678     raeburn  7095:     } elsif ($role =~ /^gr\//) {
                   7096:         my $cwogrp=$url;
1.811     albertel 7097:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7098:         unless (&allowed('mdg',$cwogrp)) {
                   7099:             &logthis('Refused group assignrole: '.
                   7100:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7101:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7102:             return 'refused';
                   7103:         }
                   7104:         $mrole='gr';
1.21      www      7105:     } else {
1.82      www      7106:         my $cwosec=$url;
1.811     albertel 7107:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7108:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7109:             my $refused;
                   7110:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7111:                 if (!(&allowed('c'.$role,$url))) {
                   7112:                     $refused = 1;
                   7113:                 }
                   7114:             } else {
                   7115:                 $refused = 1;
                   7116:             }
1.947     raeburn  7117:             if ($refused) {
1.1045    raeburn  7118:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7119:                 if (!$selfenroll && $context eq 'course') {
                   7120:                     my %crsenv;
                   7121:                     if ($role eq 'cc' || $role eq 'co') {
                   7122:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7123:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7124:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7125:                                 if ($crsenv{'internal.courseowner'} eq 
                   7126:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7127:                                     $refused = '';
                   7128:                                 }
                   7129:                             }
                   7130:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7131:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7132:                                 if ($crsenv{'internal.courseowner'} eq 
                   7133:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7134:                                     $refused = '';
                   7135:                                 }
                   7136:                             }
                   7137:                         }
                   7138:                     }
                   7139:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7140:                     $refused = '';
1.1017    raeburn  7141:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7142:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7143:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7144:                         my $wrongcc;
                   7145:                         if ($cnum =~ /^$match_community$/) {
                   7146:                             $wrongcc = 1 if ($role eq 'cc');
                   7147:                         } else {
                   7148:                             $wrongcc = 1 if ($role eq 'co');
                   7149:                         }
                   7150:                         unless ($wrongcc) {
                   7151:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7152:                             if ($crsenv{'internal.courseowner'} eq 
                   7153:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7154:                                 $refused = '';
                   7155:                             }
1.1017    raeburn  7156:                         }
                   7157:                     }
                   7158:                 }
                   7159:                 if ($refused) {
1.947     raeburn  7160:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7161:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7162: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7163:                     return 'refused';
                   7164:                 }
1.932     raeburn  7165:             }
1.1131    raeburn  7166:         } elsif ($role eq 'au') {
                   7167:             if ($url ne '/'.$udom.'/') {
                   7168:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7169:                          ' to assign author role for '.$uname.':'.$udom.
                   7170:                          ' in domain: '.$url.' refused (wrong domain).');
                   7171:                 return 'refused';
                   7172:             }
1.104     www      7173:         }
1.21      www      7174:         $mrole=$role;
                   7175:     }
1.620     albertel 7176:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7177:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7178:     if ($end) { $command.='_'.$end; }
1.21      www      7179:     if ($start) {
                   7180: 	if ($end) { 
1.81      www      7181:            $command.='_'.$start; 
1.21      www      7182:         } else {
1.81      www      7183:            $command.='_0_'.$start;
1.21      www      7184:         }
                   7185:     }
1.739     raeburn  7186:     my $origstart = $start;
                   7187:     my $origend = $end;
1.957     raeburn  7188:     my $delflag;
1.357     www      7189: # actually delete
                   7190:     if ($deleteflag) {
1.373     www      7191: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7192: # modify command to delete the role
1.620     albertel 7193:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7194:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7195: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7196: # set start and finish to negative values for userrolelog
                   7197:            $start=-1;
                   7198:            $end=-1;
1.957     raeburn  7199:            $delflag = 1;
1.357     www      7200:         }
                   7201:     }
                   7202: # send command
1.349     www      7203:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7204: # log new user role if status is ok
1.349     www      7205:     if ($answer eq 'ok') {
1.663     raeburn  7206: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7207: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7208:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7209:         unless ($role =~ /^gr/) {
                   7210:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7211:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7212:         }
1.1053    raeburn  7213:         if ($role eq 'cc') {
                   7214:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7215:         }
1.349     www      7216:     }
                   7217:     return $answer;
1.169     harris41 7218: }
                   7219: 
1.1053    raeburn  7220: sub autoupdate_coowners {
                   7221:     my ($url,$end,$start,$uname,$udom) = @_;
                   7222:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7223:     if (($cdom ne '') && ($cnum ne '')) {
                   7224:         my $now = time;
                   7225:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7226:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7227:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7228:             my $instcode = $coursehash{'internal.coursecode'};
                   7229:             if ($instcode ne '') {
1.1056    raeburn  7230:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7231:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7232:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7233:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7234:                         if ($result eq 'valid') {
                   7235:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7236:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7237:                                     push(@newcoowners,$coowner);
                   7238:                                 }
                   7239:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7240:                                     push(@newcoowners,$uname.':'.$udom);
                   7241:                                 }
                   7242:                                 @newcoowners = sort(@newcoowners);
                   7243:                             } else {
                   7244:                                 push(@newcoowners,$uname.':'.$udom);
                   7245:                             }
                   7246:                         } else {
                   7247:                             if ($coursehash{'internal.co-owners'}) {
                   7248:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7249:                                     unless ($coowner eq $uname.':'.$udom) {
                   7250:                                         push(@newcoowners,$coowner);
                   7251:                                     }
                   7252:                                 }
                   7253:                                 unless (@newcoowners > 0) {
                   7254:                                     $delcoowners = 1;
                   7255:                                     $coowners = '';
                   7256:                                 }
                   7257:                             }
                   7258:                         }
                   7259:                         if (@newcoowners || $delcoowners) {
                   7260:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7261:                                             $delcoowners,@newcoowners);
                   7262:                         }
                   7263:                     }
                   7264:                 }
                   7265:             }
                   7266:         }
                   7267:     }
                   7268: }
                   7269: 
                   7270: sub store_coowners {
                   7271:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7272:     my $cid = $cdom.'_'.$cnum;
                   7273:     my ($coowners,$delresult,$putresult);
                   7274:     if (@newcoowners) {
                   7275:         $coowners = join(',',@newcoowners);
                   7276:         my %coownershash = (
                   7277:                             'internal.co-owners' => $coowners,
                   7278:                            );
                   7279:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7280:         if ($putresult eq 'ok') {
                   7281:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7282:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7283:             }
                   7284:         }
                   7285:     }
                   7286:     if ($delcoowners) {
                   7287:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7288:         if ($delresult eq 'ok') {
                   7289:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7290:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7291:             }
                   7292:         }
                   7293:     }
                   7294:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7295:         my %crsinfo =
                   7296:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7297:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7298:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7299:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7300:         }
                   7301:     }
                   7302: }
                   7303: 
1.169     harris41 7304: # -------------------------------------------------- Modify user authentication
1.197     www      7305: # Overrides without validation
                   7306: 
1.169     harris41 7307: sub modifyuserauth {
                   7308:     my ($udom,$uname,$umode,$upass)=@_;
                   7309:     my $uhome=&homeserver($uname,$udom);
1.197     www      7310:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7311:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7312:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7313:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7314:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7315: 		     &escape($upass),$uhome);
1.620     albertel 7316:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7317:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7318:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7319:     &log($udom,,$uname,$uhome,
1.620     albertel 7320:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7321:                                      $env{'user.name'}.', '.$umode.
1.197     www      7322:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7323:     unless ($reply eq 'ok') {
1.197     www      7324:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7325: 	return 'error: '.$reply;
                   7326:     }   
1.170     harris41 7327:     return 'ok';
1.80      www      7328: }
                   7329: 
1.81      www      7330: # --------------------------------------------------------------- Modify a user
1.80      www      7331: 
1.81      www      7332: sub modifyuser {
1.206     matthew  7333:     my ($udom,    $uname, $uid,
                   7334:         $umode,   $upass, $first,
                   7335:         $middle,  $last,  $gene,
1.1058    raeburn  7336:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7337:     $udom= &LONCAPA::clean_domain($udom);
                   7338:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7339:     my $showcandelete = 'none';
                   7340:     if (ref($candelete) eq 'ARRAY') {
                   7341:         if (@{$candelete} > 0) {
                   7342:             $showcandelete = join(', ',@{$candelete});
                   7343:         }
                   7344:     }
1.81      www      7345:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7346:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7347: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7348:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7349:                                      ' desiredhome not specified'). 
1.620     albertel 7350:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7351:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7352:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7353:     my $newuser;
                   7354:     if ($uhome eq 'no_host') {
                   7355:         $newuser = 1;
                   7356:     }
1.80      www      7357: # ----------------------------------------------------------------- Create User
1.406     albertel 7358:     if (($uhome eq 'no_host') && 
                   7359: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7360:         my $unhome='';
1.844     albertel 7361:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7362:             $unhome = $desiredhome;
1.620     albertel 7363: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7364: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7365:         } else { # load balancing routine for determining $unhome
1.81      www      7366:             my $loadm=10000000;
1.841     albertel 7367: 	    my %servers = &get_servers($udom,'library');
                   7368: 	    foreach my $tryserver (keys(%servers)) {
                   7369: 		my $answer=reply('load',$tryserver);
                   7370: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7371: 		    $loadm=$answer;
                   7372: 		    $unhome=$tryserver;
                   7373: 		}
1.80      www      7374: 	    }
                   7375:         }
                   7376:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7377: 	    return 'error: unable to find a home server for '.$uname.
                   7378:                    ' in domain '.$udom;
1.80      www      7379:         }
                   7380:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7381:                          &escape($upass),$unhome);
                   7382: 	unless ($reply eq 'ok') {
                   7383:             return 'error: '.$reply;
                   7384:         }   
1.230     stredwic 7385:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7386:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7387: 	    return 'error: unable verify users home machine.';
1.80      www      7388:         }
1.209     matthew  7389:     }   # End of creation of new user
1.80      www      7390: # ---------------------------------------------------------------------- Add ID
                   7391:     if ($uid) {
                   7392:        $uid=~tr/A-Z/a-z/;
                   7393:        my %uidhash=&idrget($udom,$uname);
1.196     www      7394:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7395:          && (!$forceid)) {
1.80      www      7396: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7397: 	      return 'error: user id "'.$uid.'" does not match '.
                   7398:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7399:           }
                   7400:        } else {
                   7401: 	  &idput($udom,($uname => $uid));
                   7402:        }
                   7403:     }
                   7404: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7405:     my @tmp=&get('environment',
1.899     raeburn  7406: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7407:                     'permanentemail','inststatus'],
1.134     albertel 7408: 		   $udom,$uname);
1.1075    raeburn  7409:     my (%names,%oldnames);
1.313     matthew  7410:     if ($tmp[0] =~ m/^error:.*/) { 
                   7411:         %names=(); 
                   7412:     } else {
                   7413:         %names = @tmp;
1.1075    raeburn  7414:         %oldnames = %names;
1.313     matthew  7415:     }
1.388     www      7416: #
1.1058    raeburn  7417: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7418: # of users did not contain them), do not overwrite existing values
                   7419: # unless field is in $candelete array ref.  
                   7420: #
                   7421: 
                   7422:     my @fields = ('firstname','middlename','lastname','generation',
                   7423:                   'permanentemail','id');
                   7424:     my %newvalues;
                   7425:     if (ref($candelete) eq 'ARRAY') {
                   7426:         foreach my $field (@fields) {
                   7427:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7428:                 if ($field eq 'firstname') {
                   7429:                     $names{$field} = $first;
                   7430:                 } elsif ($field eq 'middlename') {
                   7431:                     $names{$field} = $middle;
                   7432:                 } elsif ($field eq 'lastname') {
                   7433:                     $names{$field} = $last;
                   7434:                 } elsif ($field eq 'generation') { 
                   7435:                     $names{$field} = $gene;
                   7436:                 } elsif ($field eq 'permanentemail') {
                   7437:                     $names{$field} = $email;
                   7438:                 } elsif ($field eq 'id') {
                   7439:                     $names{$field}  = $uid;
                   7440:                 }
                   7441:             }
                   7442:         }
                   7443:     }
1.388     www      7444:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7445:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7446:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7447:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7448:     if ($email) {
                   7449:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7450:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7451:     }
1.899     raeburn  7452:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7453:     if (defined($inststatus)) {
                   7454:         $names{'inststatus'} = '';
                   7455:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7456:         if (ref($usertypes) eq 'HASH') {
                   7457:             my @okstatuses; 
                   7458:             foreach my $item (split(/:/,$inststatus)) {
                   7459:                 if (defined($usertypes->{$item})) {
                   7460:                     push(@okstatuses,$item);  
                   7461:                 }
                   7462:             }
                   7463:             if (@okstatuses) {
                   7464:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7465:             }
                   7466:         }
                   7467:     }
1.1075    raeburn  7468:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7469:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7470:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7471:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7472:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7473:     } else {
                   7474:         $logmsg .= ' during self creation';
                   7475:     }
1.1075    raeburn  7476:     my $changed;
                   7477:     if ($newuser) {
                   7478:         $changed = 1;
                   7479:     } else {
                   7480:         foreach my $field (@fields) {
                   7481:             if ($names{$field} ne $oldnames{$field}) {
                   7482:                 $changed = 1;
                   7483:                 last;
                   7484:             }
                   7485:         }
                   7486:     }
                   7487:     unless ($changed) {
                   7488:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7489:         &logthis($logmsg);
                   7490:         return 'ok';
                   7491:     }
                   7492:     my $reply = &put('environment', \%names, $udom,$uname);
                   7493:     if ($reply ne 'ok') { 
                   7494:         return 'error: '.$reply;
                   7495:     }
1.1087    raeburn  7496:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7497:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7498:     }
1.1075    raeburn  7499:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7500:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7501:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7502:     &logthis($logmsg);
1.134     albertel 7503:     return 'ok';
1.80      www      7504: }
                   7505: 
1.81      www      7506: # -------------------------------------------------------------- Modify student
1.80      www      7507: 
1.81      www      7508: sub modifystudent {
                   7509:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7510:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7511:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7512:     if (!$cid) {
1.620     albertel 7513: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7514: 	    return 'not_in_class';
                   7515: 	}
1.80      www      7516:     }
                   7517: # --------------------------------------------------------------- Make the user
1.81      www      7518:     my $reply=&modifyuser
1.209     matthew  7519: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7520:          $desiredhome,$email,$inststatus);
1.80      www      7521:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7522:     # This will cause &modify_student_enrollment to get the uid from the
                   7523:     # students environment
                   7524:     $uid = undef if (!$forceid);
1.455     albertel 7525:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7526: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7527:     return $reply;
                   7528: }
                   7529: 
                   7530: sub modify_student_enrollment {
1.957     raeburn  7531:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7532:     my ($cdom,$cnum,$chome);
                   7533:     if (!$cid) {
1.620     albertel 7534: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7535: 	    return 'not_in_class';
                   7536: 	}
1.620     albertel 7537: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7538: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7539:     } else {
                   7540: 	($cdom,$cnum)=split(/_/,$cid);
                   7541:     }
1.620     albertel 7542:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7543:     if (!$chome) {
1.457     raeburn  7544: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7545:     }
1.455     albertel 7546:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7547:     # Make sure the user exists
1.81      www      7548:     my $uhome=&homeserver($uname,$udom);
                   7549:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7550: 	return 'error: no such user';
                   7551:     }
1.297     matthew  7552:     # Get student data if we were not given enough information
                   7553:     if (!defined($first)  || $first  eq '' || 
                   7554:         !defined($last)   || $last   eq '' || 
                   7555:         !defined($uid)    || $uid    eq '' || 
                   7556:         !defined($middle) || $middle eq '' || 
                   7557:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7558:         # They did not supply us with enough data to enroll the student, so
                   7559:         # we need to pick up more information.
1.297     matthew  7560:         my %tmp = &get('environment',
1.294     matthew  7561:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7562:                        ,$udom,$uname);
                   7563: 
1.800     albertel 7564:         #foreach my $key (keys(%tmp)) {
                   7565:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7566:         #}
1.294     matthew  7567:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7568:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7569:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7570:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7571:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7572:     }
1.556     albertel 7573:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7574:     my $user = "$uname:$udom";
                   7575:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7576:     my $reply=cput('classlist',
1.1148    raeburn  7577: 		   {$user => 
1.515     raeburn  7578: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7579: 		   $cdom,$cnum);
1.1148    raeburn  7580:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7581:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7582:     } else { 
1.81      www      7583: 	return 'error: '.$reply;
                   7584:     }
1.297     matthew  7585:     # Add student role to user
1.83      www      7586:     my $uurl='/'.$cid;
1.81      www      7587:     $uurl=~s/\_/\//g;
                   7588:     if ($usec) {
                   7589: 	$uurl.='/'.$usec;
                   7590:     }
1.1148    raeburn  7591:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7592:                              $selfenroll,$context);
                   7593:     if ($result ne 'ok') {
                   7594:         if ($old_entry{$user} ne '') {
                   7595:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7596:         } else {
                   7597:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7598:         }
                   7599:     }
                   7600:     return $result; 
1.21      www      7601: }
                   7602: 
1.556     albertel 7603: sub format_name {
                   7604:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7605:     my $name;
                   7606:     if ($first ne 'lastname') {
                   7607: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7608:     } else {
                   7609: 	if ($lastname=~/\S/) {
                   7610: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7611: 	    $name=~s/\s+,/,/;
                   7612: 	} else {
                   7613: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7614: 	}
                   7615:     }
                   7616:     $name=~s/^\s+//;
                   7617:     $name=~s/\s+$//;
                   7618:     $name=~s/\s+/ /g;
                   7619:     return $name;
                   7620: }
                   7621: 
1.84      www      7622: # ------------------------------------------------- Write to course preferences
                   7623: 
                   7624: sub writecoursepref {
                   7625:     my ($courseid,%prefs)=@_;
                   7626:     $courseid=~s/^\///;
                   7627:     $courseid=~s/\_/\//g;
                   7628:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7629:     my $chome=homeserver($cnum,$cdomain);
                   7630:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7631: 	return 'error: no such course';
                   7632:     }
                   7633:     my $cstring='';
1.800     albertel 7634:     foreach my $pref (keys(%prefs)) {
                   7635: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7636:     }
1.84      www      7637:     $cstring=~s/\&$//;
                   7638:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7639: }
                   7640: 
                   7641: # ---------------------------------------------------------- Make/modify course
                   7642: 
                   7643: sub createcourse {
1.741     raeburn  7644:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7645:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7646:     $url=&declutter($url);
                   7647:     my $cid='';
1.1028    raeburn  7648:     if ($context eq 'requestcourses') {
                   7649:         my $can_create = 0;
                   7650:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7651:         if ($udom eq $ownerdom) {
                   7652:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7653:                                   $context)) {
                   7654:                 $can_create = 1;
                   7655:             }
                   7656:         } else {
                   7657:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7658:                                            $category);
                   7659:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7660:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7661:                 if (@curr > 0) {
                   7662:                     my @options = qw(approval validate autolimit);
                   7663:                     my $optregex = join('|',@options);
                   7664:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7665:                         $can_create = 1;
                   7666:                     }
                   7667:                 }
                   7668:             }
                   7669:         }
                   7670:         if ($can_create) {
                   7671:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7672:                 unless (&allowed('ccc',$udom)) {
                   7673:                     return 'refused'; 
                   7674:                 }
1.1017    raeburn  7675:             }
                   7676:         } else {
                   7677:             return 'refused';
                   7678:         }
1.1028    raeburn  7679:     } elsif (!&allowed('ccc',$udom)) {
                   7680:         return 'refused';
1.84      www      7681:     }
1.1011    raeburn  7682: # --------------------------------------------------------------- Get Unique ID
                   7683:     my $uname;
                   7684:     if ($cnum =~ /^$match_courseid$/) {
                   7685:         my $chome=&homeserver($cnum,$udom,'true');
                   7686:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7687:             $uname = $cnum;
                   7688:         } else {
1.1038    raeburn  7689:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7690:         }
                   7691:     } else {
1.1038    raeburn  7692:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7693:     }
                   7694:     return $uname if ($uname =~ /^error/);
                   7695: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7696:     if (!defined($course_server)) {
                   7697:         if (defined(&domain($udom,'primary'))) {
                   7698:             $course_server = &domain($udom,'primary');
                   7699:         } else {
                   7700:             $course_server = $env{'user.home'}; 
                   7701:         }
                   7702:     }
                   7703:     my %host_servers =
                   7704:         &Apache::lonnet::get_servers($udom,'library');
                   7705:     unless ($host_servers{$course_server}) {
                   7706:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7707:     }
1.84      www      7708: # ------------------------------------------------------------- Make the course
                   7709:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7710:                       $course_server);
1.84      www      7711:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7712:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7713:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7714: 	return 'error: no such course';
                   7715:     }
1.271     www      7716: # ----------------------------------------------------------------- Course made
1.516     raeburn  7717: # log existence
1.1029    raeburn  7718:     my $now = time;
1.918     raeburn  7719:     my $newcourse = {
                   7720:                     $udom.'_'.$uname => {
1.921     raeburn  7721:                                      description => $description,
                   7722:                                      inst_code   => $inst_code,
                   7723:                                      owner       => $course_owner,
                   7724:                                      type        => $crstype,
1.1029    raeburn  7725:                                      creator     => $env{'user.name'}.':'.
                   7726:                                                     $env{'user.domain'},
                   7727:                                      created     => $now,
                   7728:                                      context     => $context,
1.918     raeburn  7729:                                                 },
                   7730:                     };
1.921     raeburn  7731:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7732: # set toplevel url
1.271     www      7733:     my $topurl=$url;
                   7734:     unless ($nonstandard) {
                   7735: # ------------------------------------------ For standard courses, make top url
                   7736:         my $mapurl=&clutter($url);
1.278     www      7737:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7738:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7739: <map>
                   7740: <resource id="1" type="start"></resource>
                   7741: <resource id="2" src="$mapurl"></resource>
                   7742: <resource id="3" type="finish"></resource>
                   7743: <link index="1" from="1" to="2"></link>
                   7744: <link index="2" from="2" to="3"></link>
                   7745: </map>
                   7746: ENDINITMAP
                   7747:         $topurl=&declutter(
1.638     albertel 7748:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7749:                           );
                   7750:     }
                   7751: # ----------------------------------------------------------- Write preferences
1.84      www      7752:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7753:                      ('description'              => $description,
                   7754:                       'url'                      => $topurl,
                   7755:                       'internal.creator'         => $env{'user.name'}.':'.
                   7756:                                                     $env{'user.domain'},
                   7757:                       'internal.created'         => $now,
                   7758:                       'internal.creationcontext' => $context)
                   7759:                     );
1.84      www      7760:     return '/'.$udom.'/'.$uname;
                   7761: }
                   7762: 
1.1011    raeburn  7763: # ------------------------------------------------------------------- Create ID
                   7764: sub generate_coursenum {
1.1038    raeburn  7765:     my ($udom,$crstype) = @_;
1.1011    raeburn  7766:     my $domdesc = &domain($udom);
                   7767:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7768:     my $first;
                   7769:     if ($crstype eq 'Community') {
                   7770:         $first = '0';
                   7771:     } else {
                   7772:         $first = int(1+rand(9)); 
                   7773:     } 
                   7774:     my $uname=$first.
1.1011    raeburn  7775:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7776:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7777:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7778: # ----------------------------------------------- Make sure that does not exist
                   7779:     my $uhome=&homeserver($uname,$udom,'true');
                   7780:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7781:         if ($crstype eq 'Community') {
                   7782:             $first = '0';
                   7783:         } else {
                   7784:             $first = int(1+rand(9));
                   7785:         }
                   7786:         $uname=$first.
1.1011    raeburn  7787:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7788:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7789:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7790:         $uhome=&homeserver($uname,$udom,'true');
                   7791:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7792:             return 'error: unable to generate unique course-ID';
                   7793:         }
                   7794:     }
                   7795:     return $uname;
                   7796: }
                   7797: 
1.813     albertel 7798: sub is_course {
                   7799:     my ($cdom,$cnum) = @_;
                   7800:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7801: 				undef,'.');
1.813     albertel 7802:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7803:         return 1;
                   7804:     }
                   7805:     return 0;
                   7806: }
                   7807: 
1.1015    raeburn  7808: sub store_userdata {
                   7809:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7810:     my $result;
1.1016    raeburn  7811:     if ($datakey ne '') {
1.1013    raeburn  7812:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7813:             if ($udom eq '' || $uname eq '') {
                   7814:                 $udom = $env{'user.domain'};
                   7815:                 $uname = $env{'user.name'};
                   7816:             }
                   7817:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7818:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7819:                 $result = 'error: no_host';
                   7820:             } else {
                   7821:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7822:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7823: 
                   7824:                 my $namevalue='';
                   7825:                 foreach my $key (keys(%{$storehash})) {
                   7826:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7827:                 }
                   7828:                 $namevalue=~s/\&$//;
1.1105    raeburn  7829:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7830:                                   $namevalue,$uhome);
1.1013    raeburn  7831:             }
                   7832:         } else {
                   7833:             $result = 'error: data to store was not a hash reference'; 
                   7834:         }
                   7835:     } else {
                   7836:         $result= 'error: invalid requestkey'; 
                   7837:     }
                   7838:     return $result;
                   7839: }
                   7840: 
1.21      www      7841: # ---------------------------------------------------------- Assign Custom Role
                   7842: 
                   7843: sub assigncustomrole {
1.957     raeburn  7844:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7845:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7846:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7847: }
                   7848: 
                   7849: # ----------------------------------------------------------------- Revoke Role
                   7850: 
                   7851: sub revokerole {
1.957     raeburn  7852:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7853:     my $now=time;
1.965     raeburn  7854:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7855: }
                   7856: 
                   7857: # ---------------------------------------------------------- Revoke Custom Role
                   7858: 
                   7859: sub revokecustomrole {
1.957     raeburn  7860:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7861:     my $now=time;
1.357     www      7862:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7863:            $deleteflag,$selfenroll,$context);
1.17      www      7864: }
                   7865: 
1.533     banghart 7866: # ------------------------------------------------------------ Disk usage
1.535     albertel 7867: sub diskusage {
1.955     raeburn  7868:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7869:     $directorypath =~ s/\/$//;
                   7870:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7871:                        .&escape($getpropath).':'.&escape($uname).':'
                   7872:                        .&escape($udom),homeserver($uname,$udom));
                   7873:     if ($listing eq 'unknown_cmd') {
                   7874:         if ($getpropath) {
                   7875:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7876:         }
                   7877:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7878:     }
1.514     albertel 7879:     return $listing;
1.512     banghart 7880: }
                   7881: 
1.566     banghart 7882: sub is_locked {
1.1096    raeburn  7883:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7884:     my @check;
                   7885:     my $is_locked;
1.1093    raeburn  7886:     push (@check,$file_name);
1.613     albertel 7887:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7888: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7889:     my ($tmp)=keys(%locked);
                   7890:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7891:     
1.566     banghart 7892:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7893:         $is_locked = 'false';
                   7894:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7895:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7896:                $is_locked = 'true';
1.1096    raeburn  7897:                if (ref($which) eq 'ARRAY') {
                   7898:                    push(@{$which},$entry);
                   7899:                } else {
                   7900:                    last;
                   7901:                }
1.745     raeburn  7902:            }
                   7903:        }
1.566     banghart 7904:     } else {
                   7905:         $is_locked = 'false';
                   7906:     }
1.1093    raeburn  7907:     return $is_locked;
1.566     banghart 7908: }
                   7909: 
1.759     albertel 7910: sub declutter_portfile {
                   7911:     my ($file) = @_;
1.833     albertel 7912:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7913:     return $file;
                   7914: }
                   7915: 
1.559     banghart 7916: # ------------------------------------------------------------- Mark as Read Only
                   7917: 
                   7918: sub mark_as_readonly {
                   7919:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7920:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7921:     my ($tmp)=keys(%current_permissions);
                   7922:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7923:     foreach my $file (@{$files}) {
1.759     albertel 7924: 	$file = &declutter_portfile($file);
1.561     banghart 7925:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7926:     }
1.613     albertel 7927:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7928:     return;
                   7929: }
                   7930: 
1.572     banghart 7931: # ------------------------------------------------------------Save Selected Files
                   7932: 
                   7933: sub save_selected_files {
                   7934:     my ($user, $path, @files) = @_;
                   7935:     my $filename = $user."savedfiles";
1.573     banghart 7936:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7937:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7938:     foreach my $file (@files) {
1.620     albertel 7939:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7940:     }
                   7941:     foreach my $file (@other_files) {
1.574     banghart 7942:         print (OUT $file."\n");
1.572     banghart 7943:     }
1.574     banghart 7944:     close (OUT);
1.572     banghart 7945:     return 'ok';
                   7946: }
                   7947: 
1.574     banghart 7948: sub clear_selected_files {
                   7949:     my ($user) = @_;
                   7950:     my $filename = $user."savedfiles";
1.1117    foxr     7951:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7952:     print (OUT undef);
                   7953:     close (OUT);
                   7954:     return ("ok");    
                   7955: }
                   7956: 
1.572     banghart 7957: sub files_in_path {
                   7958:     my ($user, $path) = @_;
                   7959:     my $filename = $user."savedfiles";
                   7960:     my %return_files;
1.1117    foxr     7961:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7962:     while (my $line_in = <IN>) {
1.574     banghart 7963:         chomp ($line_in);
                   7964:         my @paths_and_file = split (m!/!, $line_in);
                   7965:         my $file_part = pop (@paths_and_file);
                   7966:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7967:         $path_part.='/';
                   7968:         my $path_and_file = $path_part.$file_part;
                   7969:         if ($path_part eq $path) {
                   7970:             $return_files{$file_part}= 'selected';
                   7971:         }
                   7972:     }
1.574     banghart 7973:     close (IN);
                   7974:     return (\%return_files);
1.572     banghart 7975: }
                   7976: 
                   7977: # called in portfolio select mode, to show files selected NOT in current directory
                   7978: sub files_not_in_path {
                   7979:     my ($user, $path) = @_;
                   7980:     my $filename = $user."savedfiles";
                   7981:     my @return_files;
                   7982:     my $path_part;
1.1117    foxr     7983:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7984:     while (my $line = <IN>) {
1.572     banghart 7985:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7986:         my @paths_and_file = split(m|/|, $line);
                   7987:         my $file_part = pop(@paths_and_file);
                   7988:         chomp($file_part);
                   7989:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7990:         $path_part .= '/';
                   7991:         my $path_and_file = $path_part.$file_part;
                   7992:         if ($path_part ne $path) {
1.800     albertel 7993:             push(@return_files, ($path_and_file));
1.572     banghart 7994:         }
                   7995:     }
1.800     albertel 7996:     close(OUT);
1.574     banghart 7997:     return (@return_files);
1.572     banghart 7998: }
                   7999: 
1.745     raeburn  8000: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8001: 
1.745     raeburn  8002: sub get_portfile_permissions {
                   8003:     my ($domain,$user) = @_;
1.613     albertel 8004:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8005:     my ($tmp)=keys(%current_permissions);
                   8006:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8007:     return \%current_permissions;
                   8008: }
                   8009: 
                   8010: #---------------------------------------------Get portfolio file access controls
                   8011: 
1.749     raeburn  8012: sub get_access_controls {
1.745     raeburn  8013:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8014:     my %access;
                   8015:     my $real_file = $file;
                   8016:     $file =~ s/\.meta$//;
1.745     raeburn  8017:     if (defined($file)) {
1.749     raeburn  8018:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8019:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8020:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8021:             }
                   8022:         }
1.745     raeburn  8023:     } else {
1.749     raeburn  8024:         foreach my $key (keys(%{$current_permissions})) {
                   8025:             if ($key =~ /\0accesscontrol$/) {
                   8026:                 if (defined($group)) {
                   8027:                     if ($key !~ m-^\Q$group\E/-) {
                   8028:                         next;
                   8029:                     }
                   8030:                 }
                   8031:                 my ($fullpath) = split(/\0/,$key);
                   8032:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8033:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8034:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8035:                     }
                   8036:                 }
                   8037:             }
                   8038:         }
                   8039:     }
                   8040:     return %access;
                   8041: }
                   8042: 
                   8043: sub modify_access_controls {
                   8044:     my ($file_name,$changes,$domain,$user)=@_;
                   8045:     my ($outcome,$deloutcome);
                   8046:     my %store_permissions;
                   8047:     my %new_values;
                   8048:     my %new_control;
                   8049:     my %translation;
                   8050:     my @deletions = ();
                   8051:     my $now = time;
                   8052:     if (exists($$changes{'activate'})) {
                   8053:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8054:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8055:             my $numnew = scalar(@newitems);
                   8056:             for (my $i=0; $i<$numnew; $i++) {
                   8057:                 my $newkey = $newitems[$i];
                   8058:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8059:                 if ($newkey =~ /^\d+:/) { 
                   8060:                     $newkey =~ s/^(\d+)/$newid/;
                   8061:                     $translation{$1} = $newid;
                   8062:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8063:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8064:                     $translation{$1} = $newid;
                   8065:                 }
1.749     raeburn  8066:                 $new_values{$file_name."\0".$newkey} = 
                   8067:                                           $$changes{'activate'}{$newitems[$i]};
                   8068:                 $new_control{$newkey} = $now;
                   8069:             }
                   8070:         }
                   8071:     }
                   8072:     my %todelete;
                   8073:     my %changed_items;
                   8074:     foreach my $action ('delete','update') {
                   8075:         if (exists($$changes{$action})) {
                   8076:             if (ref($$changes{$action}) eq 'HASH') {
                   8077:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8078:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8079:                     if ($action eq 'delete') { 
                   8080:                         $todelete{$itemnum} = 1;
                   8081:                     } else {
                   8082:                         $changed_items{$itemnum} = $key;
                   8083:                     }
                   8084:                 }
1.745     raeburn  8085:             }
                   8086:         }
1.749     raeburn  8087:     }
                   8088:     # get lock on access controls for file.
                   8089:     my $lockhash = {
                   8090:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8091:                                                        ':'.$env{'user.domain'},
                   8092:                    }; 
                   8093:     my $tries = 0;
                   8094:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8095:    
                   8096:     while (($gotlock ne 'ok') && $tries <3) {
                   8097:         $tries ++;
                   8098:         sleep 1;
                   8099:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8100:     }
                   8101:     if ($gotlock eq 'ok') {
                   8102:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8103:         my ($tmp)=keys(%curr_permissions);
                   8104:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8105:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8106:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8107:             if (ref($curr_controls) eq 'HASH') {
                   8108:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8109:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8110:                     if (defined($todelete{$itemnum})) {
                   8111:                         push(@deletions,$file_name."\0".$control_item);
                   8112:                     } else {
                   8113:                         if (defined($changed_items{$itemnum})) {
                   8114:                             $new_control{$changed_items{$itemnum}} = $now;
                   8115:                             push(@deletions,$file_name."\0".$control_item);
                   8116:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8117:                         } else {
                   8118:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8119:                         }
                   8120:                     }
1.745     raeburn  8121:                 }
                   8122:             }
                   8123:         }
1.970     raeburn  8124:         my ($group);
                   8125:         if (&is_course($domain,$user)) {
                   8126:             ($group,my $file) = split(/\//,$file_name,2);
                   8127:         }
1.749     raeburn  8128:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8129:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8130:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8131:         #  remove lock
                   8132:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8133:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8134:         my $sqlresult =
1.970     raeburn  8135:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8136:                                     $group);
1.749     raeburn  8137:     } else {
                   8138:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8139:     }
1.749     raeburn  8140:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8141: }
                   8142: 
1.827     raeburn  8143: sub make_public_indefinitely {
                   8144:     my ($requrl) = @_;
                   8145:     my $now = time;
                   8146:     my $action = 'activate';
                   8147:     my $aclnum = 0;
                   8148:     if (&is_portfolio_url($requrl)) {
                   8149:         my (undef,$udom,$unum,$file_name,$group) =
                   8150:             &parse_portfolio_url($requrl);
                   8151:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8152:         my %access_controls = &get_access_controls($current_perms,
                   8153:                                                    $group,$file_name);
                   8154:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8155:             my ($num,$scope,$end,$start) = 
                   8156:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8157:             if ($scope eq 'public') {
                   8158:                 if ($start <= $now && $end == 0) {
                   8159:                     $action = 'none';
                   8160:                 } else {
                   8161:                     $action = 'update';
                   8162:                     $aclnum = $num;
                   8163:                 }
                   8164:                 last;
                   8165:             }
                   8166:         }
                   8167:         if ($action eq 'none') {
                   8168:              return 'ok';
                   8169:         } else {
                   8170:             my %changes;
                   8171:             my $newend = 0;
                   8172:             my $newstart = $now;
                   8173:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8174:             $changes{$action}{$newkey} = {
                   8175:                 type => 'public',
                   8176:                 time => {
                   8177:                     start => $newstart,
                   8178:                     end   => $newend,
                   8179:                 },
                   8180:             };
                   8181:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8182:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8183:             return $outcome;
                   8184:         }
                   8185:     } else {
                   8186:         return 'invalid';
                   8187:     }
                   8188: }
                   8189: 
1.745     raeburn  8190: #------------------------------------------------------Get Marked as Read Only
                   8191: 
                   8192: sub get_marked_as_readonly {
                   8193:     my ($domain,$user,$what,$group) = @_;
                   8194:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8195:     my @readonly_files;
1.629     banghart 8196:     my $cmp1=$what;
                   8197:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8198:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8199:         if (defined($group)) {
                   8200:             if ($file_name !~ m-^\Q$group\E/-) {
                   8201:                 next;
                   8202:             }
                   8203:         }
1.561     banghart 8204:         if (ref($value) eq "ARRAY"){
                   8205:             foreach my $stored_what (@{$value}) {
1.629     banghart 8206:                 my $cmp2=$stored_what;
1.759     albertel 8207:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8208:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8209:                 }
1.629     banghart 8210:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8211:                     push(@readonly_files, $file_name);
1.745     raeburn  8212:                     last;
1.563     banghart 8213:                 } elsif (!defined($what)) {
                   8214:                     push(@readonly_files, $file_name);
1.745     raeburn  8215:                     last;
1.561     banghart 8216:                 }
                   8217:             }
1.745     raeburn  8218:         }
1.561     banghart 8219:     }
                   8220:     return @readonly_files;
                   8221: }
1.577     banghart 8222: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8223: 
1.577     banghart 8224: sub get_marked_as_readonly_hash {
1.745     raeburn  8225:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8226:     my %readonly_files;
1.745     raeburn  8227:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8228:         if (defined($group)) {
                   8229:             if ($file_name !~ m-^\Q$group\E/-) {
                   8230:                 next;
                   8231:             }
                   8232:         }
1.577     banghart 8233:         if (ref($value) eq "ARRAY"){
                   8234:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8235:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8236:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8237:                         if ($lock_descriptor eq 'graded') {
                   8238:                             $readonly_files{$file_name} = 'graded';
                   8239:                         } elsif ($lock_descriptor eq 'handback') {
                   8240:                             $readonly_files{$file_name} = 'handback';
                   8241:                         } else {
                   8242:                             if (!exists($readonly_files{$file_name})) {
                   8243:                                 $readonly_files{$file_name} = 'locked';
                   8244:                             }
                   8245:                         }
1.745     raeburn  8246:                     }
1.750     banghart 8247:                 } 
1.577     banghart 8248:             }
                   8249:         } 
                   8250:     }
                   8251:     return %readonly_files;
                   8252: }
1.559     banghart 8253: # ------------------------------------------------------------ Unmark as Read Only
                   8254: 
                   8255: sub unmark_as_readonly {
1.629     banghart 8256:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8257:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8258:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8259:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8260:     my $symb_crs = $what;
                   8261:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8262:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8263:     my ($tmp)=keys(%current_permissions);
                   8264:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8265:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8266:     foreach my $file (@readonly_files) {
1.759     albertel 8267: 	my $clean_file = &declutter_portfile($file);
                   8268: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8269: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8270:         my @new_locks;
                   8271:         my @del_keys;
                   8272:         if (ref($current_locks) eq "ARRAY"){
                   8273:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8274:                 my $compare=$locker;
1.749     raeburn  8275:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8276:                     $compare=join('',@{$locker});
1.746     raeburn  8277:                     if ($compare ne $symb_crs) {
                   8278:                         push(@new_locks, $locker);
                   8279:                     }
1.563     banghart 8280:                 }
                   8281:             }
1.650     albertel 8282:             if (scalar(@new_locks) > 0) {
1.563     banghart 8283:                 $current_permissions{$file} = \@new_locks;
                   8284:             } else {
                   8285:                 push(@del_keys, $file);
1.613     albertel 8286:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8287:                 delete($current_permissions{$file});
1.563     banghart 8288:             }
                   8289:         }
1.561     banghart 8290:     }
1.613     albertel 8291:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8292:     return;
                   8293: }
1.512     banghart 8294: 
1.17      www      8295: # ------------------------------------------------------------ Directory lister
                   8296: 
                   8297: sub dirlist {
1.955     raeburn  8298:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8299:     $uri=~s/^\///;
                   8300:     $uri=~s/\/$//;
1.253     stredwic 8301:     my ($udom, $uname);
1.955     raeburn  8302:     if ($getuserdir) {
1.253     stredwic 8303:         $udom = $userdomain;
                   8304:         $uname = $username;
1.955     raeburn  8305:     } else {
                   8306:         (undef,$udom,$uname)=split(/\//,$uri);
                   8307:         if(defined($userdomain)) {
                   8308:             $udom = $userdomain;
                   8309:         }
                   8310:         if(defined($username)) {
                   8311:             $uname = $username;
                   8312:         }
1.253     stredwic 8313:     }
1.955     raeburn  8314:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8315: 
1.955     raeburn  8316:     $dirRoot = $perlvar{'lonDocRoot'};
                   8317:     if (defined($getpropath)) {
                   8318:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8319:         $dirRoot =~ s/\/$//;
1.955     raeburn  8320:     } elsif (defined($getuserdir)) {
                   8321:         my $subdir=$uname.'__';
                   8322:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8323:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8324:                    ."/$udom/$subdir/$uname";
                   8325:     } elsif (defined($alternateRoot)) {
                   8326:         $dirRoot = $alternateRoot;
1.751     banghart 8327:     }
1.253     stredwic 8328: 
                   8329:     if($udom) {
                   8330:         if($uname) {
1.1135    raeburn  8331:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8332:             if ($uhome eq 'no_host') {
                   8333:                 return ([],'no_host');
                   8334:             }
1.955     raeburn  8335:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8336:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8337:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8338:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8339:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8340:             } else {
                   8341:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8342:             }
1.605     matthew  8343:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8344:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8345:                 @listing_results = split(/:/,$listing);
                   8346:             } else {
                   8347:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8348:             }
1.1135    raeburn  8349:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8350:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8351:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8352:                 return ([],$listing);
                   8353:             } else {
                   8354:                 return (\@listing_results);
1.1135    raeburn  8355:             }
1.955     raeburn  8356:         } elsif(!$alternateRoot) {
1.1136    raeburn  8357:             my (%allusers,%listerror);
1.841     albertel 8358: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8359:  	    foreach my $tryserver (keys(%servers)) {
                   8360:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8361:                                   &escape($udom),$tryserver);
                   8362:                 if ($listing eq 'unknown_cmd') {
                   8363: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8364: 				      $udom, $tryserver);
                   8365:                 } else {
                   8366:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8367:                 }
1.841     albertel 8368: 		if ($listing eq 'unknown_cmd') {
                   8369: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8370: 				      $udom, $tryserver);
                   8371: 		    @listing_results = split(/:/,$listing);
                   8372: 		} else {
                   8373: 		    @listing_results =
                   8374: 			map { &unescape($_); } split(/:/,$listing);
                   8375: 		}
1.1136    raeburn  8376:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8377:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8378:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8379:                     $listerror{$tryserver} = $listing;
                   8380:                 } else {
1.841     albertel 8381: 		    foreach my $line (@listing_results) {
                   8382: 			my ($entry) = split(/&/,$line,2);
                   8383: 			$allusers{$entry} = 1;
                   8384: 		    }
                   8385: 		}
1.253     stredwic 8386:             }
1.1136    raeburn  8387:             my @alluserslist=();
1.800     albertel 8388:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8389:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8390:             }
1.1136    raeburn  8391:             return (\@alluserslist);
1.253     stredwic 8392:         } else {
1.1136    raeburn  8393:             return ([],'missing username');
1.253     stredwic 8394:         }
1.955     raeburn  8395:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8396:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8397:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8398:         return (\@all_domains);
1.955     raeburn  8399:     } else {
1.1136    raeburn  8400:         return ([],'missing domain');
1.275     stredwic 8401:     }
                   8402: }
                   8403: 
                   8404: # --------------------------------------------- GetFileTimestamp
                   8405: # This function utilizes dirlist and returns the date stamp for
                   8406: # when it was last modified.  It will also return an error of -1
                   8407: # if an error occurs
                   8408: 
                   8409: sub GetFileTimestamp {
1.955     raeburn  8410:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8411:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8412:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8413:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8414:                                     undef,$getuserdir);
                   8415:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8416:         return -1;
                   8417:     }
                   8418:     if (ref($fileref) eq 'ARRAY') {
                   8419:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8420:         # @stats contains first the filename, then the stat output
                   8421:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8422:     } else {
                   8423:         return -1;
1.253     stredwic 8424:     }
1.26      www      8425: }
                   8426: 
1.712     albertel 8427: sub stat_file {
                   8428:     my ($uri) = @_;
1.787     albertel 8429:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8430: 
1.955     raeburn  8431:     my ($udom,$uname,$file);
1.712     albertel 8432:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8433: 	($udom,$uname,$file) =
1.811     albertel 8434: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8435: 	$file = 'userfiles/'.$file;
                   8436:     }
                   8437:     if ($uri =~ m-^/res/-) {
                   8438: 	($udom,$uname) = 
1.807     albertel 8439: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8440: 	$file = $uri;
                   8441:     }
                   8442: 
                   8443:     if (!$udom || !$uname || !$file) {
                   8444: 	# unable to handle the uri
                   8445: 	return ();
                   8446:     }
1.956     raeburn  8447:     my $getpropath;
                   8448:     if ($file =~ /^userfiles\//) {
                   8449:         $getpropath = 1;
                   8450:     }
1.1136    raeburn  8451:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8452:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8453:         return ();
                   8454:     } else {
                   8455:         if (ref($listref) eq 'ARRAY') {
                   8456:             my @stats = split('&',$listref->[0]);
                   8457: 	    shift(@stats); #filename is first
                   8458: 	    return @stats;
                   8459:         }
1.712     albertel 8460:     }
                   8461:     return ();
                   8462: }
                   8463: 
1.26      www      8464: # -------------------------------------------------------- Value of a Condition
                   8465: 
1.713     albertel 8466: # gets the value of a specific preevaluated condition
                   8467: #    stored in the string  $env{user.state.<cid>}
                   8468: # or looks up a condition reference in the bighash and if if hasn't
                   8469: # already been evaluated recurses into docondval to get the value of
                   8470: # the condition, then memoizing it to 
                   8471: #   $env{user.state.<cid>.<condition>}
1.40      www      8472: sub directcondval {
                   8473:     my $number=shift;
1.620     albertel 8474:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8475: 	&Apache::lonuserstate::evalstate();
                   8476:     }
1.713     albertel 8477:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8478: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8479:     } elsif ($number =~ /^_/) {
                   8480: 	my $sub_condition;
                   8481: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8482: 		&GDBM_READER(),0640)) {
                   8483: 	    $sub_condition=$bighash{'conditions'.$number};
                   8484: 	    untie(%bighash);
                   8485: 	}
                   8486: 	my $value = &docondval($sub_condition);
1.949     raeburn  8487: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8488: 	return $value;
                   8489:     }
1.620     albertel 8490:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8491:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8492:     } else {
                   8493:        return 2;
                   8494:     }
                   8495: }
                   8496: 
1.713     albertel 8497: # get the collection of conditions for this resource
1.26      www      8498: sub condval {
                   8499:     my $condidx=shift;
1.54      www      8500:     my $allpathcond='';
1.713     albertel 8501:     foreach my $cond (split(/\|/,$condidx)) {
                   8502: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8503: 	    $allpathcond.=
                   8504: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8505: 	}
1.191     harris41 8506:     }
1.54      www      8507:     $allpathcond=~s/\|$//;
1.713     albertel 8508:     return &docondval($allpathcond);
                   8509: }
                   8510: 
                   8511: #evaluates an expression of conditions
                   8512: sub docondval {
                   8513:     my ($allpathcond) = @_;
                   8514:     my $result=0;
                   8515:     if ($env{'request.course.id'}
                   8516: 	&& defined($allpathcond)) {
                   8517: 	my $operand='|';
                   8518: 	my @stack;
                   8519: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8520: 	    if ($chunk eq '(') {
                   8521: 		push @stack,($operand,$result);
                   8522: 	    } elsif ($chunk eq ')') {
                   8523: 		my $before=pop @stack;
                   8524: 		if (pop @stack eq '&') {
                   8525: 		    $result=$result>$before?$before:$result;
                   8526: 		} else {
                   8527: 		    $result=$result>$before?$result:$before;
                   8528: 		}
                   8529: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8530: 		$operand=$chunk;
                   8531: 	    } else {
                   8532: 		my $new=directcondval($chunk);
                   8533: 		if ($operand eq '&') {
                   8534: 		    $result=$result>$new?$new:$result;
                   8535: 		} else {
                   8536: 		    $result=$result>$new?$result:$new;
                   8537: 		}
                   8538: 	    }
                   8539: 	}
1.26      www      8540:     }
                   8541:     return $result;
1.421     albertel 8542: }
                   8543: 
                   8544: # ---------------------------------------------------- Devalidate courseresdata
                   8545: 
                   8546: sub devalidatecourseresdata {
                   8547:     my ($coursenum,$coursedomain)=@_;
                   8548:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8549:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8550: }
                   8551: 
1.763     www      8552: 
1.200     www      8553: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8554: #
                   8555: #  Parameters:
                   8556: #      $coursenum    - Number of the course.
                   8557: #      $coursedomain - Domain at which the course was created.
                   8558: #  Returns:
                   8559: #     A hash of the course parameters along (I think) with timestamps
                   8560: #     and version info.
1.877     foxr     8561: 
1.624     albertel 8562: sub get_courseresdata {
                   8563:     my ($coursenum,$coursedomain)=@_;
1.200     www      8564:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8565:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8566:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8567:     my %dumpreply;
1.417     albertel 8568:     unless (defined($cached)) {
1.624     albertel 8569: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8570: 	$result=\%dumpreply;
1.251     albertel 8571: 	my ($tmp) = keys(%dumpreply);
                   8572: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8573: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8574: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8575: 	    return $tmp;
1.416     albertel 8576: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8577: 	    $result=undef;
1.599     albertel 8578: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8579: 	}
                   8580:     }
1.624     albertel 8581:     return $result;
                   8582: }
                   8583: 
1.633     albertel 8584: sub devalidateuserresdata {
                   8585:     my ($uname,$udom)=@_;
                   8586:     my $hashid="$udom:$uname";
                   8587:     &devalidate_cache_new('userres',$hashid);
                   8588: }
                   8589: 
1.624     albertel 8590: sub get_userresdata {
                   8591:     my ($uname,$udom)=@_;
                   8592:     #most student don\'t have any data set, check if there is some data
                   8593:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8594: 
                   8595:     my $hashid="$udom:$uname";
                   8596:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8597:     if (!defined($cached)) {
                   8598: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8599: 	$result=\%resourcedata;
                   8600: 	&do_cache_new('userres',$hashid,$result,600);
                   8601:     }
                   8602:     my ($tmp)=keys(%$result);
                   8603:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8604: 	return $result;
                   8605:     }
                   8606:     #error 2 occurs when the .db doesn't exist
                   8607:     if ($tmp!~/error: 2 /) {
1.672     albertel 8608: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8609: 		 " Trying to get resource data for ".
                   8610: 		 $uname." at ".$udom.": ".
                   8611: 		 $tmp."</font>");
                   8612:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8613: 	#&EXT_cache_set($udom,$uname);
                   8614: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8615: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8616:     }
                   8617:     return $tmp;
                   8618: }
1.879     foxr     8619: #----------------------------------------------- resdata - return resource data
                   8620: #  Purpose:
                   8621: #    Return resource data for either users or for a course.
                   8622: #  Parameters:
                   8623: #     $name      - Course/user name.
                   8624: #     $domain    - Name of the domain the user/course is registered on.
                   8625: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8626: #     @which     - Array of names of resources desired.
                   8627: #  Returns:
                   8628: #     The value of the first reasource in @which that is found in the
                   8629: #     resource hash.
                   8630: #  Exceptional Conditions:
                   8631: #     If the $type passed in is not valid (not the string 'course' or 
                   8632: #     'user', an undefined  reference is returned.
                   8633: #     If none of the resources are found, an undef is returned
1.624     albertel 8634: sub resdata {
                   8635:     my ($name,$domain,$type,@which)=@_;
                   8636:     my $result;
                   8637:     if ($type eq 'course') {
                   8638: 	$result=&get_courseresdata($name,$domain);
                   8639:     } elsif ($type eq 'user') {
                   8640: 	$result=&get_userresdata($name,$domain);
                   8641:     }
                   8642:     if (!ref($result)) { return $result; }    
1.251     albertel 8643:     foreach my $item (@which) {
1.927     albertel 8644: 	if (defined($result->{$item->[0]})) {
                   8645: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8646: 	}
1.250     albertel 8647:     }
1.291     albertel 8648:     return undef;
1.200     www      8649: }
                   8650: 
1.379     matthew  8651: #
                   8652: # EXT resource caching routines
                   8653: #
                   8654: 
                   8655: sub clear_EXT_cache_status {
1.383     albertel 8656:     &delenv('cache.EXT.');
1.379     matthew  8657: }
                   8658: 
                   8659: sub EXT_cache_status {
                   8660:     my ($target_domain,$target_user) = @_;
1.383     albertel 8661:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8662:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8663:         # We know already the user has no data
                   8664:         return 1;
                   8665:     } else {
                   8666:         return 0;
                   8667:     }
                   8668: }
                   8669: 
                   8670: sub EXT_cache_set {
                   8671:     my ($target_domain,$target_user) = @_;
1.383     albertel 8672:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8673:     #&appenv({$cachename => time});
1.379     matthew  8674: }
                   8675: 
1.28      www      8676: # --------------------------------------------------------- Value of a Variable
1.58      www      8677: sub EXT {
1.715     albertel 8678: 
1.395     albertel 8679:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8680:     unless ($varname) { return ''; }
1.218     albertel 8681:     #get real user name/domain, courseid and symb
                   8682:     my $courseid;
1.359     albertel 8683:     my $publicuser;
1.427     www      8684:     if ($symbparm) {
                   8685: 	$symbparm=&get_symb_from_alias($symbparm);
                   8686:     }
1.218     albertel 8687:     if (!($uname && $udom)) {
1.790     albertel 8688:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8689:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8690:     } else {
1.620     albertel 8691: 	$courseid=$env{'request.course.id'};
1.218     albertel 8692:     }
1.48      www      8693:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8694:     my $rest;
1.320     albertel 8695:     if (defined($therest[0])) {
1.48      www      8696:        $rest=join('.',@therest);
                   8697:     } else {
                   8698:        $rest='';
                   8699:     }
1.320     albertel 8700: 
1.57      www      8701:     my $qualifierrest=$qualifier;
                   8702:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8703:     my $spacequalifierrest=$space;
                   8704:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8705:     if ($realm eq 'user') {
1.48      www      8706: # --------------------------------------------------------------- user.resource
                   8707: 	if ($space eq 'resource') {
1.651     albertel 8708: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8709: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8710: 		 &&
1.744     albertel 8711: 		 ($symbparm eq &symbread()) ) {	
                   8712: 		# if we are in the middle of processing the resource the
                   8713: 		# get the value we are planning on committing
                   8714:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8715:                     return $Apache::lonhomework::results{$qualifierrest};
                   8716:                 } else {
                   8717:                     return $Apache::lonhomework::history{$qualifierrest};
                   8718:                 }
1.335     albertel 8719: 	    } else {
1.359     albertel 8720: 		my %restored;
1.620     albertel 8721: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8722: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8723: 		} else {
                   8724: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8725: 		}
1.335     albertel 8726: 		return $restored{$qualifierrest};
                   8727: 	    }
1.48      www      8728: # ----------------------------------------------------------------- user.access
                   8729:         } elsif ($space eq 'access') {
1.218     albertel 8730: 	    # FIXME - not supporting calls for a specific user
1.48      www      8731:             return &allowed($qualifier,$rest);
                   8732: # ------------------------------------------ user.preferences, user.environment
                   8733:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8734: 	    if (($uname eq $env{'user.name'}) &&
                   8735: 		($udom eq $env{'user.domain'})) {
                   8736: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8737: 	    } else {
1.359     albertel 8738: 		my %returnhash;
                   8739: 		if (!$publicuser) {
                   8740: 		    %returnhash=&userenvironment($udom,$uname,
                   8741: 						 $qualifierrest);
                   8742: 		}
1.218     albertel 8743: 		return $returnhash{$qualifierrest};
                   8744: 	    }
1.48      www      8745: # ----------------------------------------------------------------- user.course
                   8746:         } elsif ($space eq 'course') {
1.218     albertel 8747: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8748:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8749: # ------------------------------------------------------------------- user.role
                   8750:         } elsif ($space eq 'role') {
1.218     albertel 8751: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8752:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8753:             if ($qualifier eq 'value') {
                   8754: 		return $role;
                   8755:             } elsif ($qualifier eq 'extent') {
                   8756:                 return $where;
                   8757:             }
                   8758: # ----------------------------------------------------------------- user.domain
                   8759:         } elsif ($space eq 'domain') {
1.218     albertel 8760:             return $udom;
1.48      www      8761: # ------------------------------------------------------------------- user.name
                   8762:         } elsif ($space eq 'name') {
1.218     albertel 8763:             return $uname;
1.48      www      8764: # ---------------------------------------------------- Any other user namespace
1.29      www      8765:         } else {
1.359     albertel 8766: 	    my %reply;
                   8767: 	    if (!$publicuser) {
                   8768: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8769: 	    }
                   8770: 	    return $reply{$qualifierrest};
1.48      www      8771:         }
1.236     www      8772:     } elsif ($realm eq 'query') {
                   8773: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8774:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8775: 						[$spacequalifierrest]);
1.620     albertel 8776: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8777:    } elsif ($realm eq 'request') {
1.48      www      8778: # ------------------------------------------------------------- request.browser
                   8779:         if ($space eq 'browser') {
1.1145    bisitz   8780:             return $env{'browser.'.$qualifier};
1.57      www      8781: # ------------------------------------------------------------ request.filename
                   8782:         } else {
1.620     albertel 8783:             return $env{'request.'.$spacequalifierrest};
1.29      www      8784:         }
1.28      www      8785:     } elsif ($realm eq 'course') {
1.48      www      8786: # ---------------------------------------------------------- course.description
1.620     albertel 8787:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8788:     } elsif ($realm eq 'resource') {
1.165     www      8789: 
1.620     albertel 8790: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8791: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8792: 	}
1.693     albertel 8793: 
                   8794: 	if ($space eq 'title') {
                   8795: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8796: 	    return &gettitle($symbparm);
                   8797: 	}
                   8798: 	
                   8799: 	if ($space eq 'map') {
                   8800: 	    my ($map) = &decode_symb($symbparm);
                   8801: 	    return &symbread($map);
                   8802: 	}
1.905     albertel 8803: 	if ($space eq 'filename') {
                   8804: 	    if ($symbparm) {
                   8805: 		return &clutter((&decode_symb($symbparm))[2]);
                   8806: 	    }
                   8807: 	    return &hreflocation('',$env{'request.filename'});
                   8808: 	}
1.693     albertel 8809: 
                   8810: 	my ($section, $group, @groups);
1.593     albertel 8811: 	my ($courselevelm,$courselevel);
1.539     albertel 8812: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8813: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8814: 
1.218     albertel 8815: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8816: 
1.60      www      8817: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8818: 	    my $symbp=$symbparm;
1.735     albertel 8819: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8820: 
                   8821: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8822: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8823: 
1.620     albertel 8824: 	    if (($env{'user.name'} eq $uname) &&
                   8825: 		($env{'user.domain'} eq $udom)) {
                   8826: 		$section=$env{'request.course.sec'};
1.733     raeburn  8827:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8828:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8829: 	    } else {
1.539     albertel 8830: 		if (! defined($usection)) {
1.551     albertel 8831: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8832: 		} else {
                   8833: 		    $section = $usection;
                   8834: 		}
1.733     raeburn  8835:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8836: 	    }
                   8837: 
                   8838: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8839: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8840: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8841: 
1.593     albertel 8842: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8843: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8844: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8845: 
1.60      www      8846: # ----------------------------------------------------------- first, check user
1.624     albertel 8847: 
                   8848: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8849: 				       ([$courselevelr,'resource'],
                   8850: 					[$courselevelm,'map'     ],
                   8851: 					[$courselevel, 'course'  ]));
1.931     albertel 8852: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8853: 
1.594     albertel 8854: # ------------------------------------------------ second, check some of course
1.684     raeburn  8855:             my $coursereply;
1.691     raeburn  8856:             if (@groups > 0) {
                   8857:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8858:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8859:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8860:             }
1.96      www      8861: 
1.684     raeburn  8862: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8863: 				  $env{'course.'.$courseid.'.domain'},
                   8864: 				  'course',
                   8865: 				  ([$seclevelr,   'resource'],
                   8866: 				   [$seclevelm,   'map'     ],
                   8867: 				   [$seclevel,    'course'  ],
                   8868: 				   [$courselevelr,'resource']));
                   8869: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8870: 
1.60      www      8871: # ------------------------------------------------------ third, check map parms
1.218     albertel 8872: 	    my %parmhash=();
                   8873: 	    my $thisparm='';
                   8874: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8875: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8876: 		    &GDBM_READER(),0640)) {
1.218     albertel 8877: 		$thisparm=$parmhash{$symbparm};
                   8878: 		untie(%parmhash);
                   8879: 	    }
1.927     albertel 8880: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8881: 	}
1.594     albertel 8882: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8883: 
1.218     albertel 8884: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8885: 	my $filename;
                   8886: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8887: 	if ($symbparm) {
1.409     www      8888: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8889: 	} else {
1.620     albertel 8890: 	    $filename=$env{'request.filename'};
1.282     albertel 8891: 	}
                   8892: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8893: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8894: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8895: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8896: 
1.927     albertel 8897: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8898: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8899: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8900: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8901: 				     $env{'course.'.$courseid.'.domain'},
                   8902: 				     'course',
1.927     albertel 8903: 				     ([$courselevelm,'map'   ],
                   8904: 				      [$courselevel, 'course']));
                   8905: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8906: 	}
1.145     www      8907: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8908: 	unless ($space eq '0') {
1.336     albertel 8909: 	    my @parts=split(/_/,$space);
                   8910: 	    my $id=pop(@parts);
                   8911: 	    my $part=join('_',@parts);
                   8912: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8913: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8914: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8915: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8916: 	}
1.395     albertel 8917: 	if ($recurse) { return undef; }
                   8918: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8919: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8920: # ---------------------------------------------------- Any other user namespace
                   8921:     } elsif ($realm eq 'environment') {
                   8922: # ----------------------------------------------------------------- environment
1.620     albertel 8923: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8924: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8925: 	} else {
1.770     albertel 8926: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8927: 		return '';
                   8928: 	    }
1.219     albertel 8929: 	    my %returnhash=&userenvironment($udom,$uname,
                   8930: 					    $spacequalifierrest);
                   8931: 	    return $returnhash{$spacequalifierrest};
                   8932: 	}
1.28      www      8933:     } elsif ($realm eq 'system') {
1.48      www      8934: # ----------------------------------------------------------------- system.time
                   8935: 	if ($space eq 'time') {
                   8936: 	    return time;
                   8937:         }
1.696     albertel 8938:     } elsif ($realm eq 'server') {
                   8939: # ----------------------------------------------------------------- system.time
                   8940: 	if ($space eq 'name') {
                   8941: 	    return $ENV{'SERVER_NAME'};
                   8942:         }
1.28      www      8943:     }
1.48      www      8944:     return '';
1.61      www      8945: }
                   8946: 
1.927     albertel 8947: sub get_reply {
                   8948:     my ($reply_value) = @_;
1.940     raeburn  8949:     if (ref($reply_value) eq 'ARRAY') {
                   8950:         if (wantarray) {
                   8951: 	    return @$reply_value;
                   8952:         }
                   8953:         return $reply_value->[0];
                   8954:     } else {
                   8955:         return $reply_value;
1.927     albertel 8956:     }
                   8957: }
                   8958: 
1.691     raeburn  8959: sub check_group_parms {
                   8960:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8961:     my @groupitems = ();
                   8962:     my $resultitem;
1.927     albertel 8963:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8964:     foreach my $group (@{$groups}) {
                   8965:         foreach my $level (@levels) {
1.927     albertel 8966:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8967:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8968:         }
                   8969:     }
                   8970:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8971:                             $env{'course.'.$courseid.'.domain'},
                   8972:                                      'course',@groupitems);
                   8973:     return $coursereply;
                   8974: }
                   8975: 
                   8976: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8977:     my ($courseid,@groups) = @_;
                   8978:     @groups = sort(@groups);
1.691     raeburn  8979:     return @groups;
                   8980: }
                   8981: 
1.395     albertel 8982: sub packages_tab_default {
                   8983:     my ($uri,$varname)=@_;
                   8984:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8985: 
                   8986:     my (@extension,@specifics,$do_default);
                   8987:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8988: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8989: 	if ($pack_type eq 'default') {
                   8990: 	    $do_default=1;
                   8991: 	} elsif ($pack_type eq 'extension') {
                   8992: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8993: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8994: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8995: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8996: 	}
                   8997:     }
                   8998:     # first look for a package that matches the requested part id
                   8999:     foreach my $package (@specifics) {
                   9000: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9001: 	next if ($pack_part ne $part);
                   9002: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9003: 	    return $packagetab{"$pack_type&$name&default"};
                   9004: 	}
                   9005:     }
                   9006:     # look for any possible matching non extension_ package
                   9007:     foreach my $package (@specifics) {
                   9008: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9009: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9010: 	    return $packagetab{"$pack_type&$name&default"};
                   9011: 	}
1.585     albertel 9012: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9013: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9014: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9015: 	}
                   9016:     }
1.738     albertel 9017:     # look for any posible extension_ match
                   9018:     foreach my $package (@extension) {
                   9019: 	my ($package,$pack_type)=@{$package};
                   9020: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9021: 	    return $packagetab{"$pack_type&$name&default"};
                   9022: 	}
                   9023: 	if (defined($packagetab{$package."&$name&default"})) {
                   9024: 	    return $packagetab{$package."&$name&default"};
                   9025: 	}
                   9026:     }
                   9027:     # look for a global default setting
                   9028:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9029: 	return $packagetab{"default&$name&default"};
                   9030:     }
1.395     albertel 9031:     return undef;
                   9032: }
                   9033: 
1.334     albertel 9034: sub add_prefix_and_part {
                   9035:     my ($prefix,$part)=@_;
                   9036:     my $keyroot;
                   9037:     if (defined($prefix) && $prefix !~ /^__/) {
                   9038: 	# prefix that has a part already
                   9039: 	$keyroot=$prefix;
                   9040:     } elsif (defined($prefix)) {
                   9041: 	# prefix that is missing a part
                   9042: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9043:     } else {
                   9044: 	# no prefix at all
                   9045: 	if (defined($part)) { $keyroot='_'.$part; }
                   9046:     }
                   9047:     return $keyroot;
                   9048: }
                   9049: 
1.71      www      9050: # ---------------------------------------------------------------- Get metadata
                   9051: 
1.599     albertel 9052: my %metaentry;
1.1070    www      9053: my %importedpartids;
1.71      www      9054: sub metadata {
1.176     www      9055:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9056:     $uri=&declutter($uri);
1.288     albertel 9057:     # if it is a non metadata possible uri return quickly
1.529     albertel 9058:     if (($uri eq '') || 
                   9059: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9060: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9061:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9062: 	return undef;
                   9063:     }
1.1140    www      9064:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9065: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9066: 	return undef;
1.288     albertel 9067:     }
1.73      www      9068:     my $filename=$uri;
                   9069:     $uri=~s/\.meta$//;
1.172     www      9070: #
                   9071: # Is the metadata already cached?
1.177     www      9072: # Look at timestamp of caching
1.172     www      9073: # Everything is cached by the main uri, libraries are never directly cached
                   9074: #
1.428     albertel 9075:     if (!defined($liburi)) {
1.599     albertel 9076: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9077: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9078:     }
                   9079:     {
1.1069    www      9080: # Imported parts would go here
1.1070    www      9081:         my %importedids=();
                   9082:         my @origfileimportpartids=();
1.1069    www      9083:         my $importedparts=0;
1.172     www      9084: #
                   9085: # Is this a recursive call for a library?
                   9086: #
1.599     albertel 9087: #	if (! exists($metacache{$uri})) {
                   9088: #	    $metacache{$uri}={};
                   9089: #	}
1.924     albertel 9090: 	my $cachetime = 60*60;
1.171     www      9091:         if ($liburi) {
                   9092: 	    $liburi=&declutter($liburi);
                   9093:             $filename=$liburi;
1.401     bowersj2 9094:         } else {
1.599     albertel 9095: 	    &devalidate_cache_new('meta',$uri);
                   9096: 	    undef(%metaentry);
1.401     bowersj2 9097: 	}
1.140     www      9098:         my %metathesekeys=();
1.73      www      9099:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9100: 	my $metastring;
1.1140    www      9101: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9102: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9103: 	    $metastring = 
1.929     albertel 9104: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9105: 					  ('grade_target' => 'meta'));
                   9106: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9107: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9108:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9109: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9110: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9111: 	    $metastring=&getfile($file);
1.489     albertel 9112: 	}
1.208     albertel 9113:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9114:         my $token;
1.140     www      9115:         undef %metathesekeys;
1.71      www      9116:         while ($token=$parser->get_token) {
1.339     albertel 9117: 	    if ($token->[0] eq 'S') {
                   9118: 		if (defined($token->[2]->{'package'})) {
1.172     www      9119: #
                   9120: # This is a package - get package info
                   9121: #
1.339     albertel 9122: 		    my $package=$token->[2]->{'package'};
                   9123: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9124: 		    if (defined($token->[2]->{'id'})) { 
                   9125: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9126: 		    }
1.599     albertel 9127: 		    if ($metaentry{':packages'}) {
                   9128: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9129: 		    } else {
1.599     albertel 9130: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9131: 		    }
1.736     albertel 9132: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9133: 			my $part=$keyroot;
                   9134: 			$part=~s/^\_//;
1.736     albertel 9135: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9136: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9137: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9138: 			    # ignore package.tab specified default values
                   9139:                             # here &package_tab_default() will fetch those
                   9140: 			    if ($subp eq 'default') { next; }
1.736     albertel 9141: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9142: 			    my $unikey;
                   9143: 			    if ($pack =~ /_0$/) {
                   9144: 				$unikey='parameter_0_'.$name;
                   9145: 				$part=0;
                   9146: 			    } else {
                   9147: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9148: 			    }
1.339     albertel 9149: 			    if ($subp eq 'display') {
                   9150: 				$value.=' [Part: '.$part.']';
                   9151: 			    }
1.599     albertel 9152: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9153: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9154: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9155: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9156: 			    }
1.599     albertel 9157: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9158: 				$metaentry{':'.$unikey}=
                   9159: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9160: 			    }
1.339     albertel 9161: 			}
                   9162: 		    }
                   9163: 		} else {
1.172     www      9164: #
                   9165: # This is not a package - some other kind of start tag
1.339     albertel 9166: #
                   9167: 		    my $entry=$token->[1];
1.1068    www      9168: 		    my $unikey='';
1.175     www      9169: 
1.339     albertel 9170: 		    if ($entry eq 'import') {
1.175     www      9171: #
                   9172: # Importing a library here
1.339     albertel 9173: #
1.1067    www      9174:                         my $location=$parser->get_text('/import');
                   9175:                         my $dir=$filename;
                   9176:                         $dir=~s|[^/]*$||;
                   9177:                         $location=&filelocation($dir,$location);
1.1069    www      9178:                        
1.1068    www      9179:                         my $importmode=$token->[2]->{'importmode'};
                   9180:                         if ($importmode eq 'problem') {
1.1069    www      9181: # Import as problem/response
1.1068    www      9182:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9183:                         } elsif ($importmode eq 'part') {
                   9184: # Import as part(s)
1.1069    www      9185:                            $importedparts=1;
                   9186: # We need to get the original file and the imported file to get the part order correct
                   9187: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9188: # Load and inspect original file
1.1070    www      9189:                            if ($#origfileimportpartids<0) {
                   9190:                               undef(%importedpartids);
                   9191:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9192:                               my $origfile=&getfile($origfilelocation);
                   9193:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9194:                            }
                   9195: 
1.1069    www      9196: # Load and inspect imported file
                   9197:                            my $impfile=&getfile($location);
                   9198:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9199:                            if ($#impfilepartids>=0) {
                   9200: # This problem had parts
1.1070    www      9201:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9202:                            } else {
                   9203: # Importing by turning a single problem into a problem part
                   9204: # It gets the import-tags ID as part-ID
                   9205:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9206:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9207:                            }
1.1068    www      9208:                         } else {
                   9209: # Normal import
                   9210:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9211:                            if (defined($token->[2]->{'id'})) {
                   9212:                               $unikey.='_'.$token->[2]->{'id'};
                   9213:                            }
1.1067    www      9214:                         }
                   9215: 
1.339     albertel 9216: 			if ($depthcount<20) {
1.736     albertel 9217: 			    my $metadata = 
                   9218: 				&metadata($uri,'keys', $location,$unikey,
                   9219: 					  $depthcount+1);
                   9220: 			    foreach my $meta (split(',',$metadata)) {
                   9221: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9222: 				$metathesekeys{$meta}=1;
1.339     albertel 9223: 			    }
1.1068    www      9224: 			
                   9225:                         }
1.1067    www      9226: 		    } else {
                   9227: #
                   9228: # Not importing, some other kind of non-package, non-library start tag
                   9229: # 
                   9230:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9231:                         if (defined($token->[2]->{'id'})) {
                   9232:                             $unikey.='_'.$token->[2]->{'id'};
                   9233:                         }
1.339     albertel 9234: 			if (defined($token->[2]->{'name'})) { 
                   9235: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9236: 			}
                   9237: 			$metathesekeys{$unikey}=1;
1.736     albertel 9238: 			foreach my $param (@{$token->[3]}) {
                   9239: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9240: 				$token->[2]->{$param};
1.339     albertel 9241: 			}
                   9242: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9243: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9244: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9245: 		 # only ws inside the tag, and not in default, so use default
                   9246: 		 # as value
1.599     albertel 9247: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9248: 			} elsif ( $internaltext =~ /\S/ ) {
                   9249: 		  # something interesting inside the tag
                   9250: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9251: 			} else {
1.908     albertel 9252: 		  # no interesting values, don't set a default
1.339     albertel 9253: 			}
1.172     www      9254: # end of not-a-package not-a-library import
1.339     albertel 9255: 		    }
1.172     www      9256: # end of not-a-package start tag
1.339     albertel 9257: 		}
1.172     www      9258: # the next is the end of "start tag"
1.339     albertel 9259: 	    }
                   9260: 	}
1.483     albertel 9261: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9262: 	$extension = lc($extension);
                   9263: 	if ($extension eq 'htm') { $extension='html'; }
                   9264: 
1.737     albertel 9265: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9266: 	    #no specific packages #how's our extension
                   9267: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9268: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9269: 					 \%metathesekeys);
                   9270: 	}
1.883     albertel 9271: 
                   9272: 	if (!exists($metaentry{':packages'})
                   9273: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9274: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9275: 		#no specific packages well let's get default then
                   9276: 		if ($key!~/^default&/) { next; }
1.488     albertel 9277: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9278: 					     \%metathesekeys);
                   9279: 	    }
                   9280: 	}
1.338     www      9281: # are there custom rights to evaluate
1.599     albertel 9282: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9283: 
1.338     www      9284:     #
                   9285:     # Importing a rights file here
1.339     albertel 9286:     #
                   9287: 	    unless ($depthcount) {
1.599     albertel 9288: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9289: 		my $dir=$filename;
                   9290: 		$dir=~s|[^/]*$||;
                   9291: 		$location=&filelocation($dir,$location);
1.736     albertel 9292: 		my $rights_metadata =
                   9293: 		    &metadata($uri,'keys',$location,'_rights',
                   9294: 			      $depthcount+1);
                   9295: 		foreach my $rights (split(',',$rights_metadata)) {
                   9296: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9297: 		    $metathesekeys{$rights}=1;
1.339     albertel 9298: 		}
                   9299: 	    }
                   9300: 	}
1.737     albertel 9301: 	# uniqifiy package listing
                   9302: 	my %seen;
                   9303: 	my @uniq_packages =
                   9304: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9305: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9306: 
1.1070    www      9307:         if ($importedparts) {
                   9308: # We had imported parts and need to rebuild partorder
                   9309:            $metaentry{':partorder'}='';
                   9310:            $metathesekeys{'partorder'}=1;
                   9311:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9312:                if ($origfileimportpartids[$index] eq 'part') {
                   9313: # original part, part of the problem
                   9314:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9315:                } else {
                   9316: # we have imported parts at this position
                   9317:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9318:                }
                   9319:            }
                   9320:            $metaentry{':partorder'}=~s/^\,//;
                   9321:         }
                   9322: 
1.737     albertel 9323: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9324: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9325: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9326: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9327: # this is the end of "was not already recently cached
1.71      www      9328:     }
1.599     albertel 9329:     return $metaentry{':'.$what};
1.261     albertel 9330: }
                   9331: 
1.488     albertel 9332: sub metadata_create_package_def {
1.483     albertel 9333:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9334:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9335:     if ($subp eq 'default') { next; }
                   9336:     
1.599     albertel 9337:     if (defined($metaentry{':packages'})) {
                   9338: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9339:     } else {
1.599     albertel 9340: 	$metaentry{':packages'}=$package;
1.483     albertel 9341:     }
                   9342:     my $value=$packagetab{$key};
                   9343:     my $unikey;
                   9344:     $unikey='parameter_0_'.$name;
1.599     albertel 9345:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9346:     $$metathesekeys{$unikey}=1;
1.599     albertel 9347:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9348: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9349:     }
1.599     albertel 9350:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9351: 	$metaentry{':'.$unikey}=
                   9352: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9353:     }
                   9354: }
                   9355: 
1.261     albertel 9356: sub metadata_generate_part0 {
                   9357:     my ($metadata,$metacache,$uri) = @_;
                   9358:     my %allnames;
1.737     albertel 9359:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9360: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9361: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9362: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9363: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9364: 	    $allnames{$name}=$part;
                   9365: 	  }
                   9366: 	}
                   9367:     }
                   9368:     foreach my $name (keys(%allnames)) {
                   9369:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9370:       my $key=":parameter_0_$name";
1.261     albertel 9371:       $$metacache{"$key.part"}='0';
                   9372:       $$metacache{"$key.name"}=$name;
1.428     albertel 9373:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9374: 					   $allnames{$name}.'_'.$name.
                   9375: 					   '.type'};
1.428     albertel 9376:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9377: 			     '.display'};
1.644     www      9378:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9379:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9380:       $$metacache{"$key.display"}=$olddis;
                   9381:     }
1.71      www      9382: }
                   9383: 
1.764     albertel 9384: # ------------------------------------------------------ Devalidate title cache
                   9385: 
                   9386: sub devalidate_title_cache {
                   9387:     my ($url)=@_;
                   9388:     if (!$env{'request.course.id'}) { return; }
                   9389:     my $symb=&symbread($url);
                   9390:     if (!$symb) { return; }
                   9391:     my $key=$env{'request.course.id'}."\0".$symb;
                   9392:     &devalidate_cache_new('title',$key);
                   9393: }
                   9394: 
1.1014    droeschl 9395: # ------------------------------------------------- Get the title of a course
                   9396: 
                   9397: sub current_course_title {
                   9398:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9399: }
1.301     www      9400: # ------------------------------------------------- Get the title of a resource
                   9401: 
                   9402: sub gettitle {
                   9403:     my $urlsymb=shift;
                   9404:     my $symb=&symbread($urlsymb);
1.534     albertel 9405:     if ($symb) {
1.620     albertel 9406: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9407: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9408: 	if (defined($cached)) { 
                   9409: 	    return $result;
                   9410: 	}
1.534     albertel 9411: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9412: 	my $title='';
1.907     albertel 9413: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9414: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9415: 	} else {
                   9416: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9417: 		    &GDBM_READER(),0640)) {
                   9418: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9419: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9420: 		untie(%bighash);
                   9421: 	    }
1.534     albertel 9422: 	}
                   9423: 	$title=~s/\&colon\;/\:/gs;
                   9424: 	if ($title) {
1.1159    www      9425: # Remember both $symb and $title for dynamic metadata
                   9426:             $accesshash{$symb.'___crstitle'}=$title;
1.1161  ! www      9427:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9428: # Cache this title and then return it
1.599     albertel 9429: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9430: 	}
                   9431: 	$urlsymb=$url;
                   9432:     }
                   9433:     my $title=&metadata($urlsymb,'title');
                   9434:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9435:     return $title;
1.301     www      9436: }
1.613     albertel 9437: 
1.614     albertel 9438: sub get_slot {
                   9439:     my ($which,$cnum,$cdom)=@_;
                   9440:     if (!$cnum || !$cdom) {
1.790     albertel 9441: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9442: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9443: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9444:     }
1.703     albertel 9445:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9446:     my %slotinfo;
                   9447:     if (exists($remembered{$key})) {
                   9448: 	$slotinfo{$which} = $remembered{$key};
                   9449:     } else {
                   9450: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9451: 	&Apache::lonhomework::showhash(%slotinfo);
                   9452: 	my ($tmp)=keys(%slotinfo);
                   9453: 	if ($tmp=~/^error:/) { return (); }
                   9454: 	$remembered{$key} = $slotinfo{$which};
                   9455:     }
1.616     albertel 9456:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9457: 	return %{$slotinfo{$which}};
                   9458:     }
                   9459:     return $slotinfo{$which};
1.614     albertel 9460: }
1.1150    raeburn  9461: 
                   9462: sub get_reservable_slots {
                   9463:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9464:     my $now = time;
                   9465:     my $reservable_info;
                   9466:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9467:     if (exists($remembered{$key})) {
                   9468:         $reservable_info = $remembered{$key};
                   9469:     } else {
                   9470:         my %resv;
                   9471:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9472:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9473:         $reservable_info = \%resv;
                   9474:         $remembered{$key} = $reservable_info;
                   9475:     }
                   9476:     return $reservable_info;
                   9477: }
                   9478: 
                   9479: sub get_course_slots {
                   9480:     my ($cnum,$cdom) = @_;
                   9481:     my $hashid=$cnum.':'.$cdom;
                   9482:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9483:     if (defined($cached)) {
                   9484:         if (ref($result) eq 'HASH') {
                   9485:             return %{$result};
                   9486:         }
                   9487:     } else {
                   9488:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9489:         my ($tmp) = keys(%slots);
                   9490:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9491:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9492:             return %slots;
                   9493:         }
                   9494:     }
                   9495:     return;
                   9496: }
                   9497: 
                   9498: sub devalidate_slots_cache {
                   9499:     my ($cnum,$cdom)=@_;
                   9500:     my $hashid=$cnum.':'.$cdom;
                   9501:     &devalidate_cache_new('allslots',$hashid);
                   9502: }
                   9503: 
1.31      www      9504: # ------------------------------------------------- Update symbolic store links
                   9505: 
                   9506: sub symblist {
                   9507:     my ($mapname,%newhash)=@_;
1.438     www      9508:     $mapname=&deversion(&declutter($mapname));
1.31      www      9509:     my %hash;
1.620     albertel 9510:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9511:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9512:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9513: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9514: 		next if ($url eq 'last_known'
                   9515: 			 && $env{'form.no_update_last_known'});
                   9516: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9517: 						    $newhash{$url}->[1],
                   9518: 						    $newhash{$url}->[0]);
1.191     harris41 9519:             }
1.31      www      9520:             if (untie(%hash)) {
                   9521: 		return 'ok';
                   9522:             }
                   9523:         }
                   9524:     }
                   9525:     return 'error';
1.212     www      9526: }
                   9527: 
                   9528: # --------------------------------------------------------------- Verify a symb
                   9529: 
                   9530: sub symbverify {
1.510     www      9531:     my ($symb,$thisurl)=@_;
                   9532:     my $thisfn=$thisurl;
1.439     www      9533:     $thisfn=&declutter($thisfn);
1.215     www      9534: # direct jump to resource in page or to a sequence - will construct own symbs
                   9535:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9536: # check URL part
1.409     www      9537:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9538: 
1.431     www      9539:     unless ($url eq $thisfn) { return 0; }
1.213     www      9540: 
1.216     www      9541:     $symb=&symbclean($symb);
1.510     www      9542:     $thisurl=&deversion($thisurl);
1.439     www      9543:     $thisfn=&deversion($thisfn);
1.213     www      9544: 
                   9545:     my %bighash;
                   9546:     my $okay=0;
1.431     www      9547: 
1.620     albertel 9548:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9549:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9550:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9551:             $thisurl =~ s/\?.+$//;
                   9552:         }
1.510     www      9553:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9554:         unless ($ids) {
                   9555:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9556:             $ids=$bighash{$idkey};
1.216     www      9557:         }
                   9558:         if ($ids) {
                   9559: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9560: 	    foreach my $id (split(/\,/,$ids)) {
                   9561: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9562:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9563:                    $symb =~ s/\?.+$//;
                   9564:                }
1.216     www      9565:                if (
                   9566:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9567:    eq $symb) { 
1.620     albertel 9568: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9569: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9570:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9571: 		       $okay=1; 
                   9572: 		   }
                   9573: 	       }
1.216     www      9574: 	   }
                   9575:         }
1.213     www      9576: 	untie(%bighash);
                   9577:     }
                   9578:     return $okay;
1.31      www      9579: }
                   9580: 
1.210     www      9581: # --------------------------------------------------------------- Clean-up symb
                   9582: 
                   9583: sub symbclean {
                   9584:     my $symb=shift;
1.568     albertel 9585:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9586: # remove version from map
                   9587:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9588: 
1.210     www      9589: # remove version from URL
                   9590:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9591: 
1.507     www      9592: # remove wrapper
                   9593: 
1.510     www      9594:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9595:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9596:     return $symb;
1.409     www      9597: }
                   9598: 
                   9599: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9600: 
                   9601: sub encode_symb {
                   9602:     my ($map,$resid,$url)=@_;
                   9603:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9604: }
1.409     www      9605: 
                   9606: sub decode_symb {
1.568     albertel 9607:     my $symb=shift;
                   9608:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9609:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9610:     return (&fixversion($map),$resid,&fixversion($url));
                   9611: }
                   9612: 
                   9613: sub fixversion {
                   9614:     my $fn=shift;
1.609     banghart 9615:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9616:     my %bighash;
                   9617:     my $uri=&clutter($fn);
1.620     albertel 9618:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9619: # is this cached?
1.599     albertel 9620:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9621:     if (defined($cached)) { return $result; }
                   9622: # unfortunately not cached, or expired
1.620     albertel 9623:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9624: 	    &GDBM_READER(),0640)) {
                   9625:  	if ($bighash{'version_'.$uri}) {
                   9626:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9627:  	    unless (($version eq 'mostrecent') || 
                   9628: 		    ($version==&getversion($uri))) {
1.440     www      9629:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9630:  	    }
                   9631:  	}
                   9632:  	untie %bighash;
1.413     www      9633:     }
1.599     albertel 9634:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9635: }
                   9636: 
                   9637: sub deversion {
                   9638:     my $url=shift;
                   9639:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9640:     return $url;
1.210     www      9641: }
                   9642: 
1.31      www      9643: # ------------------------------------------------------ Return symb list entry
                   9644: 
                   9645: sub symbread {
1.249     www      9646:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9647:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9648:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9649: # no filename provided? try from environment
1.44      www      9650:     unless ($thisfn) {
1.620     albertel 9651:         if ($env{'request.symb'}) {
                   9652: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9653: 	}
1.620     albertel 9654: 	$thisfn=$env{'request.filename'};
1.44      www      9655:     }
1.569     albertel 9656:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9657: # is that filename actually a symb? Verify, clean, and return
                   9658:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9659: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9660: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9661: 	}
1.242     www      9662:     }
1.44      www      9663:     $thisfn=declutter($thisfn);
1.31      www      9664:     my %hash;
1.37      www      9665:     my %bighash;
                   9666:     my $syval='';
1.620     albertel 9667:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9668:         my $targetfn = $thisfn;
1.609     banghart 9669:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9670:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9671:         }
1.687     albertel 9672: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9673: 	    $targetfn=$1;
                   9674: 	}
1.620     albertel 9675:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9676:                       &GDBM_READER(),0640)) {
1.481     raeburn  9677: 	    $syval=$hash{$targetfn};
1.37      www      9678:             untie(%hash);
                   9679:         }
                   9680: # ---------------------------------------------------------- There was an entry
                   9681:         if ($syval) {
1.601     albertel 9682: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9683: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9684: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9685: 		    #return $env{$cache_str}='';
1.601     albertel 9686: 		#}    
                   9687: 		#$syval.=$1;
                   9688: 	    #}
1.37      www      9689:         } else {
                   9690: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9691:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9692:                             &GDBM_READER(),0640)) {
1.37      www      9693: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9694:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9695:               unless ($ids) { 
                   9696:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9697:               }
                   9698:               unless ($ids) {
                   9699: # alias?
                   9700: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9701:               }
1.37      www      9702:               if ($ids) {
                   9703: # ------------------------------------------------------------------- Has ID(s)
                   9704:                  my @possibilities=split(/\,/,$ids);
1.39      www      9705:                  if ($#possibilities==0) {
                   9706: # ----------------------------------------------- There is only one possibility
1.37      www      9707: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9708: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9709: 						    $resid,$thisfn);
1.249     www      9710:                  } elsif (!$donotrecurse) {
1.39      www      9711: # ------------------------------------------ There is more than one possibility
                   9712:                      my $realpossible=0;
1.800     albertel 9713:                      foreach my $id (@possibilities) {
                   9714: 			 my $file=$bighash{'src_'.$id};
1.39      www      9715:                          if (&allowed('bre',$file)) {
1.800     albertel 9716:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9717:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9718: 				$realpossible++;
1.626     albertel 9719:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9720: 						    $resid,$thisfn);
1.39      www      9721:                             }
                   9722: 			 }
1.191     harris41 9723:                      }
1.39      www      9724: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9725:                  } else {
                   9726:                      $syval='';
1.37      www      9727:                  }
                   9728: 	      }
                   9729:               untie(%bighash)
1.481     raeburn  9730:            }
1.31      www      9731:         }
1.62      www      9732:         if ($syval) {
1.620     albertel 9733: 	    return $env{$cache_str}=$syval;
1.62      www      9734:         }
1.31      www      9735:     }
1.949     raeburn  9736:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9737:     return $env{$cache_str}='';
1.31      www      9738: }
                   9739: 
                   9740: # ---------------------------------------------------------- Return random seed
                   9741: 
1.32      www      9742: sub numval {
                   9743:     my $txt=shift;
                   9744:     $txt=~tr/A-J/0-9/;
                   9745:     $txt=~tr/a-j/0-9/;
                   9746:     $txt=~tr/K-T/0-9/;
                   9747:     $txt=~tr/k-t/0-9/;
                   9748:     $txt=~tr/U-Z/0-5/;
                   9749:     $txt=~tr/u-z/0-5/;
                   9750:     $txt=~s/\D//g;
1.564     albertel 9751:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9752:     return int($txt);
1.368     albertel 9753: }
                   9754: 
1.484     albertel 9755: sub numval2 {
                   9756:     my $txt=shift;
                   9757:     $txt=~tr/A-J/0-9/;
                   9758:     $txt=~tr/a-j/0-9/;
                   9759:     $txt=~tr/K-T/0-9/;
                   9760:     $txt=~tr/k-t/0-9/;
                   9761:     $txt=~tr/U-Z/0-5/;
                   9762:     $txt=~tr/u-z/0-5/;
                   9763:     $txt=~s/\D//g;
                   9764:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9765:     my $total;
                   9766:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9767:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9768:     return int($total);
                   9769: }
                   9770: 
1.575     albertel 9771: sub numval3 {
                   9772:     use integer;
                   9773:     my $txt=shift;
                   9774:     $txt=~tr/A-J/0-9/;
                   9775:     $txt=~tr/a-j/0-9/;
                   9776:     $txt=~tr/K-T/0-9/;
                   9777:     $txt=~tr/k-t/0-9/;
                   9778:     $txt=~tr/U-Z/0-5/;
                   9779:     $txt=~tr/u-z/0-5/;
                   9780:     $txt=~s/\D//g;
                   9781:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9782:     my $total;
                   9783:     foreach my $val (@txts) { $total+=$val; }
                   9784:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9785:     return $total;
                   9786: }
                   9787: 
1.675     albertel 9788: sub digest {
                   9789:     my ($data)=@_;
                   9790:     my $digest=&Digest::MD5::md5($data);
                   9791:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9792:     my ($e,$f);
                   9793:     {
                   9794:         use integer;
                   9795:         $e=($a+$b);
                   9796:         $f=($c+$d);
                   9797:         if ($_64bit) {
                   9798:             $e=(($e<<32)>>32);
                   9799:             $f=(($f<<32)>>32);
                   9800:         }
                   9801:     }
                   9802:     if (wantarray) {
                   9803: 	return ($e,$f);
                   9804:     } else {
                   9805: 	my $g;
                   9806: 	{
                   9807: 	    use integer;
                   9808: 	    $g=($e+$f);
                   9809: 	    if ($_64bit) {
                   9810: 		$g=(($g<<32)>>32);
                   9811: 	    }
                   9812: 	}
                   9813: 	return $g;
                   9814:     }
                   9815: }
                   9816: 
1.368     albertel 9817: sub latest_rnd_algorithm_id {
1.675     albertel 9818:     return '64bit5';
1.366     albertel 9819: }
1.32      www      9820: 
1.503     albertel 9821: sub get_rand_alg {
                   9822:     my ($courseid)=@_;
1.790     albertel 9823:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9824:     if ($courseid) {
1.620     albertel 9825: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9826:     }
                   9827:     return &latest_rnd_algorithm_id();
                   9828: }
                   9829: 
1.562     albertel 9830: sub validCODE {
                   9831:     my ($CODE)=@_;
                   9832:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9833:     return 0;
                   9834: }
                   9835: 
1.491     albertel 9836: sub getCODE {
1.620     albertel 9837:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9838:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9839: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9840: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9841: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9842:     }
                   9843:     return undef;
                   9844: }
1.1133    foxr     9845: #
                   9846: #  Determines the random seed for a specific context:
                   9847: #
                   9848: # parameters:
                   9849: #   symb      - in course context the symb for the seed.
                   9850: #   course_id - The course id of the form domain_coursenum.
                   9851: #   domain    - Domain for the user.
                   9852: #   course    - Course for the user.
                   9853: #   cenv      - environment of the course.
                   9854: #
                   9855: # NOTE:
                   9856: #   All parameters are picked out of the environment if missing
                   9857: #   or not defined.
                   9858: #   If a symb cannot be determined the current time is used instead.
                   9859: #
                   9860: #  For a given well defined symb, courside, domain, username,
                   9861: #  and course environment, the seed is reproducible.
                   9862: #
1.31      www      9863: sub rndseed {
1.1133    foxr     9864:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 9865:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9866:     if (!defined($symb)) {
1.366     albertel 9867: 	unless ($symb=$wsymb) { return time; }
                   9868:     }
1.1146    foxr     9869:     if (!defined $courseid) { 
                   9870: 	$courseid=$wcourseid; 
                   9871:     }
                   9872:     if (!defined $domain) { $domain=$wdomain; }
                   9873:     if (!defined $username) { $username=$wusername }
1.1133    foxr     9874: 
                   9875:     my $which;
                   9876:     if (defined($cenv->{'rndseed'})) {
                   9877: 	$which = $cenv->{'rndseed'};
                   9878:     } else {
                   9879: 	$which =&get_rand_alg($courseid);
                   9880:     }
1.491     albertel 9881:     if (defined(&getCODE())) {
1.1133    foxr     9882: 
1.675     albertel 9883: 	if ($which eq '64bit5') {
                   9884: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9885: 	} elsif ($which eq '64bit4') {
1.575     albertel 9886: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9887: 	} else {
                   9888: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9889: 	}
1.675     albertel 9890:     } elsif ($which eq '64bit5') {
                   9891: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9892:     } elsif ($which eq '64bit4') {
                   9893: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9894:     } elsif ($which eq '64bit3') {
                   9895: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9896:     } elsif ($which eq '64bit2') {
                   9897: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9898:     } elsif ($which eq '64bit') {
                   9899: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9900:     }
                   9901:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9902: }
                   9903: 
                   9904: sub rndseed_32bit {
                   9905:     my ($symb,$courseid,$domain,$username)=@_;
                   9906:     {
                   9907: 	use integer;
                   9908: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9909: 	my $symbseed=numval($symb) << 22;
                   9910: 	my $namechck=unpack("%32C*",$username) << 17;
                   9911: 	my $nameseed=numval($username) << 12;
                   9912: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9913: 	my $courseseed=unpack("%32C*",$courseid);
                   9914: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9915: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9916: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9917: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9918: 	return $num;
                   9919:     }
                   9920: }
                   9921: 
                   9922: sub rndseed_64bit {
                   9923:     my ($symb,$courseid,$domain,$username)=@_;
                   9924:     {
                   9925: 	use integer;
                   9926: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9927: 	my $symbseed=numval($symb) << 10;
                   9928: 	my $namechck=unpack("%32S*",$username);
                   9929: 	
                   9930: 	my $nameseed=numval($username) << 21;
                   9931: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9932: 	my $courseseed=unpack("%32S*",$courseid);
                   9933: 	
                   9934: 	my $num1=$symbchck+$symbseed+$namechck;
                   9935: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9936: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9937: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9938: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9939: 	return "$num1,$num2";
1.155     albertel 9940:     }
1.366     albertel 9941: }
                   9942: 
1.443     albertel 9943: sub rndseed_64bit2 {
                   9944:     my ($symb,$courseid,$domain,$username)=@_;
                   9945:     {
                   9946: 	use integer;
                   9947: 	# strings need to be an even # of cahracters long, it it is odd the
                   9948:         # last characters gets thrown away
                   9949: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9950: 	my $symbseed=numval($symb) << 10;
                   9951: 	my $namechck=unpack("%32S*",$username.' ');
                   9952: 	
                   9953: 	my $nameseed=numval($username) << 21;
1.501     albertel 9954: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9955: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9956: 	
                   9957: 	my $num1=$symbchck+$symbseed+$namechck;
                   9958: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9959: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9960: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9961: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9962: 	return "$num1,$num2";
                   9963:     }
                   9964: }
                   9965: 
                   9966: sub rndseed_64bit3 {
                   9967:     my ($symb,$courseid,$domain,$username)=@_;
                   9968:     {
                   9969: 	use integer;
                   9970: 	# strings need to be an even # of cahracters long, it it is odd the
                   9971:         # last characters gets thrown away
                   9972: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9973: 	my $symbseed=numval2($symb) << 10;
                   9974: 	my $namechck=unpack("%32S*",$username.' ');
                   9975: 	
                   9976: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9977: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9978: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9979: 	
                   9980: 	my $num1=$symbchck+$symbseed+$namechck;
                   9981: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9982: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9983: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9984: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9985: 	
1.503     albertel 9986: 	return "$num1:$num2";
1.443     albertel 9987:     }
                   9988: }
                   9989: 
1.575     albertel 9990: sub rndseed_64bit4 {
                   9991:     my ($symb,$courseid,$domain,$username)=@_;
                   9992:     {
                   9993: 	use integer;
                   9994: 	# strings need to be an even # of cahracters long, it it is odd the
                   9995:         # last characters gets thrown away
                   9996: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9997: 	my $symbseed=numval3($symb) << 10;
                   9998: 	my $namechck=unpack("%32S*",$username.' ');
                   9999: 	
                   10000: 	my $nameseed=numval3($username) << 21;
                   10001: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10002: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10003: 	
                   10004: 	my $num1=$symbchck+$symbseed+$namechck;
                   10005: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10006: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10007: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10008: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10009: 	
1.575     albertel 10010: 	return "$num1:$num2";
                   10011:     }
                   10012: }
                   10013: 
1.675     albertel 10014: sub rndseed_64bit5 {
                   10015:     my ($symb,$courseid,$domain,$username)=@_;
                   10016:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10017:     return "$num1:$num2";
                   10018: }
                   10019: 
1.366     albertel 10020: sub rndseed_CODE_64bit {
                   10021:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10022:     {
1.366     albertel 10023: 	use integer;
1.443     albertel 10024: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10025: 	my $symbseed=numval2($symb);
1.491     albertel 10026: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10027: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10028: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10029: 	my $num1=$symbseed+$CODEchck;
                   10030: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10031: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10032: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10033: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10034: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10035: 	return "$num1:$num2";
1.366     albertel 10036:     }
                   10037: }
                   10038: 
1.575     albertel 10039: sub rndseed_CODE_64bit4 {
                   10040:     my ($symb,$courseid,$domain,$username)=@_;
                   10041:     {
                   10042: 	use integer;
                   10043: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10044: 	my $symbseed=numval3($symb);
                   10045: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10046: 	my $CODEseed=numval3(&getCODE());
                   10047: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10048: 	my $num1=$symbseed+$CODEchck;
                   10049: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10050: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10051: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10052: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10053: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10054: 	return "$num1:$num2";
                   10055:     }
                   10056: }
                   10057: 
1.675     albertel 10058: sub rndseed_CODE_64bit5 {
                   10059:     my ($symb,$courseid,$domain,$username)=@_;
                   10060:     my $code = &getCODE();
                   10061:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10062:     return "$num1:$num2";
                   10063: }
                   10064: 
1.366     albertel 10065: sub setup_random_from_rndseed {
                   10066:     my ($rndseed)=@_;
1.503     albertel 10067:     if ($rndseed =~/([,:])/) {
                   10068: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10069: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10070:     } else {
                   10071: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10072:     }
1.36      albertel 10073: }
                   10074: 
1.474     albertel 10075: sub latest_receipt_algorithm_id {
1.835     albertel 10076:     return 'receipt3';
1.474     albertel 10077: }
                   10078: 
1.480     www      10079: sub recunique {
                   10080:     my $fucourseid=shift;
                   10081:     my $unique;
1.835     albertel 10082:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10083: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10084: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10085:     } else {
                   10086: 	$unique=$perlvar{'lonReceipt'};
                   10087:     }
                   10088:     return unpack("%32C*",$unique);
                   10089: }
                   10090: 
                   10091: sub recprefix {
                   10092:     my $fucourseid=shift;
                   10093:     my $prefix;
1.835     albertel 10094:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10095: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10096: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10097:     } else {
                   10098: 	$prefix=$perlvar{'lonHostID'};
                   10099:     }
                   10100:     return unpack("%32C*",$prefix);
                   10101: }
                   10102: 
1.76      www      10103: sub ireceipt {
1.474     albertel 10104:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10105: 
                   10106:     my $return =&recprefix($fucourseid).'-';
                   10107: 
                   10108:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10109: 	$env{'request.state'} eq 'construct') {
                   10110: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10111: 	return $return;
                   10112:     }
                   10113: 
1.76      www      10114:     my $cuname=unpack("%32C*",$funame);
                   10115:     my $cudom=unpack("%32C*",$fudom);
                   10116:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10117:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10118:     my $cunique=&recunique($fucourseid);
1.474     albertel 10119:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10120:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10121: 
1.790     albertel 10122: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10123: 			       
                   10124: 	$return.= ($cunique%$cuname+
                   10125: 		   $cunique%$cudom+
                   10126: 		   $cusymb%$cuname+
                   10127: 		   $cusymb%$cudom+
                   10128: 		   $cucourseid%$cuname+
                   10129: 		   $cucourseid%$cudom+
                   10130: 		   $cpart%$cuname+
                   10131: 		   $cpart%$cudom);
                   10132:     } else {
                   10133: 	$return.= ($cunique%$cuname+
                   10134: 		   $cunique%$cudom+
                   10135: 		   $cusymb%$cuname+
                   10136: 		   $cusymb%$cudom+
                   10137: 		   $cucourseid%$cuname+
                   10138: 		   $cucourseid%$cudom);
                   10139:     }
                   10140:     return $return;
1.76      www      10141: }
                   10142: 
                   10143: sub receipt {
1.474     albertel 10144:     my ($part)=@_;
1.790     albertel 10145:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10146:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10147: }
1.260     ng       10148: 
1.790     albertel 10149: sub whichuser {
                   10150:     my ($passedsymb)=@_;
                   10151:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10152:     if (defined($env{'form.grade_symb'})) {
                   10153: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10154: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10155: 	if (!$allowed &&
                   10156: 	    exists($env{'request.course.sec'}) &&
                   10157: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10158: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10159: 			      '/'.$env{'request.course.sec'});
                   10160: 	}
                   10161: 	if ($allowed) {
                   10162: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10163: 	    $courseid=$tmp_courseid;
                   10164: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10165: 	    ($name)=&get_env_multiple('form.grade_username');
                   10166: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10167: 	}
                   10168:     }
                   10169:     if (!$passedsymb) {
                   10170: 	$symb=&symbread();
                   10171:     } else {
                   10172: 	$symb=$passedsymb;
                   10173:     }
                   10174:     $courseid=$env{'request.course.id'};
                   10175:     $domain=$env{'user.domain'};
                   10176:     $name=$env{'user.name'};
                   10177:     if ($name eq 'public' && $domain eq 'public') {
                   10178: 	if (!defined($env{'form.username'})) {
                   10179: 	    $env{'form.username'}.=time.rand(10000000);
                   10180: 	}
                   10181: 	$name.=$env{'form.username'};
                   10182:     }
                   10183:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10184: 
                   10185: }
                   10186: 
1.36      albertel 10187: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10188: # returns either the contents of the file or 
                   10189: # -1 if the file doesn't exist
1.481     raeburn  10190: #
                   10191: # if the target is a file that was uploaded via DOCS, 
                   10192: # a check will be made to see if a current copy exists on the local server,
                   10193: # if it does this will be served, otherwise a copy will be retrieved from
                   10194: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10195: # the local server.   
1.472     albertel 10196: 
1.36      albertel 10197: sub getfile {
1.538     albertel 10198:     my ($file) = @_;
1.609     banghart 10199:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10200:     &repcopy($file);
                   10201:     return &readfile($file);
                   10202: }
                   10203: 
                   10204: sub repcopy_userfile {
                   10205:     my ($file)=@_;
1.1142    raeburn  10206:     my $londocroot = $perlvar{'lonDocRoot'};
                   10207:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
                   10208:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10209:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10210: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10211:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10212:     if (-e "$file") {
1.828     www      10213: # we already have a local copy, check it out
1.538     albertel 10214: 	my @fileinfo = stat($file);
1.828     www      10215: 	my $rtncode;
                   10216: 	my $info;
1.538     albertel 10217: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10218: 	if ($lwpresp ne 'ok') {
1.828     www      10219: # there is no such file anymore, even though we had a local copy
1.482     albertel 10220: 	    if ($rtncode eq '404') {
1.538     albertel 10221: 		unlink($file);
1.482     albertel 10222: 	    }
                   10223: 	    return -1;
                   10224: 	}
                   10225: 	if ($info < $fileinfo[9]) {
1.828     www      10226: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10227: 	    return 'ok';
1.828     www      10228: 	} else {
                   10229: # the file is outdated, get rid of it
                   10230: 	    unlink($file);
1.482     albertel 10231: 	}
1.828     www      10232:     }
                   10233: # one way or the other, at this point, we don't have the file
                   10234: # construct the correct path for the file
                   10235:     my @parts = ($cdom,$cnum); 
                   10236:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10237: 	push @parts, split(/\//,$1);
                   10238:     }
                   10239:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10240:     foreach my $part (@parts) {
                   10241: 	$path .= '/'.$part;
                   10242: 	if (!-e $path) {
                   10243: 	    mkdir($path,0770);
1.482     albertel 10244: 	}
                   10245:     }
1.828     www      10246: # now the path exists for sure
                   10247: # get a user agent
                   10248:     my $ua=new LWP::UserAgent;
                   10249:     my $transferfile=$file.'.in.transfer';
                   10250: # FIXME: this should flock
                   10251:     if (-e $transferfile) { return 'ok'; }
                   10252:     my $request;
                   10253:     $uri=~s/^\///;
1.980     raeburn  10254:     my $homeserver = &homeserver($cnum,$cdom);
                   10255:     my $protocol = $protocol{$homeserver};
                   10256:     $protocol = 'http' if ($protocol ne 'https');
                   10257:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10258:     my $response=$ua->request($request,$transferfile);
                   10259: # did it work?
                   10260:     if ($response->is_error()) {
                   10261: 	unlink($transferfile);
                   10262: 	&logthis("Userfile repcopy failed for $uri");
                   10263: 	return -1;
                   10264:     }
                   10265: # worked, rename the transfer file
                   10266:     rename($transferfile,$file);
1.607     raeburn  10267:     return 'ok';
1.481     raeburn  10268: }
                   10269: 
1.517     albertel 10270: sub tokenwrapper {
                   10271:     my $uri=shift;
1.980     raeburn  10272:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10273:     $uri=~s|^/||;
1.620     albertel 10274:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10275:     my $token=$1;
1.552     albertel 10276:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10277:     if ($udom && $uname && $file) {
                   10278: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10279:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10280:         my $homeserver = &homeserver($uname,$udom);
                   10281:         my $protocol = $protocol{$homeserver};
                   10282:         $protocol = 'http' if ($protocol ne 'https');
                   10283:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10284:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10285:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10286:     } else {
                   10287:         return '/adm/notfound.html';
                   10288:     }
                   10289: }
                   10290: 
1.828     www      10291: # call with reqtype HEAD: get last modification time
                   10292: # call with reqtype GET: get the file contents
                   10293: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10294: #
1.481     raeburn  10295: sub getuploaded {
                   10296:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10297:     $uri=~s/^\///;
1.980     raeburn  10298:     my $homeserver = &homeserver($cnum,$cdom);
                   10299:     my $protocol = $protocol{$homeserver};
                   10300:     $protocol = 'http' if ($protocol ne 'https');
                   10301:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10302:     my $ua=new LWP::UserAgent;
                   10303:     my $request=new HTTP::Request($reqtype,$uri);
                   10304:     my $response=$ua->request($request);
                   10305:     $$rtncode = $response->code;
1.482     albertel 10306:     if (! $response->is_success()) {
                   10307: 	return 'failed';
                   10308:     }      
                   10309:     if ($reqtype eq 'HEAD') {
1.486     www      10310: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10311:     } elsif ($reqtype eq 'GET') {
                   10312: 	$$info = $response->content;
1.472     albertel 10313:     }
1.482     albertel 10314:     return 'ok';
1.36      albertel 10315: }
                   10316: 
1.481     raeburn  10317: sub readfile {
                   10318:     my $file = shift;
                   10319:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10320:     my $fh;
                   10321:     open($fh,"<$file");
                   10322:     my $a='';
1.800     albertel 10323:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10324:     return $a;
                   10325: }
                   10326: 
1.36      albertel 10327: sub filelocation {
1.590     banghart 10328:     my ($dir,$file) = @_;
                   10329:     my $location;
                   10330:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10331: 
                   10332:     if ($file =~ m-^/adm/-) {
                   10333: 	$file=~s-^/adm/wrapper/-/-;
                   10334: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10335:     }
1.882     albertel 10336: 
1.1139    www      10337:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10338:         $location = $file;
1.609     banghart 10339:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10340:         my ($udom,$uname,$filename)=
1.811     albertel 10341:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10342:         my $home=&homeserver($uname,$udom);
                   10343:         my $is_me=0;
                   10344:         my @ids=&current_machine_ids();
                   10345:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10346:         if ($is_me) {
1.1117    foxr     10347:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10348:         } else {
                   10349:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10350:   	      $udom.'/'.$uname.'/'.$filename;
                   10351:         }
1.882     albertel 10352:     } elsif ($file =~ m-^/adm/-) {
                   10353: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10354:     } else {
                   10355:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10356:         $file=~s:^/(res|priv)/:/:;
                   10357:         my $space=$1;
1.590     banghart 10358:         if ( !( $file =~ m:^/:) ) {
                   10359:             $location = $dir. '/'.$file;
                   10360:         } else {
1.1142    raeburn  10361:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10362:         }
1.59      albertel 10363:     }
1.590     banghart 10364:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10365:     while ($location=~m{/\.\./}) {
                   10366: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10367: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10368: 	} else {
                   10369: 	    $location=~ s{/\.\./}{/}g;
                   10370: 	}
                   10371:     } #remove dir/..
1.590     banghart 10372:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10373:     return $location;
1.46      www      10374: }
1.36      albertel 10375: 
1.46      www      10376: sub hreflocation {
                   10377:     my ($dir,$file)=@_;
1.980     raeburn  10378:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10379: 	$file=filelocation($dir,$file);
1.700     albertel 10380:     } elsif ($file=~m-^/adm/-) {
                   10381: 	$file=~s-^/adm/wrapper/-/-;
                   10382: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10383:     }
                   10384:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10385: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10386:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10387: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10388: 	        {/uploaded/$1/$2/}x;
1.46      www      10389:     }
1.913     albertel 10390:     if ($file=~ m{^/userfiles/}) {
                   10391: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10392:     }
1.462     albertel 10393:     return $file;
1.465     albertel 10394: }
                   10395: 
1.1139    www      10396: 
                   10397: 
                   10398: 
                   10399: 
1.465     albertel 10400: sub current_machine_domains {
1.853     albertel 10401:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10402: }
                   10403: 
                   10404: sub machine_domains {
                   10405:     my ($hostname) = @_;
1.465     albertel 10406:     my @domains;
1.838     albertel 10407:     my %hostname = &all_hostnames();
1.465     albertel 10408:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10409: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10410: 	if ($hostname eq $name) {
1.844     albertel 10411: 	    push(@domains,&host_domain($id));
1.465     albertel 10412: 	}
                   10413:     }
                   10414:     return @domains;
                   10415: }
                   10416: 
                   10417: sub current_machine_ids {
1.853     albertel 10418:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10419: }
                   10420: 
                   10421: sub machine_ids {
                   10422:     my ($hostname) = @_;
                   10423:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10424:     my @ids;
1.888     albertel 10425:     my %name_to_host = &all_names();
1.889     albertel 10426:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10427: 	return @{ $name_to_host{$hostname} };
                   10428:     }
                   10429:     return;
1.31      www      10430: }
                   10431: 
1.824     raeburn  10432: sub additional_machine_domains {
                   10433:     my @domains;
                   10434:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10435:     while( my $line = <$fh>) {
                   10436:         $line =~ s/\s//g;
                   10437:         push(@domains,$line);
                   10438:     }
                   10439:     return @domains;
                   10440: }
                   10441: 
                   10442: sub default_login_domain {
                   10443:     my $domain = $perlvar{'lonDefDomain'};
                   10444:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10445:     foreach my $posdom (&current_machine_domains(),
                   10446:                         &additional_machine_domains()) {
                   10447:         if (lc($posdom) eq lc($testdomain)) {
                   10448:             $domain=$posdom;
                   10449:             last;
                   10450:         }
                   10451:     }
                   10452:     return $domain;
                   10453: }
                   10454: 
1.31      www      10455: # ------------------------------------------------------------- Declutters URLs
                   10456: 
                   10457: sub declutter {
                   10458:     my $thisfn=shift;
1.569     albertel 10459:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10460:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10461:     $thisfn=~s/^\///;
1.697     albertel 10462:     $thisfn=~s|^adm/wrapper/||;
                   10463:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10464:     $thisfn=~s/^res\///;
1.1032    raeburn  10465:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10466:         $thisfn=~s/\?.+$//;
                   10467:     }
1.268     www      10468:     return $thisfn;
                   10469: }
                   10470: 
                   10471: # ------------------------------------------------------------- Clutter up URLs
                   10472: 
                   10473: sub clutter {
                   10474:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10475:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10476: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10477:        $thisfn='/res'.$thisfn; 
                   10478:     }
1.1031    raeburn  10479:     if ($thisfn !~m|^/adm|) {
                   10480: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10481: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10482: 	} else {
                   10483: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10484: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10485: 	    if ($embstyle eq 'ssi'
                   10486: 		|| ($embstyle eq 'hdn')
                   10487: 		|| ($embstyle eq 'rat')
                   10488: 		|| ($embstyle eq 'prv')
                   10489: 		|| ($embstyle eq 'ign')) {
                   10490: 		#do nothing with these
                   10491: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10492: 		|| ($embstyle eq 'emb')
                   10493: 		|| ($embstyle eq 'wrp')) {
                   10494: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10495: 	    } elsif ($embstyle eq 'unk'
                   10496: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10497: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10498: 	    } else {
1.718     www      10499: #		&logthis("Got a blank emb style");
1.695     albertel 10500: 	    }
1.694     albertel 10501: 	}
                   10502:     }
1.31      www      10503:     return $thisfn;
1.12      www      10504: }
                   10505: 
1.787     albertel 10506: sub clutter_with_no_wrapper {
                   10507:     my $uri = &clutter(shift);
                   10508:     if ($uri =~ m-^/adm/-) {
                   10509: 	$uri =~ s-^/adm/wrapper/-/-;
                   10510: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10511:     }
                   10512:     return $uri;
                   10513: }
                   10514: 
1.557     albertel 10515: sub freeze_escape {
                   10516:     my ($value)=@_;
                   10517:     if (ref($value)) {
                   10518: 	$value=&nfreeze($value);
                   10519: 	return '__FROZEN__'.&escape($value);
                   10520:     }
                   10521:     return &escape($value);
                   10522: }
                   10523: 
1.11      www      10524: 
1.557     albertel 10525: sub thaw_unescape {
                   10526:     my ($value)=@_;
                   10527:     if ($value =~ /^__FROZEN__/) {
                   10528: 	substr($value,0,10,undef);
                   10529: 	$value=&unescape($value);
                   10530: 	return &thaw($value);
                   10531:     }
                   10532:     return &unescape($value);
                   10533: }
                   10534: 
1.436     albertel 10535: sub correct_line_ends {
                   10536:     my ($result)=@_;
                   10537:     $$result =~s/\r\n/\n/mg;
                   10538:     $$result =~s/\r/\n/mg;
1.415     albertel 10539: }
1.1       albertel 10540: # ================================================================ Main Program
                   10541: 
1.184     www      10542: sub goodbye {
1.204     albertel 10543:    &logthis("Starting Shut down");
1.443     albertel 10544: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10545:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10546: #converted
1.599     albertel 10547: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10548:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10549: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10550: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10551: #1.1 only
1.870     albertel 10552: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10553: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10554: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10555: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10556:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10557:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10558:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10559:    &flushcourselogs();
                   10560:    &logthis("Shutting down");
                   10561: }
                   10562: 
1.852     albertel 10563: sub get_dns {
1.869     albertel 10564:     my ($url,$func,$ignore_cache) = @_;
                   10565:     if (!$ignore_cache) {
                   10566: 	my ($content,$cached)=
                   10567: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10568: 	if ($cached) {
                   10569: 	    &$func($content);
                   10570: 	    return;
                   10571: 	}
                   10572:     }
                   10573: 
                   10574:     my %alldns;
1.852     albertel 10575:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10576:     foreach my $dns (<$config>) {
                   10577: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10578:         my $line = $1;
                   10579:         my ($host,$protocol) = split(/:/,$line);
                   10580:         if ($protocol ne 'https') {
                   10581:             $protocol = 'http';
                   10582:         }
                   10583: 	$alldns{$host} = $protocol;
1.869     albertel 10584:     }
                   10585:     while (%alldns) {
                   10586: 	my ($dns) = keys(%alldns);
1.852     albertel 10587: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10588:         $ua->timeout(30);
1.979     raeburn  10589: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10590: 	my $response=$ua->request($request);
1.979     raeburn  10591:         delete($alldns{$dns});
1.852     albertel 10592: 	next if ($response->is_error());
                   10593: 	my @content = split("\n",$response->content);
1.869     albertel 10594: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10595: 	&$func(\@content);
1.869     albertel 10596: 	return;
1.852     albertel 10597:     }
                   10598:     close($config);
1.871     albertel 10599:     my $which = (split('/',$url))[3];
                   10600:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10601:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10602:     my @content = <$config>;
                   10603:     &$func(\@content);
                   10604:     return;
1.852     albertel 10605: }
1.327     albertel 10606: # ------------------------------------------------------------ Read domain file
                   10607: {
1.852     albertel 10608:     my $loaded;
1.846     albertel 10609:     my %domain;
                   10610: 
1.852     albertel 10611:     sub parse_domain_tab {
                   10612: 	my ($lines) = @_;
                   10613: 	foreach my $line (@$lines) {
                   10614: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10615: 
1.846     albertel 10616: 	    chomp($line);
1.852     albertel 10617: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10618: 	    my %this_domain;
                   10619: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10620: 			       'lang_def', 'city', 'longi', 'lati',
                   10621: 			       'primary') {
                   10622: 		$this_domain{$field} = shift(@elements);
                   10623: 	    }
                   10624: 	    $domain{$name} = \%this_domain;
1.852     albertel 10625: 	}
                   10626:     }
1.864     albertel 10627: 
                   10628:     sub reset_domain_info {
                   10629: 	undef($loaded);
                   10630: 	undef(%domain);
                   10631:     }
                   10632: 
1.852     albertel 10633:     sub load_domain_tab {
1.869     albertel 10634: 	my ($ignore_cache) = @_;
                   10635: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10636: 	my $fh;
                   10637: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10638: 	    my @lines = <$fh>;
                   10639: 	    &parse_domain_tab(\@lines);
1.448     albertel 10640: 	}
1.852     albertel 10641: 	close($fh);
                   10642: 	$loaded = 1;
1.327     albertel 10643:     }
1.846     albertel 10644: 
                   10645:     sub domain {
1.852     albertel 10646: 	&load_domain_tab() if (!$loaded);
                   10647: 
1.846     albertel 10648: 	my ($name,$what) = @_;
                   10649: 	return if ( !exists($domain{$name}) );
                   10650: 
                   10651: 	if (!$what) {
                   10652: 	    return $domain{$name}{'description'};
                   10653: 	}
                   10654: 	return $domain{$name}{$what};
                   10655:     }
1.974     raeburn  10656: 
                   10657:     sub domain_info {
                   10658:         &load_domain_tab() if (!$loaded);
                   10659:         return %domain;
                   10660:     }
                   10661: 
1.327     albertel 10662: }
                   10663: 
                   10664: 
1.1       albertel 10665: # ------------------------------------------------------------- Read hosts file
                   10666: {
1.838     albertel 10667:     my %hostname;
1.844     albertel 10668:     my %hostdom;
1.845     albertel 10669:     my %libserv;
1.852     albertel 10670:     my $loaded;
1.888     albertel 10671:     my %name_to_host;
1.1074    raeburn  10672:     my %internetdom;
1.1107    raeburn  10673:     my %LC_dns_serv;
1.852     albertel 10674: 
                   10675:     sub parse_hosts_tab {
                   10676: 	my ($file) = @_;
                   10677: 	foreach my $configline (@$file) {
                   10678: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10679:             chomp($configline);
                   10680: 	    if ($configline =~ /^\^/) {
                   10681:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10682:                     $LC_dns_serv{$1} = 1;
                   10683:                 }
                   10684:                 next;
                   10685:             }
1.1074    raeburn  10686: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10687: 	    $name=~s/\s//g;
                   10688: 	    if ($id && $domain && $role && $name) {
                   10689: 		$hostname{$id}=$name;
1.888     albertel 10690: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10691: 		$hostdom{$id}=$domain;
                   10692: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10693:                 if (defined($protocol)) {
                   10694:                     if ($protocol eq 'https') {
                   10695:                         $protocol{$id} = $protocol;
                   10696:                     } else {
                   10697:                         $protocol{$id} = 'http'; 
                   10698:                     }
1.968     raeburn  10699:                 } else {
1.969     raeburn  10700:                     $protocol{$id} = 'http';
1.968     raeburn  10701:                 }
1.1074    raeburn  10702:                 if (defined($intdom)) {
                   10703:                     $internetdom{$id} = $intdom;
                   10704:                 }
1.852     albertel 10705: 	    }
                   10706: 	}
                   10707:     }
1.864     albertel 10708:     
                   10709:     sub reset_hosts_info {
1.897     albertel 10710: 	&purge_remembered();
1.864     albertel 10711: 	&reset_domain_info();
                   10712: 	&reset_hosts_ip_info();
1.892     albertel 10713: 	undef(%name_to_host);
1.864     albertel 10714: 	undef(%hostname);
                   10715: 	undef(%hostdom);
                   10716: 	undef(%libserv);
                   10717: 	undef($loaded);
                   10718:     }
1.1       albertel 10719: 
1.852     albertel 10720:     sub load_hosts_tab {
1.869     albertel 10721: 	my ($ignore_cache) = @_;
                   10722: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10723: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10724: 	my @config = <$config>;
                   10725: 	&parse_hosts_tab(\@config);
                   10726: 	close($config);
                   10727: 	$loaded=1;
1.1       albertel 10728:     }
1.852     albertel 10729: 
1.838     albertel 10730:     sub hostname {
1.852     albertel 10731: 	&load_hosts_tab() if (!$loaded);
                   10732: 
1.838     albertel 10733: 	my ($lonid) = @_;
                   10734: 	return $hostname{$lonid};
                   10735:     }
1.845     albertel 10736: 
1.838     albertel 10737:     sub all_hostnames {
1.852     albertel 10738: 	&load_hosts_tab() if (!$loaded);
                   10739: 
1.838     albertel 10740: 	return %hostname;
                   10741:     }
1.845     albertel 10742: 
1.888     albertel 10743:     sub all_names {
                   10744: 	&load_hosts_tab() if (!$loaded);
                   10745: 
                   10746: 	return %name_to_host;
                   10747:     }
                   10748: 
1.974     raeburn  10749:     sub all_host_domain {
                   10750:         &load_hosts_tab() if (!$loaded);
                   10751:         return %hostdom;
                   10752:     }
                   10753: 
1.845     albertel 10754:     sub is_library {
1.852     albertel 10755: 	&load_hosts_tab() if (!$loaded);
                   10756: 
1.845     albertel 10757: 	return exists($libserv{$_[0]});
                   10758:     }
                   10759: 
                   10760:     sub all_library {
1.852     albertel 10761: 	&load_hosts_tab() if (!$loaded);
                   10762: 
1.845     albertel 10763: 	return %libserv;
                   10764:     }
                   10765: 
1.1062    droeschl 10766:     sub unique_library {
                   10767: 	#2x reverse removes all hostnames that appear more than once
                   10768:         my %unique = reverse &all_library();
                   10769:         return reverse %unique;
                   10770:     }
                   10771: 
1.841     albertel 10772:     sub get_servers {
1.852     albertel 10773: 	&load_hosts_tab() if (!$loaded);
                   10774: 
1.841     albertel 10775: 	my ($domain,$type) = @_;
                   10776: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10777: 	                                          : %hostname;
                   10778: 	my %result;
1.842     albertel 10779: 	if (ref($domain) eq 'ARRAY') {
                   10780: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10781: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10782: 		    $result{$host} = $hostname;
                   10783: 		}
                   10784: 	    }
                   10785: 	} else {
                   10786: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10787: 		if ($hostdom{$host} eq $domain) {
                   10788: 		    $result{$host} = $hostname;
                   10789: 		}
1.841     albertel 10790: 	    }
                   10791: 	}
                   10792: 	return %result;
                   10793:     }
1.845     albertel 10794: 
1.1062    droeschl 10795:     sub get_unique_servers {
                   10796:         my %unique = reverse &get_servers(@_);
                   10797: 	return reverse %unique;
                   10798:     }
                   10799: 
1.844     albertel 10800:     sub host_domain {
1.852     albertel 10801: 	&load_hosts_tab() if (!$loaded);
                   10802: 
1.844     albertel 10803: 	my ($lonid) = @_;
                   10804: 	return $hostdom{$lonid};
                   10805:     }
                   10806: 
1.841     albertel 10807:     sub all_domains {
1.852     albertel 10808: 	&load_hosts_tab() if (!$loaded);
                   10809: 
1.841     albertel 10810: 	my %seen;
                   10811: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10812: 	return @uniq;
                   10813:     }
1.1074    raeburn  10814: 
                   10815:     sub internet_dom {
                   10816:         &load_hosts_tab() if (!$loaded);
                   10817: 
                   10818:         my ($lonid) = @_;
                   10819:         return $internetdom{$lonid};
                   10820:     }
1.1107    raeburn  10821: 
                   10822:     sub is_LC_dns {
                   10823:         &load_hosts_tab() if (!$loaded);
                   10824: 
                   10825:         my ($hostname) = @_;
                   10826:         return exists($LC_dns_serv{$hostname});
                   10827:     }
                   10828: 
1.1       albertel 10829: }
                   10830: 
1.847     albertel 10831: { 
                   10832:     my %iphost;
1.856     albertel 10833:     my %name_to_ip;
                   10834:     my %lonid_to_ip;
1.869     albertel 10835: 
1.847     albertel 10836:     sub get_hosts_from_ip {
                   10837: 	my ($ip) = @_;
                   10838: 	my %iphosts = &get_iphost();
                   10839: 	if (ref($iphosts{$ip})) {
                   10840: 	    return @{$iphosts{$ip}};
                   10841: 	}
                   10842: 	return;
1.839     albertel 10843:     }
1.864     albertel 10844:     
                   10845:     sub reset_hosts_ip_info {
                   10846: 	undef(%iphost);
                   10847: 	undef(%name_to_ip);
                   10848: 	undef(%lonid_to_ip);
                   10849:     }
1.856     albertel 10850: 
                   10851:     sub get_host_ip {
                   10852: 	my ($lonid) = @_;
                   10853: 	if (exists($lonid_to_ip{$lonid})) {
                   10854: 	    return $lonid_to_ip{$lonid};
                   10855: 	}
                   10856: 	my $name=&hostname($lonid);
                   10857:    	my $ip = gethostbyname($name);
                   10858: 	return if (!$ip || length($ip) ne 4);
                   10859: 	$ip=inet_ntoa($ip);
                   10860: 	$name_to_ip{$name}   = $ip;
                   10861: 	$lonid_to_ip{$lonid} = $ip;
                   10862: 	return $ip;
                   10863:     }
1.847     albertel 10864:     
                   10865:     sub get_iphost {
1.869     albertel 10866: 	my ($ignore_cache) = @_;
1.894     albertel 10867: 
1.869     albertel 10868: 	if (!$ignore_cache) {
                   10869: 	    if (%iphost) {
                   10870: 		return %iphost;
                   10871: 	    }
                   10872: 	    my ($ip_info,$cached)=
                   10873: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10874: 	    if ($cached) {
                   10875: 		%iphost      = %{$ip_info->[0]};
                   10876: 		%name_to_ip  = %{$ip_info->[1]};
                   10877: 		%lonid_to_ip = %{$ip_info->[2]};
                   10878: 		return %iphost;
                   10879: 	    }
                   10880: 	}
1.894     albertel 10881: 
                   10882: 	# get yesterday's info for fallback
                   10883: 	my %old_name_to_ip;
                   10884: 	my ($ip_info,$cached)=
                   10885: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10886: 	if ($cached) {
                   10887: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10888: 	}
                   10889: 
1.888     albertel 10890: 	my %name_to_host = &all_names();
                   10891: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10892: 	    my $ip;
                   10893: 	    if (!exists($name_to_ip{$name})) {
                   10894: 		$ip = gethostbyname($name);
                   10895: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10896: 		    if (defined($old_name_to_ip{$name})) {
                   10897: 			$ip = $old_name_to_ip{$name};
                   10898: 			&logthis("Can't find $name defaulting to old $ip");
                   10899: 		    } else {
                   10900: 			&logthis("Name $name no IP found");
                   10901: 			next;
                   10902: 		    }
                   10903: 		} else {
                   10904: 		    $ip=inet_ntoa($ip);
1.847     albertel 10905: 		}
                   10906: 		$name_to_ip{$name} = $ip;
                   10907: 	    } else {
                   10908: 		$ip = $name_to_ip{$name};
1.653     albertel 10909: 	    }
1.888     albertel 10910: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10911: 		$lonid_to_ip{$id} = $ip;
                   10912: 	    }
                   10913: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10914: 	}
1.869     albertel 10915: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10916: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10917: 				      48*60*60);
1.869     albertel 10918: 
1.847     albertel 10919: 	return %iphost;
1.598     albertel 10920:     }
                   10921: 
1.992     raeburn  10922:     #
                   10923:     #  Given a DNS returns the loncapa host name for that DNS 
                   10924:     # 
                   10925:     sub host_from_dns {
                   10926:         my ($dns) = @_;
                   10927:         my @hosts;
                   10928:         my $ip;
                   10929: 
1.993     raeburn  10930:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10931:             $ip = $name_to_ip{$dns};
                   10932:         }
                   10933:         if (!$ip) {
                   10934:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10935:             if (length($ip) == 4) { 
                   10936: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10937:             }
                   10938:         }
                   10939:         if ($ip) {
                   10940: 	    @hosts = get_hosts_from_ip($ip);
                   10941: 	    return $hosts[0];
                   10942:         }
                   10943:         return undef;
1.986     foxr     10944:     }
1.992     raeburn  10945: 
1.1074    raeburn  10946:     sub get_internet_names {
                   10947:         my ($lonid) = @_;
                   10948:         return if ($lonid eq '');
                   10949:         my ($idnref,$cached)=
                   10950:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10951:         if ($cached) {
                   10952:             return $idnref;
                   10953:         }
                   10954:         my $ip = &get_host_ip($lonid);
                   10955:         my @hosts = &get_hosts_from_ip($ip);
                   10956:         my %iphost = &get_iphost();
                   10957:         my (@idns,%seen);
                   10958:         foreach my $id (@hosts) {
                   10959:             my $dom = &host_domain($id);
                   10960:             my $prim_id = &domain($dom,'primary');
                   10961:             my $prim_ip = &get_host_ip($prim_id);
                   10962:             next if ($seen{$prim_ip});
                   10963:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10964:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10965:                     my $intdom = &internet_dom($id);
                   10966:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10967:                         push(@idns,$intdom);
                   10968:                     }
                   10969:                 }
                   10970:             }
                   10971:             $seen{$prim_ip} = 1;
                   10972:         }
                   10973:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10974:     }
                   10975: 
1.986     foxr     10976: }
                   10977: 
1.1079    raeburn  10978: sub all_loncaparevs {
                   10979:     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);
                   10980: }
                   10981: 
1.862     albertel 10982: BEGIN {
                   10983: 
                   10984: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10985:     unless ($readit) {
                   10986: {
                   10987:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10988:     %perlvar = (%perlvar,%{$configvars});
                   10989: }
                   10990: 
                   10991: 
1.1       albertel 10992: # ------------------------------------------------------ Read spare server file
                   10993: {
1.448     albertel 10994:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10995: 
                   10996:     while (my $configline=<$config>) {
                   10997:        chomp($configline);
1.284     matthew  10998:        if ($configline) {
1.784     albertel 10999: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11000: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11001: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11002:        }
                   11003:     }
1.448     albertel 11004:     close($config);
1.1       albertel 11005: }
1.11      www      11006: # ------------------------------------------------------------ Read permissions
                   11007: {
1.448     albertel 11008:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11009: 
                   11010:     while (my $configline=<$config>) {
1.448     albertel 11011: 	chomp($configline);
                   11012: 	if ($configline) {
                   11013: 	    my ($role,$perm)=split(/ /,$configline);
                   11014: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11015: 	}
1.11      www      11016:     }
1.448     albertel 11017:     close($config);
1.11      www      11018: }
                   11019: 
                   11020: # -------------------------------------------- Read plain texts for permissions
                   11021: {
1.448     albertel 11022:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11023: 
                   11024:     while (my $configline=<$config>) {
1.448     albertel 11025: 	chomp($configline);
                   11026: 	if ($configline) {
1.742     raeburn  11027: 	    my ($short,@plain)=split(/:/,$configline);
                   11028:             %{$prp{$short}} = ();
                   11029: 	    if (@plain > 0) {
                   11030:                 $prp{$short}{'std'} = $plain[0];
                   11031:                 for (my $i=1; $i<@plain; $i++) {
                   11032:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11033:                 }
                   11034:             }
1.448     albertel 11035: 	}
1.135     www      11036:     }
1.448     albertel 11037:     close($config);
1.135     www      11038: }
                   11039: 
                   11040: # ---------------------------------------------------------- Read package table
                   11041: {
1.448     albertel 11042:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11043: 
                   11044:     while (my $configline=<$config>) {
1.483     albertel 11045: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11046: 	chomp($configline);
                   11047: 	my ($short,$plain)=split(/:/,$configline);
                   11048: 	my ($pack,$name)=split(/\&/,$short);
                   11049: 	if ($plain ne '') {
                   11050: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11051: 	    $packagetab{$short}=$plain; 
                   11052: 	}
1.11      www      11053:     }
1.448     albertel 11054:     close($config);
1.329     matthew  11055: }
                   11056: 
1.1073    raeburn  11057: # ---------------------------------------------------------- Read loncaparev table
                   11058: {
                   11059:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11060:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11061:             while (my $configline=<$config>) {
                   11062:                 chomp($configline);
                   11063:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11064:                 $loncaparevs{$hostid}=$loncaparev;
                   11065:             }
                   11066:             close($config);
                   11067:         }
                   11068:     }
                   11069: }
                   11070: 
1.1074    raeburn  11071: # ---------------------------------------------------------- Read serverhostID table
                   11072: {
                   11073:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11074:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11075:             while (my $configline=<$config>) {
                   11076:                 chomp($configline);
                   11077:                 my ($name,$id)=split(/:/,$configline);
                   11078:                 $serverhomeIDs{$name}=$id;
                   11079:             }
                   11080:             close($config);
                   11081:         }
                   11082:     }
                   11083: }
                   11084: 
1.1079    raeburn  11085: {
                   11086:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11087:     if (-e $file) {
                   11088:         my $parser = HTML::LCParser->new($file);
                   11089:         while (my $token = $parser->get_token()) {
                   11090:             if ($token->[0] eq 'S') {
                   11091:                 my $item = $token->[1];
                   11092:                 my $name = $token->[2]{'name'};
                   11093:                 my $value = $token->[2]{'value'};
                   11094:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11095:                     my $release = $parser->get_text();
                   11096:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11097:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11098:                 }
                   11099:             }
                   11100:         }
                   11101:     }
1.1073    raeburn  11102: }
                   11103: 
1.1138    raeburn  11104: # ---------------------------------------------------------- Read managers table
                   11105: {
                   11106:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11107:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11108:             while (my $configline=<$config>) {
                   11109:                 chomp($configline);
                   11110:                 next if ($configline =~ /^\#/);
                   11111:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11112:                     $managerstab{$configline} = 1;
                   11113:                 }
                   11114:             }
                   11115:             close($config);
                   11116:         }
                   11117:     }
                   11118: }
                   11119: 
1.329     matthew  11120: # ------------- set up temporary directory
                   11121: {
1.1117    foxr     11122:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11123: 
1.11      www      11124: }
                   11125: 
1.794     albertel 11126: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11127: 				'compress_threshold'=> 20_000,
                   11128:  			        });
1.185     www      11129: 
1.281     www      11130: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11131: $dumpcount=0;
1.958     www      11132: $locknum=0;
1.22      www      11133: 
1.163     harris41 11134: &logtouch();
1.672     albertel 11135: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11136: $readit=1;
1.564     albertel 11137:     {
                   11138: 	use integer;
                   11139: 	my $test=(2**32)+1;
1.568     albertel 11140: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11141: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11142:     }
1.195     www      11143: }
1.1       albertel 11144: }
1.179     www      11145: 
1.1       albertel 11146: 1;
1.191     harris41 11147: __END__
                   11148: 
1.243     albertel 11149: =pod
                   11150: 
1.191     harris41 11151: =head1 NAME
                   11152: 
1.243     albertel 11153: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11154: 
                   11155: =head1 SYNOPSIS
                   11156: 
1.243     albertel 11157: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11158: 
                   11159:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11160: 
1.243     albertel 11161: Common parameters:
                   11162: 
                   11163: =over 4
                   11164: 
                   11165: =item *
                   11166: 
                   11167: $uname : an internal username (if $cname expecting a course Id specifically)
                   11168: 
                   11169: =item *
                   11170: 
                   11171: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11172: 
                   11173: =item *
                   11174: 
                   11175: $symb : a resource instance identifier
                   11176: 
                   11177: =item *
                   11178: 
                   11179: $namespace : the name of a .db file that contains the data needed or
                   11180: being set.
                   11181: 
                   11182: =back
                   11183: 
1.394     bowersj2 11184: =head1 OVERVIEW
1.191     harris41 11185: 
1.394     bowersj2 11186: lonnet provides subroutines which interact with the
                   11187: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11188: about classes, users, and resources.
1.243     albertel 11189: 
                   11190: For many of these objects you can also use this to store data about
                   11191: them or modify them in various ways.
1.191     harris41 11192: 
1.394     bowersj2 11193: =head2 Symbs
1.191     harris41 11194: 
1.394     bowersj2 11195: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11196: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11197: map, the resource number of the resource in the map, and the URL of
                   11198: the resource itself. The latter is somewhat redundant, but might help
                   11199: if maps change.
                   11200: 
                   11201: An example is
                   11202: 
                   11203:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11204: 
                   11205: The respective map entry is
                   11206: 
                   11207:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11208:   title="Problem 2">
                   11209:  </resource>
                   11210: 
                   11211: Symbs are used by the random number generator, as well as to store and
                   11212: restore data specific to a certain instance of for example a problem.
                   11213: 
                   11214: =head2 Storing And Retrieving Data
                   11215: 
                   11216: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11217: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11218: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11219: is is the non-critical message twin of cstore. These functions are for
                   11220: handlers to store a perl hash to a user's permanent data space in an
                   11221: easy manner, and to retrieve it again on another call. It is expected
                   11222: that a handler would use this once at the beginning to retrieve data,
                   11223: and then again once at the end to send only the new data back.
                   11224: 
                   11225: The data is stored in the user's data directory on the user's
                   11226: homeserver under the ID of the course.
                   11227: 
                   11228: The hash that is returned by restore will have all of the previous
                   11229: value for all of the elements of the hash.
                   11230: 
                   11231: Example:
                   11232: 
                   11233:  #creating a hash
                   11234:  my %hash;
                   11235:  $hash{'foo'}='bar';
                   11236: 
                   11237:  #storing it
                   11238:  &Apache::lonnet::cstore(\%hash);
                   11239: 
                   11240:  #changing a value
                   11241:  $hash{'foo'}='notbar';
                   11242: 
                   11243:  #adding a new value
                   11244:  $hash{'bar'}='foo';
                   11245:  &Apache::lonnet::cstore(\%hash);
                   11246: 
                   11247:  #retrieving the hash
                   11248:  my %history=&Apache::lonnet::restore();
                   11249: 
                   11250:  #print the hash
                   11251:  foreach my $key (sort(keys(%history))) {
                   11252:    print("\%history{$key} = $history{$key}");
                   11253:  }
                   11254: 
                   11255: Will print out:
1.191     harris41 11256: 
1.394     bowersj2 11257:  %history{1:foo} = bar
                   11258:  %history{1:keys} = foo:timestamp
                   11259:  %history{1:timestamp} = 990455579
                   11260:  %history{2:bar} = foo
                   11261:  %history{2:foo} = notbar
                   11262:  %history{2:keys} = foo:bar:timestamp
                   11263:  %history{2:timestamp} = 990455580
                   11264:  %history{bar} = foo
                   11265:  %history{foo} = notbar
                   11266:  %history{timestamp} = 990455580
                   11267:  %history{version} = 2
                   11268: 
                   11269: Note that the special hash entries C<keys>, C<version> and
                   11270: C<timestamp> were added to the hash. C<version> will be equal to the
                   11271: total number of versions of the data that have been stored. The
                   11272: C<timestamp> attribute will be the UNIX time the hash was
                   11273: stored. C<keys> is available in every historical section to list which
                   11274: keys were added or changed at a specific historical revision of a
                   11275: hash.
                   11276: 
                   11277: B<Warning>: do not store the hash that restore returns directly. This
                   11278: will cause a mess since it will restore the historical keys as if the
                   11279: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11280: 
1.394     bowersj2 11281: Calling convention:
1.191     harris41 11282: 
1.394     bowersj2 11283:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11284:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11285: 
1.394     bowersj2 11286: For more detailed information, see lonnet specific documentation.
1.191     harris41 11287: 
1.394     bowersj2 11288: =head1 RETURN MESSAGES
1.191     harris41 11289: 
1.394     bowersj2 11290: =over 4
1.191     harris41 11291: 
1.394     bowersj2 11292: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11293: 
1.394     bowersj2 11294: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11295: when the connection is brought back up
1.191     harris41 11296: 
1.394     bowersj2 11297: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11298: for later delivery
1.191     harris41 11299: 
1.967     bisitz   11300: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11301: 
1.394     bowersj2 11302: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11303: that was requested
1.191     harris41 11304: 
1.243     albertel 11305: =back
1.191     harris41 11306: 
1.243     albertel 11307: =head1 PUBLIC SUBROUTINES
1.191     harris41 11308: 
1.243     albertel 11309: =head2 Session Environment Functions
1.191     harris41 11310: 
1.243     albertel 11311: =over 4
1.191     harris41 11312: 
1.394     bowersj2 11313: =item * 
                   11314: X<appenv()>
1.949     raeburn  11315: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11316: the user envirnoment file, and will be restored for each access this
1.620     albertel 11317: user makes during this session, also modifies the %env for the current
1.949     raeburn  11318: process. Optional rolesarrayref - if defined contains a reference to an array
                   11319: of roles which are exempt from the restriction on modifying user.role entries 
                   11320: in the user's environment.db and in %env.    
1.191     harris41 11321: 
                   11322: =item *
1.394     bowersj2 11323: X<delenv()>
1.987     raeburn  11324: B<delenv($delthis,$regexp)>: removes all items from the session
                   11325: environment file that begin with $delthis. If the 
                   11326: optional second arg - $regexp - is true, $delthis is treated as a 
                   11327: regular expression, otherwise \Q$delthis\E is used. 
                   11328: The values are also deleted from the current processes %env.
1.191     harris41 11329: 
1.795     albertel 11330: =item * get_env_multiple($name) 
                   11331: 
                   11332: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11333: values may be defined and end up as an array ref.
                   11334: 
                   11335: returns an array of values
                   11336: 
1.243     albertel 11337: =back
                   11338: 
                   11339: =head2 User Information
1.191     harris41 11340: 
1.243     albertel 11341: =over 4
1.191     harris41 11342: 
                   11343: =item *
1.394     bowersj2 11344: X<queryauthenticate()>
                   11345: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11346: authentication scheme
                   11347: 
                   11348: =item *
1.394     bowersj2 11349: X<authenticate()>
1.1073    raeburn  11350: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11351: authenticate user from domain's lib servers (first use the current
                   11352: one). C<$upass> should be the users password.
1.1073    raeburn  11353: $checkdefauth is optional (value is 1 if a check should be made to
                   11354:    authenticate user using default authentication method, and allow
                   11355:    account creation if username does not have account in the domain).
                   11356: $clientcancheckhost is optional (value is 1 if checking whether the
                   11357:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11358: 
                   11359: =item *
1.394     bowersj2 11360: X<homeserver()>
                   11361: B<homeserver($uname,$udom)>: find the server which has
                   11362: the user's directory and files (there must be only one), this caches
                   11363: the answer, and also caches if there is a borken connection.
1.191     harris41 11364: 
                   11365: =item *
1.394     bowersj2 11366: X<idget()>
                   11367: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11368: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11369: username, and only 1 username per ID in a specific domain) (returns
                   11370: hash: id=>name,id=>name)
1.191     harris41 11371: 
                   11372: =item *
1.394     bowersj2 11373: X<idrget()>
                   11374: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11375: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11376: 
                   11377: =item *
1.394     bowersj2 11378: X<idput()>
                   11379: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11380: 
                   11381: =item *
1.394     bowersj2 11382: X<rolesinit()>
                   11383: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 11384: 
                   11385: =item *
1.551     albertel 11386: X<getsection()>
                   11387: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11388: course $cname, return section name/number or '' for "not in course"
                   11389: and '-1' for "no section"
                   11390: 
                   11391: =item *
1.394     bowersj2 11392: X<userenvironment()>
                   11393: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11394: passed in @what from the requested user's environment, returns a hash
                   11395: 
1.858     raeburn  11396: =item * 
                   11397: X<userlog_query()>
1.859     albertel 11398: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11399: activity.log file. %filters defines filters applied when parsing the
                   11400: log file. These can be start or end timestamps, or the type of action
                   11401: - log to look for Login or Logout events, check for Checkin or
                   11402: Checkout, role for role selection. The response is in the form
                   11403: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11404: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11405: 
1.243     albertel 11406: =back
                   11407: 
                   11408: =head2 User Roles
                   11409: 
                   11410: =over 4
                   11411: 
                   11412: =item *
                   11413: 
1.810     raeburn  11414: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11415:  F: full access
                   11416:  U,I,K: authentication modes (cxx only)
                   11417:  '': forbidden
                   11418:  1: user needs to choose course
                   11419:  2: browse allowed
1.766     albertel 11420:  A: passphrase authentication needed
1.243     albertel 11421: 
                   11422: =item *
                   11423: 
                   11424: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11425: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11426: and course level
                   11427: 
                   11428: =item *
                   11429: 
1.988     raeburn  11430: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11431: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11432: $type is Course (default) or Community.
1.988     raeburn  11433: If $forcedefault evaluates to true, text returned will be default 
                   11434: text for $type. Otherwise, if this is a course, the text returned 
                   11435: will be a custom name for the role (if defined in the course's 
                   11436: environment).  If no custom name is defined the default is returned.
                   11437:    
1.832     raeburn  11438: =item *
                   11439: 
1.935     raeburn  11440: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11441: All arguments are optional. Returns a hash of a roles, either for
                   11442: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11443: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11444: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11445: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11446: For each key, value is set to colon-separated start and end times for
                   11447: the role.  If no username and domain are specified, will default to
1.934     raeburn  11448: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11449: of role statuses (active, future or previous), roles 
                   11450: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11451: to restrict the list of roles reported. If no array ref is 
                   11452: provided for types, will default to return only active roles.
1.834     albertel 11453: 
1.243     albertel 11454: =back
                   11455: 
                   11456: =head2 User Modification
                   11457: 
                   11458: =over 4
                   11459: 
                   11460: =item *
                   11461: 
1.957     raeburn  11462: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11463: user for the level given by URL.  Optional start and end dates (leave empty
                   11464: string or zero for "no date")
1.191     harris41 11465: 
                   11466: =item *
                   11467: 
1.243     albertel 11468: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11469: change a users, password, possible return values are: ok,
                   11470: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11471: refused
1.191     harris41 11472: 
                   11473: =item *
                   11474: 
1.243     albertel 11475: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11476: 
                   11477: =item *
                   11478: 
1.1058    raeburn  11479: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11480:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11481: 
                   11482: will update user information (firstname,middlename,lastname,generation,
                   11483: permanentemail), and if forceid is true, student/employee ID also.
                   11484: A user's institutional affiliation(s) can also be updated.
                   11485: User information fields will not be overwritten with empty entries 
                   11486: unless the field is included in the $candelete array reference.
                   11487: This array is included when a single user is modified via "Manage Users",
                   11488: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11489: 
                   11490: =item *
                   11491: 
1.286     matthew  11492: modifystudent
                   11493: 
1.957     raeburn  11494: modify a student's enrollment and identification information.
1.286     matthew  11495: The course id is resolved based on the current users environment.  
                   11496: This means the envoking user must be a course coordinator or otherwise
                   11497: associated with a course.
                   11498: 
1.297     matthew  11499: This call is essentially a wrapper for lonnet::modifyuser and
                   11500: lonnet::modify_student_enrollment
1.286     matthew  11501: 
                   11502: Inputs: 
                   11503: 
                   11504: =over 4
                   11505: 
1.957     raeburn  11506: =item B<$udom> Student's loncapa domain
1.286     matthew  11507: 
1.957     raeburn  11508: =item B<$uname> Student's loncapa login name
1.286     matthew  11509: 
1.964     bisitz   11510: =item B<$uid> Student/Employee ID
1.286     matthew  11511: 
1.957     raeburn  11512: =item B<$umode> Student's authentication mode
1.286     matthew  11513: 
1.957     raeburn  11514: =item B<$upass> Student's password
1.286     matthew  11515: 
1.957     raeburn  11516: =item B<$first> Student's first name
1.286     matthew  11517: 
1.957     raeburn  11518: =item B<$middle> Student's middle name
1.286     matthew  11519: 
1.957     raeburn  11520: =item B<$last> Student's last name
1.286     matthew  11521: 
1.957     raeburn  11522: =item B<$gene> Student's generation
1.286     matthew  11523: 
1.957     raeburn  11524: =item B<$usec> Student's section in course
1.286     matthew  11525: 
                   11526: =item B<$end> Unix time of the roles expiration
                   11527: 
                   11528: =item B<$start> Unix time of the roles start date
                   11529: 
                   11530: =item B<$forceid> If defined, allow $uid to be changed
                   11531: 
                   11532: =item B<$desiredhome> server to use as home server for student
                   11533: 
1.957     raeburn  11534: =item B<$email> Student's permanent e-mail address
                   11535: 
                   11536: =item B<$type> Type of enrollment (auto or manual)
                   11537: 
1.963     raeburn  11538: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11539: 
                   11540: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11541: 
1.963     raeburn  11542: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11543: 
1.963     raeburn  11544: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11545: 
1.963     raeburn  11546: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11547: 
1.286     matthew  11548: =back
1.297     matthew  11549: 
                   11550: =item *
                   11551: 
                   11552: modify_student_enrollment
                   11553: 
                   11554: Change a students enrollment status in a class.  The environment variable
                   11555: 'role.request.course' must be defined for this function to proceed.
                   11556: 
                   11557: Inputs:
                   11558: 
                   11559: =over 4
                   11560: 
                   11561: =item $udom, students domain
                   11562: 
                   11563: =item $uname, students name
                   11564: 
                   11565: =item $uid, students user id
                   11566: 
                   11567: =item $first, students first name
                   11568: 
                   11569: =item $middle
                   11570: 
                   11571: =item $last
                   11572: 
                   11573: =item $gene
                   11574: 
                   11575: =item $usec
                   11576: 
                   11577: =item $end
                   11578: 
                   11579: =item $start
                   11580: 
1.957     raeburn  11581: =item $type
                   11582: 
                   11583: =item $locktype
                   11584: 
                   11585: =item $cid
                   11586: 
                   11587: =item $selfenroll
                   11588: 
                   11589: =item $context
                   11590: 
1.297     matthew  11591: =back
                   11592: 
1.191     harris41 11593: 
                   11594: =item *
                   11595: 
1.243     albertel 11596: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11597: custom role; give a custom role to a user for the level given by URL.  Specify
                   11598: name and domain of role author, and role name
1.191     harris41 11599: 
                   11600: =item *
                   11601: 
1.243     albertel 11602: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11603: 
                   11604: =item *
                   11605: 
1.243     albertel 11606: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11607: 
                   11608: =back
                   11609: 
                   11610: =head2 Course Infomation
                   11611: 
                   11612: =over 4
1.191     harris41 11613: 
                   11614: =item *
                   11615: 
1.1118    foxr     11616: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11617: specified course id, including all environment settings for the
                   11618: course, the description of the course will be in the hash under the
                   11619: key 'description'
1.191     harris41 11620: 
1.1118    foxr     11621: $options is an optional parameter that if supplied is a hash reference that controls
                   11622: what how this function works.  It has the following key/values:
                   11623: 
                   11624: =over 4
                   11625: 
                   11626: =item freshen_cache
                   11627: 
                   11628: If defined, and the environment cache for the course is valid, it is 
                   11629: returned in the returned hash.
                   11630: 
                   11631: =item one_time
                   11632: 
                   11633: If defined, the last cache time is set to _now_
                   11634: 
                   11635: =item user
                   11636: 
                   11637: If defined, the supplied username is used instead of the current user.
                   11638: 
                   11639: 
                   11640: =back
                   11641: 
1.191     harris41 11642: =item *
                   11643: 
1.624     albertel 11644: resdata($name,$domain,$type,@which) : request for current parameter
                   11645: setting for a specific $type, where $type is either 'course' or 'user',
                   11646: @what should be a list of parameters to ask about. This routine caches
                   11647: answers for 5 minutes.
1.243     albertel 11648: 
1.877     foxr     11649: =item *
                   11650: 
                   11651: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11652: data base, returning a hash that is keyed by the resource name and has
                   11653: values that are the resource value.  I believe that the timestamps and
                   11654: versions are also returned.
                   11655: 
                   11656: 
1.243     albertel 11657: =back
                   11658: 
                   11659: =head2 Course Modification
                   11660: 
                   11661: =over 4
1.191     harris41 11662: 
                   11663: =item *
                   11664: 
1.243     albertel 11665: writecoursepref($courseid,%prefs) : write preferences (environment
                   11666: database) for a course
1.191     harris41 11667: 
                   11668: =item *
                   11669: 
1.1011    raeburn  11670: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11671: 
                   11672: =item *
                   11673: 
1.1038    raeburn  11674: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11675: 
                   11676: =back
                   11677: 
                   11678: =head2 Resource Subroutines
                   11679: 
                   11680: =over 4
1.191     harris41 11681: 
                   11682: =item *
                   11683: 
1.243     albertel 11684: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11685: 
                   11686: =item *
                   11687: 
1.243     albertel 11688: repcopy($filename) : subscribes to the requested file, and attempts to
                   11689: replicate from the owning library server, Might return
1.607     raeburn  11690: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11691: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11692: resource. Expects the local filesystem pathname
                   11693: (/home/httpd/html/res/....)
                   11694: 
                   11695: =back
                   11696: 
                   11697: =head2 Resource Information
                   11698: 
                   11699: =over 4
1.191     harris41 11700: 
                   11701: =item *
                   11702: 
1.243     albertel 11703: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11704: a vairety of different possible values, $varname should be a request
                   11705: string, and the other parameters can be used to specify who and what
                   11706: one is asking about.
                   11707: 
                   11708: Possible values for $varname are environment.lastname (or other item
                   11709: from the envirnment hash), user.name (or someother aspect about the
                   11710: user), resource.0.maxtries (or some other part and parameter of a
                   11711: resource)
1.204     albertel 11712: 
                   11713: =item *
                   11714: 
1.243     albertel 11715: directcondval($number) : get current value of a condition; reads from a state
                   11716: string
1.204     albertel 11717: 
                   11718: =item *
                   11719: 
1.243     albertel 11720: condval($condidx) : value of condition index based on state
1.204     albertel 11721: 
                   11722: =item *
                   11723: 
1.243     albertel 11724: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11725: resource's metadata, $what should be either a specific key, or either
                   11726: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11727: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11728: 
                   11729: this function automatically caches all requests
1.191     harris41 11730: 
                   11731: =item *
                   11732: 
1.243     albertel 11733: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11734: network of library servers; returns file handle of where SQL and regex results
                   11735: will be stored for query
1.191     harris41 11736: 
                   11737: =item *
                   11738: 
1.243     albertel 11739: symbread($filename) : return symbolic list entry (filename argument optional);
                   11740: returns the data handle
1.191     harris41 11741: 
                   11742: =item *
                   11743: 
1.243     albertel 11744: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11745: a possible symb for the URL in $thisfn, and if is an encryypted
                   11746: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11747: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11748: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11749: 
1.191     harris41 11750: 
                   11751: =item *
                   11752: 
1.243     albertel 11753: symbclean($symb) : removes versions numbers from a symb, returns the
                   11754: cleaned symb
1.191     harris41 11755: 
                   11756: =item *
                   11757: 
1.243     albertel 11758: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11759: course map, user must be in a course for it to work.
1.191     harris41 11760: 
                   11761: =item *
                   11762: 
1.243     albertel 11763: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11764: 
                   11765: =item *
                   11766: 
1.243     albertel 11767: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11768: a random seed, all arguments are optional, if they aren't sent it uses the
                   11769: environment to derive them. Note: if symb isn't sent and it can't get one
                   11770: from &symbread it will use the current time as its return value
1.191     harris41 11771: 
                   11772: =item *
                   11773: 
1.243     albertel 11774: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11775: unfakeable, receipt
1.191     harris41 11776: 
                   11777: =item *
                   11778: 
1.620     albertel 11779: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11780: 
                   11781: =item *
                   11782: 
1.243     albertel 11783: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11784: 
                   11785: =item *
                   11786: 
1.243     albertel 11787: 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 11788: 
                   11789: =item *
                   11790: 
1.243     albertel 11791: 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 11792: 
                   11793: =item *
                   11794: 
1.243     albertel 11795: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11796: 
                   11797: =item *
                   11798: 
1.243     albertel 11799: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11800: forcing spreadsheet to reevaluate the resource scores next time.
                   11801: 
                   11802: =back
                   11803: 
                   11804: =head2 Storing/Retreiving Data
                   11805: 
                   11806: =over 4
1.191     harris41 11807: 
                   11808: =item *
                   11809: 
1.243     albertel 11810: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11811: for this url; hashref needs to be given and should be a \%hashname; the
                   11812: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11813: be derived from the env
1.191     harris41 11814: 
                   11815: =item *
                   11816: 
1.243     albertel 11817: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11818: uses critical subroutine
1.191     harris41 11819: 
                   11820: =item *
                   11821: 
1.243     albertel 11822: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11823: all args are optional
1.191     harris41 11824: 
                   11825: =item *
                   11826: 
1.717     albertel 11827: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11828: dumps the complete (or key matching regexp) namespace into a hash
                   11829: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11830: normally &store()ed into
                   11831: 
                   11832: $range should be either an integer '100' (give me the first 100
                   11833:                                            matching records)
                   11834:               or be  two integers sperated by a - with no spaces
                   11835:                  '30-50' (give me the 30th through the 50th matching
                   11836:                           records)
                   11837: 
                   11838: 
                   11839: =item *
                   11840: 
                   11841: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11842: replaces a &store() version of data with a replacement set of data
                   11843: for a particular resource in a namespace passed in the $storehash hash 
                   11844: reference
                   11845: 
                   11846: =item *
                   11847: 
1.243     albertel 11848: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11849: works very similar to store/cstore, but all data is stored in a
                   11850: temporary location and can be reset using tmpreset, $storehash should
                   11851: be a hash reference, returns nothing on success
1.191     harris41 11852: 
                   11853: =item *
                   11854: 
1.243     albertel 11855: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11856: similar to restore, but all data is stored in a temporary location and
                   11857: can be reset using tmpreset. Returns a hash of values on success,
                   11858: error string otherwise.
1.191     harris41 11859: 
                   11860: =item *
                   11861: 
1.243     albertel 11862: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11863: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11864: 
                   11865: =item *
                   11866: 
1.243     albertel 11867: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11868: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11869: 
                   11870: =item *
                   11871: 
1.243     albertel 11872: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11873: namesp ($udom and $uname are optional)
1.191     harris41 11874: 
                   11875: =item *
                   11876: 
1.702     albertel 11877: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11878: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11879: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11880: 
1.702     albertel 11881: $range should be either an integer '100' (give me the first 100
                   11882:                                            matching records)
                   11883:               or be  two integers sperated by a - with no spaces
                   11884:                  '30-50' (give me the 30th through the 50th matching
                   11885:                           records)
1.449     matthew  11886: =item *
                   11887: 
                   11888: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11889: $store can be a scalar, an array reference, or if the amount to be 
                   11890: incremented is > 1, a hash reference.
                   11891: 
                   11892: ($udom and $uname are optional)
1.191     harris41 11893: 
                   11894: =item *
                   11895: 
1.243     albertel 11896: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11897: ($udom and $uname are optional)
1.191     harris41 11898: 
                   11899: =item *
                   11900: 
1.243     albertel 11901: cput($namespace,$storehash,$udom,$uname) : critical put
                   11902: ($udom and $uname are optional)
1.191     harris41 11903: 
                   11904: =item *
                   11905: 
1.748     albertel 11906: newput($namespace,$storehash,$udom,$uname) :
                   11907: 
                   11908: Attempts to store the items in the $storehash, but only if they don't
                   11909: currently exist, if this succeeds you can be certain that you have 
                   11910: successfully created a new key value pair in the $namespace db.
                   11911: 
                   11912: 
                   11913: Args:
                   11914:  $namespace: name of database to store values to
                   11915:  $storehash: hashref to store to the db
                   11916:  $udom: (optional) domain of user containing the db
                   11917:  $uname: (optional) name of user caontaining the db
                   11918: 
                   11919: Returns:
                   11920:  'ok' -> succeeded in storing all keys of $storehash
                   11921:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11922:                         least <key> already existed in the db (other
                   11923:                         requested keys may also already exist)
1.967     bisitz   11924:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11925:  'con_lost' -> unable to contact request server
                   11926:  'refused' -> action was not allowed by remote machine
                   11927: 
                   11928: 
                   11929: =item *
                   11930: 
1.243     albertel 11931: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11932: reference filled in from namesp (encrypts the return communication)
                   11933: ($udom and $uname are optional)
1.191     harris41 11934: 
                   11935: =item *
                   11936: 
1.243     albertel 11937: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11938: critical subroutine
                   11939: 
1.806     raeburn  11940: =item *
                   11941: 
1.860     raeburn  11942: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11943: array reference filled in from namespace found in domain level on either
                   11944: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11945: 
                   11946: =item *
                   11947: 
1.860     raeburn  11948: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11949: domain level either on specified domain server ($uhome) or primary domain 
                   11950: server ($udom and $uhome are optional)
1.806     raeburn  11951: 
1.943     raeburn  11952: =item * 
                   11953: 
                   11954: get_domain_defaults($target_domain) : returns hash with defaults for
                   11955: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11956: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11957: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11958: Values are retrieved from cache (if current), or from domain's configuration.db
                   11959: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11960: or lonTabs/domain.tab. 
                   11961: 
                   11962: %domdefaults = &get_auth_defaults($target_domain);
                   11963: 
1.243     albertel 11964: =back
                   11965: 
                   11966: =head2 Network Status Functions
                   11967: 
                   11968: =over 4
1.191     harris41 11969: 
                   11970: =item *
                   11971: 
1.1137    raeburn  11972: dirlist() : return directory list based on URI (first arg).
                   11973: 
                   11974: Inputs: 1 required, 5 optional.
                   11975: 
                   11976: =over
                   11977: 
                   11978: =item 
                   11979: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   11980: 
                   11981: =item
                   11982: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   11983: 
                   11984: =item
                   11985: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   11986: 
                   11987: =item
                   11988: $getpropath - boolean: 1 if prepend path using &propath(). 
                   11989: 
                   11990: =item
                   11991: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   11992: 
                   11993: =item 
                   11994: $alternateRoot - path to prepend in place of path from $uri.
                   11995: 
                   11996: =back
                   11997: 
                   11998: Returns: Array of up to two items.
                   11999: 
                   12000: =over
                   12001: 
                   12002: a reference to an array of files/subdirectories
                   12003: 
                   12004: =over
                   12005: 
                   12006: Each element in the array of files/subdirectories is a & separated list of
                   12007: item name and the result of running stat on the item.  If dirlist was requested
                   12008: for a file instead of a directory, the item name will be ''. For a directory 
                   12009: listing, if the item is a metadata file, the element will end &N&M 
                   12010: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12011: default copyright set (1).  
                   12012: 
                   12013: =back
                   12014: 
                   12015: a scalar containing error condition (if encountered).
                   12016: 
                   12017: =over
                   12018: 
                   12019: =item 
                   12020: no_host (no homeserver identified for $username:$domain).
                   12021: 
                   12022: =item 
                   12023: no_such_host (server contacted for listing not identified as valid host).
                   12024: 
                   12025: =item 
                   12026: con_lost (connection to remote server failed).
                   12027: 
                   12028: =item 
                   12029: refused (invalid $username:$domain received on lond side).
                   12030: 
                   12031: =item 
                   12032: no_such_dir (directory at specified path on lond side does not exist). 
                   12033: 
                   12034: =item 
                   12035: empty (directory at specified path on lond side is empty).
                   12036: 
                   12037: =over
                   12038: 
                   12039: This is currently not encountered because the &ls3, &ls2, 
                   12040: &ls (_handler) routines on the lond side do not filter out
                   12041: . and .. from a directory listing. 
                   12042: 
                   12043: =back
                   12044: 
                   12045: =back
                   12046: 
                   12047: =back
1.191     harris41 12048: 
                   12049: =item *
                   12050: 
1.243     albertel 12051: spareserver() : find server with least workload from spare.tab
                   12052: 
1.986     foxr     12053: 
                   12054: =item *
                   12055: 
                   12056: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12057: if there is no corresponding loncapa host.
                   12058: 
1.243     albertel 12059: =back
                   12060: 
1.986     foxr     12061: 
1.243     albertel 12062: =head2 Apache Request
                   12063: 
                   12064: =over 4
1.191     harris41 12065: 
                   12066: =item *
                   12067: 
1.243     albertel 12068: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12069: localhost, posts hash
                   12070: 
                   12071: =back
                   12072: 
                   12073: =head2 Data to String to Data
                   12074: 
                   12075: =over 4
1.191     harris41 12076: 
                   12077: =item *
                   12078: 
1.243     albertel 12079: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12080: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12081: 
                   12082: =item *
                   12083: 
1.243     albertel 12084: hashref2str($hashref) : convert a hashref into a string complete with
                   12085: escaping and '=' and '&' separators, supports elements that are
                   12086: arrayrefs and hashrefs
1.191     harris41 12087: 
                   12088: =item *
                   12089: 
1.243     albertel 12090: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12091: with escaping and '&' separators, supports elements that are arrayrefs
                   12092: and hashrefs
1.191     harris41 12093: 
                   12094: =item *
                   12095: 
1.243     albertel 12096: str2hash($string) : convert string to hash using unescaping and
                   12097: splitting on '=' and '&', supports elements that are arrayrefs and
                   12098: hashrefs
1.191     harris41 12099: 
                   12100: =item *
                   12101: 
1.243     albertel 12102: str2array($string) : convert string to hash using unescaping and
                   12103: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12104: 
                   12105: =back
                   12106: 
                   12107: =head2 Logging Routines
                   12108: 
                   12109: 
                   12110: These routines allow one to make log messages in the lonnet.log and
                   12111: lonnet.perm logfiles.
1.191     harris41 12112: 
1.1119    foxr     12113: =over 4
                   12114: 
1.191     harris41 12115: =item *
                   12116: 
1.243     albertel 12117: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12118: 
                   12119: =item *
                   12120: 
1.243     albertel 12121: logthis() : append message to the normal lonnet.log file, it gets
                   12122: preiodically rolled over and deleted.
1.191     harris41 12123: 
                   12124: =item *
                   12125: 
1.243     albertel 12126: logperm() : append a permanent message to lonnet.perm.log, this log
                   12127: file never gets deleted by any automated portion of the system, only
                   12128: messages of critical importance should go in here.
                   12129: 
1.1119    foxr     12130: 
1.243     albertel 12131: =back
                   12132: 
                   12133: =head2 General File Helper Routines
                   12134: 
                   12135: =over 4
1.191     harris41 12136: 
                   12137: =item *
                   12138: 
1.481     raeburn  12139: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12140: (a) files in /uploaded
                   12141:   (i) If a local copy of the file exists - 
                   12142:       compares modification date of local copy with last-modified date for 
                   12143:       definitive version stored on home server for course. If local copy is 
                   12144:       stale, requests a new version from the home server and stores it. 
                   12145:       If the original has been removed from the home server, then local copy 
                   12146:       is unlinked.
                   12147:   (ii) If local copy does not exist -
                   12148:       requests the file from the home server and stores it. 
                   12149:   
                   12150:   If $caller is 'uploadrep':  
                   12151:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12152:     for request for files originally uploaded via DOCS. 
                   12153:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12154:   
                   12155:   Otherwise:
                   12156:      This indicates a call from the content generation phase of the request.
                   12157:      -  returns the entire contents of the file or -1.
                   12158:      
                   12159: (b) files in /res
                   12160:    - returns the entire contents of a file or -1; 
                   12161:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12162: 
1.712     albertel 12163: 
                   12164: =item *
                   12165: 
                   12166: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12167:                   reference
                   12168: 
                   12169: returns either a stat() list of data about the file or an empty list
                   12170: if the file doesn't exist or couldn't find out about it (connection
                   12171: problems or user unknown)
                   12172: 
1.191     harris41 12173: =item *
                   12174: 
1.243     albertel 12175: filelocation($dir,$file) : returns file system location of a file
                   12176: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12177: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12178: and a file of ../bob will become /a/bob)
1.191     harris41 12179: 
                   12180: =item *
                   12181: 
                   12182: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12183: filelocation except for hrefs
                   12184: 
                   12185: =item *
                   12186: 
                   12187: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12188: 
1.243     albertel 12189: =back
                   12190: 
1.608     albertel 12191: =head2 Usererfile file routines (/uploaded*)
                   12192: 
                   12193: =over 4
                   12194: 
                   12195: =item *
                   12196: 
                   12197: userfileupload(): main rotine for putting a file in a user or course's
                   12198:                   filespace, arguments are,
                   12199: 
1.620     albertel 12200:  formname - required - this is the name of the element in $env where the
1.608     albertel 12201:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12202:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12203:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12204:  context - if coursedoc, store the file in the course of the active role
                   12205:              of the current user; 
                   12206:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12207:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12208:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12209:          if undefined, it will be placed in "unknown"
                   12210: 
                   12211:  (This routine calls clean_filename() to remove any dangerous
                   12212:  characters from the filename, and then calls finuserfileupload() to
                   12213:  complete the transaction)
                   12214: 
                   12215:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12216:  and /adm/notfound.html if unsuccessful
                   12217: 
                   12218: =item *
                   12219: 
                   12220: clean_filename(): routine for cleaing a filename up for storage in
                   12221:                  userfile space, argument is:
                   12222: 
                   12223:  filename - proposed filename
                   12224: 
                   12225: returns: the new clean filename
                   12226: 
                   12227: =item *
                   12228: 
1.1090    raeburn  12229: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12230: userspace, probably shouldn't be called directly
                   12231: 
                   12232:   docuname: username or courseid of destination for the file
                   12233:   docudom: domain of user/course of destination for the file
                   12234:   formname: same as for userfileupload()
1.1090    raeburn  12235:   fname: filename (including subdirectories) for the file
                   12236:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12237:   allfiles: reference to hash used to store objects found by parser
                   12238:   codebase: reference to hash used for codebases of java objects found by parser
                   12239:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12240:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12241:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12242:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12243:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12244:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12245:   mimetype: reference to scalar to accommodate mime type determined
                   12246:             from File::MMagic if $parser = parse.
1.608     albertel 12247: 
                   12248:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12249:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12250:  was 'overwrite').
                   12251:  
1.608     albertel 12252: 
                   12253: =item *
                   12254: 
                   12255: renameuserfile(): renames an existing userfile to a new name
                   12256: 
                   12257:   Args:
                   12258:    docuname: username or courseid of destination for the file
                   12259:    docudom: domain of user/course of destination for the file
                   12260:    old: current file name (including any subdirs under userfiles)
                   12261:    new: desired file name (including any subdirs under userfiles)
                   12262: 
                   12263: =item *
                   12264: 
                   12265: mkdiruserfile(): creates a directory is a userfiles dir
                   12266: 
                   12267:   Args:
                   12268:    docuname: username or courseid of destination for the file
                   12269:    docudom: domain of user/course of destination for the file
                   12270:    dir: dir to create (including any subdirs under userfiles)
                   12271: 
                   12272: =item *
                   12273: 
                   12274: removeuserfile(): removes a file that exists in userfiles
                   12275: 
                   12276:   Args:
                   12277:    docuname: username or courseid of destination for the file
                   12278:    docudom: domain of user/course of destination for the file
                   12279:    fname: filname to delete (including any subdirs under userfiles)
                   12280: 
                   12281: =item *
                   12282: 
                   12283: removeuploadedurl(): convience function for removeuserfile()
                   12284: 
                   12285:   Args:
                   12286:    url:  a full /uploaded/... url to delete
                   12287: 
1.747     albertel 12288: =item * 
                   12289: 
                   12290: get_portfile_permissions():
                   12291:   Args:
                   12292:     domain: domain of user or course contain the portfolio files
                   12293:     user: name of user or num of course contain the portfolio files
                   12294:   Returns:
                   12295:     hashref of a dump of the proper file_permissions.db
                   12296:    
                   12297: 
                   12298: =item * 
                   12299: 
                   12300: get_access_controls():
                   12301: 
                   12302: Args:
                   12303:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12304:   group: (optional) the group you want the files associated with
                   12305:   file: (optional) the file you want access info on
                   12306: 
                   12307: Returns:
1.749     raeburn  12308:     a hash (keys are file names) of hashes containing
                   12309:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12310:         values are XML containing access control settings (see below) 
1.747     albertel 12311: 
                   12312: Internal notes:
                   12313: 
1.749     raeburn  12314:  access controls are stored in file_permissions.db as key=value pairs.
                   12315:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12316:         where scope -> public,guest,course,group,domains or users.
                   12317:               end -> UNIX time for end of access (0 -> no end date)
                   12318:               start -> UNIX time for start of access
                   12319: 
                   12320:     value -> XML description of access control
                   12321:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12322:             <start></start>
                   12323:             <end></end>
                   12324: 
                   12325:             <password></password>  for scope type = guest
                   12326: 
                   12327:             <domain></domain>     for scope type = course or group
                   12328:             <number></number>
                   12329:             <roles id="">
                   12330:              <role></role>
                   12331:              <access></access>
                   12332:              <section></section>
                   12333:              <group></group>
                   12334:             </roles>
                   12335: 
                   12336:             <dom></dom>         for scope type = domains
                   12337: 
                   12338:             <users>             for scope type = users
                   12339:              <user>
                   12340:               <uname></uname>
                   12341:               <udom></udom>
                   12342:              </user>
                   12343:             </users>
                   12344:            </scope> 
                   12345:               
                   12346:  Access data is also aggregated for each file in an additional key=value pair:
                   12347:  key -> path to file/file_name\0accesscontrol 
                   12348:  value -> reference to hash
                   12349:           hash contains key = value pairs
                   12350:           where key = uniqueID:scope_end_start
                   12351:                 value = UNIX time record was last updated
                   12352: 
                   12353:           Used to improve speed of look-ups of access controls for each file.  
                   12354:  
                   12355:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12356: 
                   12357: modify_access_controls():
                   12358: 
                   12359: Modifies access controls for a portfolio file
                   12360: Args
                   12361: 1. file name
                   12362: 2. reference to hash of required changes,
                   12363: 3. domain
                   12364: 4. username
                   12365:   where domain,username are the domain of the portfolio owner 
                   12366:   (either a user or a course) 
                   12367: 
                   12368: Returns:
                   12369: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12370: 2. result of deletions ('ok' or 'error', with error message).
                   12371: 3. reference to hash of any new or updated access controls.
                   12372: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12373:    key = integer (inbound ID)
                   12374:    value = uniqueID  
1.747     albertel 12375: 
1.608     albertel 12376: =back
                   12377: 
1.243     albertel 12378: =head2 HTTP Helper Routines
                   12379: 
                   12380: =over 4
                   12381: 
1.191     harris41 12382: =item *
                   12383: 
                   12384: escape() : unpack non-word characters into CGI-compatible hex codes
                   12385: 
                   12386: =item *
                   12387: 
                   12388: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12389: 
1.243     albertel 12390: =back
                   12391: 
                   12392: =head1 PRIVATE SUBROUTINES
                   12393: 
                   12394: =head2 Underlying communication routines (Shouldn't call)
                   12395: 
                   12396: =over 4
                   12397: 
                   12398: =item *
                   12399: 
                   12400: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12401: 
                   12402: =item *
                   12403: 
                   12404: reply() : uses subreply to send a message to remote machine, logs all failures
                   12405: 
                   12406: =item *
                   12407: 
                   12408: critical() : passes a critical message to another server; if cannot
                   12409: get through then place message in connection buffer directory and
                   12410: returns con_delayed, if incapable of saving message, returns
                   12411: con_failed
                   12412: 
                   12413: =item *
                   12414: 
                   12415: reconlonc() : tries to reconnect lonc client processes.
                   12416: 
                   12417: =back
                   12418: 
                   12419: =head2 Resource Access Logging
                   12420: 
                   12421: =over 4
                   12422: 
                   12423: =item *
                   12424: 
                   12425: flushcourselogs() : flush (save) buffer logs and access logs
                   12426: 
                   12427: =item *
                   12428: 
                   12429: courselog($what) : save message for course in hash
                   12430: 
                   12431: =item *
                   12432: 
                   12433: courseacclog($what) : save message for course using &courselog().  Perform
                   12434: special processing for specific resource types (problems, exams, quizzes, etc).
                   12435: 
1.191     harris41 12436: =item *
                   12437: 
                   12438: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12439: as a PerlChildExitHandler
1.243     albertel 12440: 
                   12441: =back
                   12442: 
                   12443: =head2 Other
                   12444: 
                   12445: =over 4
                   12446: 
                   12447: =item *
                   12448: 
                   12449: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12450: 
                   12451: =back
                   12452: 
                   12453: =cut
1.877     foxr     12454: 

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