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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1164  ! raeburn     4: # $Id: lonnet.pm,v 1.1163 2012/04/01 16:19:20 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.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'; }
1.1164  ! raeburn  2446:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  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 = ();
1.1164  ! raeburn  3036:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3037:     my %javafiles = (
                   3038:                       codebase => '',
                   3039:                       code => '',
                   3040:                       archive => ''
                   3041:                     );
                   3042:     my %mediafiles = (
                   3043:                       src => '',
                   3044:                       movie => '',
                   3045:                      );
1.648     raeburn  3046:     my $p;
                   3047:     if ($content) {
                   3048:         $p = HTML::LCParser->new($content);
                   3049:     } else {
1.961     raeburn  3050:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3051:     }
1.641     albertel 3052:     while (my $t=$p->get_token()) {
1.640     albertel 3053: 	if ($t->[0] eq 'S') {
                   3054: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3055: 	    push(@state, $tagname);
1.648     raeburn  3056:             if (lc($tagname) eq 'allow') {
                   3057:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3058:             }
1.640     albertel 3059: 	    if (lc($tagname) eq 'img') {
                   3060: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3061: 	    }
1.886     albertel 3062: 	    if (lc($tagname) eq 'a') {
                   3063: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3064: 	    }
1.645     raeburn  3065:             if (lc($tagname) eq 'script') {
1.1164  ! raeburn  3066:                 my $src;
1.645     raeburn  3067:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3068:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3069:                 } else {
1.1164  ! raeburn  3070:                     if ($attr->{'src'} ne '') {
        !          3071:                         $src = $attr->{'src'};
        !          3072:                         &add_filetype($allfiles,$src,'src');
        !          3073:                     }
        !          3074:                 }
        !          3075:                 my $text = $p->get_trimmed_text();
        !          3076:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
        !          3077:                     my @swfargs = split(/,/,$1);
        !          3078:                     foreach my $item (@swfargs) {
        !          3079:                         $item =~ s/["']//g;
        !          3080:                         $item =~ s/^\s+//;
        !          3081:                         $item =~ s/\s+$//;
        !          3082:                     }
        !          3083:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
        !          3084:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
        !          3085:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
        !          3086:                         } else {
        !          3087:                             $related{$swfargs[0]} = [$swfargs[2]];
        !          3088:                         }
        !          3089:                     }
1.645     raeburn  3090:                 }
                   3091:             }
                   3092:             if (lc($tagname) eq 'link') {
                   3093:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3094:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3095:                 }
                   3096:             }
1.640     albertel 3097: 	    if (lc($tagname) eq 'object' ||
                   3098: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3099: 		foreach my $item (keys(%javafiles)) {
                   3100: 		    $javafiles{$item} = '';
                   3101: 		}
1.1164  ! raeburn  3102:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
        !          3103:                     $lastids{lc($tagname)} = $attr->{'id'};
        !          3104:                 }
1.640     albertel 3105: 	    }
                   3106: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3107: 		my $name = lc($attr->{'name'});
                   3108: 		foreach my $item (keys(%javafiles)) {
                   3109: 		    if ($name eq $item) {
                   3110: 			$javafiles{$item} = $attr->{'value'};
                   3111: 			last;
                   3112: 		    }
                   3113: 		}
1.1164  ! raeburn  3114:                 my $pathfrom;
1.640     albertel 3115: 		foreach my $item (keys(%mediafiles)) {
                   3116: 		    if ($name eq $item) {
1.1164  ! raeburn  3117:                         $pathfrom = $attr->{'value'};
        !          3118:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
        !          3119: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3120: 			last;
                   3121: 		    }
                   3122: 		}
1.1164  ! raeburn  3123:                 if ($name eq 'flashvars') {
        !          3124:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
        !          3125:                 }
        !          3126:                 if ($pathfrom ne '') {
        !          3127:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
        !          3128:                                          $pathfrom);
        !          3129:                 }
1.640     albertel 3130: 	    }
                   3131: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3132: 		foreach my $item (keys(%javafiles)) {
                   3133: 		    if ($attr->{$item}) {
                   3134: 			$javafiles{$item} = $attr->{$item};
                   3135: 			last;
                   3136: 		    }
                   3137: 		}
                   3138: 		foreach my $item (keys(%mediafiles)) {
                   3139: 		    if ($attr->{$item}) {
                   3140: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3141: 			last;
                   3142: 		    }
                   3143: 		}
1.1164  ! raeburn  3144:                 if (lc($tagname) eq 'embed') {
        !          3145:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
        !          3146:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
        !          3147:                                              $attr->{'src'});
        !          3148:                     }
        !          3149:                 }
1.640     albertel 3150: 	    }
1.1164  ! raeburn  3151:             if ($t->[4] =~ m{/>$}) {
        !          3152:                 pop(@state);  
        !          3153:             }
1.640     albertel 3154: 	} elsif ($t->[0] eq 'E') {
                   3155: 	    my ($tagname) = ($t->[1]);
                   3156: 	    if ($javafiles{'codebase'} ne '') {
                   3157: 		$javafiles{'codebase'} .= '/';
                   3158: 	    }  
                   3159: 	    if (lc($tagname) eq 'applet' ||
                   3160: 		lc($tagname) eq 'object' ||
                   3161: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3162: 		) {
                   3163: 		foreach my $item (keys(%javafiles)) {
                   3164: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3165: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3166: 			&add_filetype($allfiles,$file,$item);
                   3167: 		    }
                   3168: 		}
                   3169: 	    } 
                   3170: 	    pop @state;
                   3171: 	}
                   3172:     }
1.1164  ! raeburn  3173:     foreach my $id (sort(keys(%flashvars))) {
        !          3174:         if ($shockwave{$id} ne '') {
        !          3175:             my @pairs = split(/\&/,$flashvars{$id});
        !          3176:             foreach my $pair (@pairs) {
        !          3177:                 my ($key,$value) = split(/\=/,$pair);
        !          3178:                 if ($key eq 'thumb') {
        !          3179:                     &add_filetype($allfiles,$value,$key);
        !          3180:                 } elsif ($key eq 'content') {
        !          3181:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
        !          3182:                     my ($ext) = ($value =~ /\.([^.]+)$/);
        !          3183:                     if ($ext ne '') {
        !          3184:                         &add_filetype($allfiles,$path.$value,$ext);
        !          3185:                     }
        !          3186:                 }
        !          3187:             }
        !          3188:         }
        !          3189:     }
1.637     raeburn  3190:     return 'ok';
                   3191: }
                   3192: 
1.639     albertel 3193: sub add_filetype {
                   3194:     my ($allfiles,$file,$type)=@_;
                   3195:     if (exists($allfiles->{$file})) {
                   3196: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3197: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3198: 	}
                   3199:     } else {
                   3200: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3201:     }
                   3202: }
                   3203: 
1.1164  ! raeburn  3204: sub embedded_dependency {
        !          3205:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
        !          3206:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
        !          3207:         if (($identifier ne '') &&
        !          3208:             (ref($related->{$identifier}) eq 'ARRAY') &&
        !          3209:             ($pathfrom ne '')) {
        !          3210:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
        !          3211:             foreach my $dep (@{$related->{$identifier}}) {
        !          3212:                 &add_filetype($allfiles,$path.$dep,'object');
        !          3213:             }
        !          3214:         }
        !          3215:     }
        !          3216:     return;
        !          3217: }
        !          3218: 
1.493     albertel 3219: sub removeuploadedurl {
1.984     neumanie 3220:     my ($url)=@_;	
                   3221:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3222:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3223: }
                   3224: 
                   3225: sub removeuserfile {
                   3226:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3227:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3228:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3229:     if ($result eq 'ok') {	
1.798     raeburn  3230:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3231:             my $metafile = $fname.'.meta';
                   3232:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3233: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3234:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3235:             my $sqlresult = 
1.823     albertel 3236:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3237:                                         'portfolio_metadata',$group,
                   3238:                                         'delete');
1.798     raeburn  3239:         }
                   3240:     }
                   3241:     return $result;
1.257     www      3242: }
1.15      www      3243: 
1.530     albertel 3244: sub mkdiruserfile {
                   3245:     my ($docuname,$docudom,$dir)=@_;
                   3246:     my $home=&homeserver($docuname,$docudom);
                   3247:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3248: }
                   3249: 
1.531     albertel 3250: sub renameuserfile {
                   3251:     my ($docuname,$docudom,$old,$new)=@_;
                   3252:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3253:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3254:                         &escape("$old").':'.&escape("$new"),$home);
                   3255:     if ($result eq 'ok') {
                   3256:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3257:             my $oldmeta = $old.'.meta';
                   3258:             my $newmeta = $new.'.meta';
                   3259:             my $metaresult = 
                   3260:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3261: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3262:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3263:             my $sqlresult = 
1.823     albertel 3264:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3265:                                         'portfolio_metadata',$group,
                   3266:                                         'delete');
1.798     raeburn  3267:         }
                   3268:     }
                   3269:     return $result;
1.531     albertel 3270: }
                   3271: 
1.14      www      3272: # ------------------------------------------------------------------------- Log
                   3273: 
                   3274: sub log {
                   3275:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3276:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3277: }
                   3278: 
                   3279: # ------------------------------------------------------------------ Course Log
1.352     www      3280: #
                   3281: # This routine flushes several buffers of non-mission-critical nature
                   3282: #
1.157     www      3283: 
                   3284: sub flushcourselogs {
1.352     www      3285:     &logthis('Flushing log buffers');
                   3286: #
                   3287: # course logs
                   3288: # This is a log of all transactions in a course, which can be used
                   3289: # for data mining purposes
                   3290: #
                   3291: # It also collects the courseid database, which lists last transaction
                   3292: # times and course titles for all courseids
                   3293: #
                   3294:     my %courseidbuffer=();
1.921     raeburn  3295:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3296:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3297: 		          &escape($courselogs{$crsid}),
                   3298: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3299: 	    delete $courselogs{$crsid};
                   3300:         } else {
                   3301:             &logthis('Failed to flush log buffer for '.$crsid);
                   3302:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3303:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3304:                         " exceeded maximum size, deleting.</font>");
                   3305:                delete $courselogs{$crsid};
                   3306:             }
1.352     www      3307:         }
1.920     raeburn  3308:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3309:             'description' => $coursedescrbuf{$crsid},
                   3310:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3311:             'type'        => $coursetypebuf{$crsid},
                   3312:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3313:         };
1.191     harris41 3314:     }
1.352     www      3315: #
                   3316: # Write course id database (reverse lookup) to homeserver of courses 
                   3317: # Is used in pickcourse
                   3318: #
1.840     albertel 3319:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3320:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3321:                                     $courseidbuffer{$crs_home},
                   3322:                                     $crs_home,'timeonly');
1.352     www      3323:     }
                   3324: #
                   3325: # File accesses
                   3326: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3327: #
1.449     matthew  3328:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3329:         if ($entry =~ /___count$/) {
                   3330:             my ($dom,$name);
1.807     albertel 3331:             ($dom,$name,undef)=
1.811     albertel 3332: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3333:             if (! defined($dom) || $dom eq '' || 
                   3334:                 ! defined($name) || $name eq '') {
1.620     albertel 3335:                 my $cid = $env{'request.course.id'};
                   3336:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3337:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3338:             }
1.450     matthew  3339:             my $value = $accesshash{$entry};
                   3340:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3341:             my %temphash=($url => $value);
1.449     matthew  3342:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3343:             if ($result eq 'ok') {
                   3344:                 delete $accesshash{$entry};
                   3345:             }
                   3346:         } else {
1.811     albertel 3347:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3348:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3349:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3350:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3351:                 delete $accesshash{$entry};
                   3352:             }
1.185     www      3353:         }
1.191     harris41 3354:     }
1.352     www      3355: #
                   3356: # Roles
                   3357: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3358: #
1.800     albertel 3359:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3360:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3361: 	    split(/\:/,$entry);
                   3362:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3363:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3364:                 $rudom,$runame) eq 'ok') {
                   3365: 	    delete $userrolehash{$entry};
                   3366:         }
                   3367:     }
1.662     raeburn  3368: #
                   3369: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3370: #
                   3371:     my %domrolebuffer = ();
1.1000    raeburn  3372:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3373:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3374:         if ($domrolebuffer{$rudom}) {
                   3375:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3376:                       '='.&escape($domainrolehash{$entry});
                   3377:         } else {
                   3378:             $domrolebuffer{$rudom}.=&escape($entry).
                   3379:                       '='.&escape($domainrolehash{$entry});
                   3380:         }
                   3381:         delete $domainrolehash{$entry};
                   3382:     }
                   3383:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3384: 	my %servers = &get_servers($dom,'library');
                   3385: 	foreach my $tryserver (keys(%servers)) {
                   3386: 	    unless (&reply('domroleput:'.$dom.':'.
                   3387: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3388: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3389: 	    }
1.662     raeburn  3390:         }
                   3391:     }
1.186     www      3392:     $dumpcount++;
1.157     www      3393: }
                   3394: 
                   3395: sub courselog {
                   3396:     my $what=shift;
1.158     www      3397:     $what=time.':'.$what;
1.620     albertel 3398:     unless ($env{'request.course.id'}) { return ''; }
                   3399:     $coursedombuf{$env{'request.course.id'}}=
                   3400:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3401:     $coursenumbuf{$env{'request.course.id'}}=
                   3402:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3403:     $coursehombuf{$env{'request.course.id'}}=
                   3404:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3405:     $coursedescrbuf{$env{'request.course.id'}}=
                   3406:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3407:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3408:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3409:     $courseownerbuf{$env{'request.course.id'}}=
                   3410:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3411:     $coursetypebuf{$env{'request.course.id'}}=
                   3412:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3413:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3414: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3415:     } else {
1.620     albertel 3416: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3417:     }
1.620     albertel 3418:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3419: 	&flushcourselogs();
                   3420:     }
1.158     www      3421: }
                   3422: 
                   3423: sub courseacclog {
                   3424:     my $fnsymb=shift;
1.620     albertel 3425:     unless ($env{'request.course.id'}) { return ''; }
                   3426:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3427:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3428:         $what.=':POST';
1.583     matthew  3429:         # FIXME: Probably ought to escape things....
1.800     albertel 3430: 	foreach my $key (keys(%env)) {
                   3431:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3432:                 my $formitem = $1;
                   3433:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3434:                     $what.=':'.$formitem.'='.$env{$key};
                   3435:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3436:                     $what.=':'.$formitem.'='.$env{$key};
                   3437:                 }
1.158     www      3438:             }
1.191     harris41 3439:         }
1.583     matthew  3440:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3441:         # FIXME: We should not be depending on a form parameter that someone
                   3442:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3443:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3444:             $what.= ':POST';
                   3445:             # FIXME: Probably ought to escape things....
                   3446:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3447:                                  'crsdiscuss') {
1.620     albertel 3448:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3449:             }
                   3450:         }
1.158     www      3451:     }
                   3452:     &courselog($what);
1.149     www      3453: }
                   3454: 
1.185     www      3455: sub countacc {
                   3456:     my $url=&declutter(shift);
1.458     matthew  3457:     return if (! defined($url) || $url eq '');
1.620     albertel 3458:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3459: #
                   3460: # Mark that this url was used in this course
                   3461: #
1.620     albertel 3462:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3463: #
                   3464: # Increase the access count for this resource in this child process
                   3465: #
1.281     www      3466:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3467:     $accesshash{$key}++;
1.185     www      3468: }
1.349     www      3469: 
1.361     www      3470: sub linklog {
                   3471:     my ($from,$to)=@_;
                   3472:     $from=&declutter($from);
                   3473:     $to=&declutter($to);
                   3474:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3475:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3476: }
1.1160    www      3477: 
                   3478: sub statslog {
                   3479:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3480:     if ($users<2) { return; }
                   3481:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3482:             'course'       => $env{'request.course.id'},
                   3483:             'sections'     => '"all"',
                   3484:             'num_students' => $users,
                   3485:             'part'         => $part,
                   3486:             'symb'         => $symb,
                   3487:             'mean_tries'   => $av_attempts,
                   3488:             'deg_of_diff'  => $degdiff});
                   3489:     foreach my $key (keys(%dynstore)) {
                   3490:         $accesshash{$key}=$dynstore{$key};
                   3491:     }
                   3492: }
1.361     www      3493:   
1.349     www      3494: sub userrolelog {
                   3495:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3496:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3497:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3498:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3499:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3500:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3501:        $userrolehash
                   3502:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3503:                     =$tend.':'.$tstart;
1.662     raeburn  3504:     }
1.898     albertel 3505:     if (($env{'request.role'} =~ /dc\./) &&
                   3506: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3507: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3508: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3509:          ($trole=~/^co/))) {
1.898     albertel 3510:        $userrolehash
                   3511:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3512:                     =$tend.':'.$tstart;
                   3513:     }
1.662     raeburn  3514:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3515:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3516:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3517:         ($trole=~/^sc/)) {
                   3518:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3519:        $domainrolehash
                   3520:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3521:                     = $tend.':'.$tstart;
                   3522:     }
1.351     www      3523: }
                   3524: 
1.957     raeburn  3525: sub courserolelog {
                   3526:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3527:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3528:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3529:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3530:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3531:         ($trole eq 'co')) {
1.957     raeburn  3532:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3533:             my $cdom = $1;
                   3534:             my $cnum = $2;
                   3535:             my $sec = $3;
                   3536:             my $namespace = 'rolelog';
                   3537:             my %storehash = (
                   3538:                                role    => $trole,
                   3539:                                start   => $tstart,
                   3540:                                end     => $tend,
                   3541:                                selfenroll => $selfenroll,
                   3542:                                context    => $context,
                   3543:                             );
                   3544:             if ($trole eq 'gr') {
                   3545:                 $namespace = 'groupslog';
                   3546:                 $storehash{'group'} = $sec;
                   3547:             } else {
                   3548:                 $storehash{'section'} = $sec;
                   3549:             }
                   3550:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3551:             if (($trole ne 'st') || ($sec ne '')) {
                   3552:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3553:             }
1.957     raeburn  3554:         }
                   3555:     }
                   3556:     return;
                   3557: }
                   3558: 
1.351     www      3559: sub get_course_adv_roles {
1.948     raeburn  3560:     my ($cid,$codes) = @_;
1.620     albertel 3561:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3562:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3563:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3564:     my %nothide=();
1.800     albertel 3565:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3566:         if ($user !~ /:/) {
                   3567: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3568:         } else {
                   3569:             $nothide{$user}=1;
                   3570:         }
1.470     www      3571:     }
1.351     www      3572:     my %returnhash=();
                   3573:     my %dumphash=
                   3574:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3575:     my $now=time;
1.997     raeburn  3576:     my %privileged;
1.1000    raeburn  3577:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3578: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3579:         if (($tstart) && ($tstart<0)) { next; }
                   3580:         if (($tend) && ($tend<$now)) { next; }
                   3581:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3582:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3583: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3584:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3585:             my %dompersonnel =
1.998     raeburn  3586:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3587:             $privileged{$domain} = {};
                   3588:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3589:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3590:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3591:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3592:                         $privileged{$udom}{$uname} = 1;
                   3593:                     }
                   3594:                 }
                   3595:             }
                   3596:         }
                   3597:         if ((exists($privileged{$domain}{$username})) && 
                   3598:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3599: 	if ($role eq 'cr') { next; }
1.948     raeburn  3600:         if ($codes) {
                   3601:             if ($section) { $role .= ':'.$section; }
                   3602:             if ($returnhash{$role}) {
                   3603:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3604:             } else {
                   3605:                 $returnhash{$role}=$username.':'.$domain;
                   3606:             }
1.351     www      3607:         } else {
1.988     raeburn  3608:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3609:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3610:             if ($returnhash{$key}) {
                   3611: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3612:             } else {
                   3613:                 $returnhash{$key}=$username.':'.$domain;
                   3614:             }
1.351     www      3615:         }
1.948     raeburn  3616:     }
1.400     www      3617:     return %returnhash;
                   3618: }
                   3619: 
                   3620: sub get_my_roles {
1.937     raeburn  3621:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3622:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3623:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3624:     my (%dumphash,%nothide);
1.1086    raeburn  3625:     if ($context eq 'userroles') {
                   3626:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3627:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3628:     } else {
                   3629:         %dumphash=
1.400     www      3630:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3631:         if ($hidepriv) {
                   3632:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3633:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3634:                 if ($user !~ /:/) {
                   3635:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3636:                 } else {
                   3637:                     $nothide{$user} = 1;
                   3638:                 }
                   3639:             }
                   3640:         }
1.858     raeburn  3641:     }
1.400     www      3642:     my %returnhash=();
                   3643:     my $now=time;
1.999     raeburn  3644:     my %privileged;
1.800     albertel 3645:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3646:         my ($role,$tend,$tstart);
                   3647:         if ($context eq 'userroles') {
1.1149    raeburn  3648:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3649: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3650:         } else {
                   3651:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3652:         }
1.400     www      3653:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3654:         my $status = 'active';
1.939     raeburn  3655:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3656:             $status = 'previous';
                   3657:         } 
                   3658:         if (($tstart) && ($now<$tstart)) {
                   3659:             $status = 'future';
                   3660:         }
                   3661:         if (ref($types) eq 'ARRAY') {
                   3662:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3663:                 next;
                   3664:             } 
                   3665:         } else {
                   3666:             if ($status ne 'active') {
                   3667:                 next;
                   3668:             }
                   3669:         }
1.867     raeburn  3670:         my ($rolecode,$username,$domain,$section,$area);
                   3671:         if ($context eq 'userroles') {
                   3672:             ($area,$rolecode) = split(/_/,$entry);
                   3673:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3674:         } else {
                   3675:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3676:         }
1.832     raeburn  3677:         if (ref($roledoms) eq 'ARRAY') {
                   3678:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3679:                 next;
                   3680:             }
                   3681:         }
                   3682:         if (ref($roles) eq 'ARRAY') {
                   3683:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3684:                 if ($role =~ /^cr\//) {
                   3685:                     if (!grep(/^cr$/,@{$roles})) {
                   3686:                         next;
                   3687:                     }
1.1104    raeburn  3688:                 } elsif ($role =~ /^gr\//) {
                   3689:                     if (!grep(/^gr$/,@{$roles})) {
                   3690:                         next;
                   3691:                     }
1.922     raeburn  3692:                 } else {
                   3693:                     next;
                   3694:                 }
1.832     raeburn  3695:             }
1.867     raeburn  3696:         }
1.937     raeburn  3697:         if ($hidepriv) {
1.999     raeburn  3698:             if ($context eq 'userroles') {
                   3699:                 if ((&privileged($username,$domain)) &&
                   3700:                     (!$nothide{$username.':'.$domain})) {
                   3701:                     next;
                   3702:                 }
                   3703:             } else {
                   3704:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3705:                     my %dompersonnel =
                   3706:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3707:                     $privileged{$domain} = {};
                   3708:                     if (keys(%dompersonnel)) {
                   3709:                         foreach my $server (keys(%dompersonnel)) {
                   3710:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3711:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3712:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3713:                                     $privileged{$udom}{$uname} = $trole;
                   3714:                                 }
                   3715:                             }
                   3716:                         }
                   3717:                     }
                   3718:                 }
                   3719:                 if (exists($privileged{$domain}{$username})) {
                   3720:                     if (!$nothide{$username.':'.$domain}) {
                   3721:                         next;
                   3722:                     }
                   3723:                 }
1.937     raeburn  3724:             }
                   3725:         }
1.933     raeburn  3726:         if ($withsec) {
                   3727:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3728:                 $tstart.':'.$tend;
                   3729:         } else {
                   3730:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3731:         }
1.832     raeburn  3732:     }
1.373     www      3733:     return %returnhash;
1.399     www      3734: }
                   3735: 
                   3736: # ----------------------------------------------------- Frontpage Announcements
                   3737: #
                   3738: #
                   3739: 
                   3740: sub postannounce {
                   3741:     my ($server,$text)=@_;
1.844     albertel 3742:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3743:     unless ($text=~/\w/) { $text=''; }
                   3744:     return &reply('setannounce:'.&escape($text),$server);
                   3745: }
                   3746: 
                   3747: sub getannounce {
1.448     albertel 3748: 
                   3749:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3750: 	my $announcement='';
1.800     albertel 3751: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3752: 	close($fh);
1.399     www      3753: 	if ($announcement=~/\w/) { 
                   3754: 	    return 
                   3755:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3756:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3757: 	} else {
                   3758: 	    return '';
                   3759: 	}
                   3760:     } else {
                   3761: 	return '';
                   3762:     }
1.351     www      3763: }
1.353     www      3764: 
                   3765: # ---------------------------------------------------------- Course ID routines
                   3766: # Deal with domain's nohist_courseid.db files
                   3767: #
                   3768: 
                   3769: sub courseidput {
1.921     raeburn  3770:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3771:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3772:     my $outcome;
                   3773:     if ($caller eq 'timeonly') {
                   3774:         my $cids = '';
                   3775:         foreach my $item (keys(%$storehash)) {
                   3776:             $cids.=&escape($item).'&';
                   3777:         }
                   3778:         $cids=~s/\&$//;
                   3779:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3780:                           $coursehome);       
                   3781:     } else {
                   3782:         my $items = '';
                   3783:         foreach my $item (keys(%$storehash)) {
                   3784:             $items.= &escape($item).'='.
                   3785:                      &freeze_escape($$storehash{$item}).'&';
                   3786:         }
                   3787:         $items=~s/\&$//;
                   3788:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3789:                           $coursehome);
1.918     raeburn  3790:     }
                   3791:     if ($outcome eq 'unknown_cmd') {
                   3792:         my $what;
                   3793:         foreach my $cid (keys(%$storehash)) {
                   3794:             $what .= &escape($cid).'=';
1.921     raeburn  3795:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3796:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3797:             }
                   3798:             $what =~ s/\:$/&/;
                   3799:         }
                   3800:         $what =~ s/\&$//;  
                   3801:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3802:     } else {
                   3803:         return $outcome;
                   3804:     }
1.353     www      3805: }
                   3806: 
                   3807: sub courseiddump {
1.921     raeburn  3808:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3809:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3810:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3811:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3812:     my $as_hash = 1;
                   3813:     my %returnhash;
                   3814:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3815:     my %libserv = &all_library();
                   3816:     foreach my $tryserver (keys(%libserv)) {
                   3817:         if ( (  $hostidflag == 1 
                   3818: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3819: 	     || (!defined($hostidflag)) ) {
                   3820: 
1.918     raeburn  3821: 	    if (($domfilter eq '') ||
                   3822: 		(&host_domain($tryserver) eq $domfilter)) {
                   3823:                 my $rep = 
                   3824:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3825:                          $sincefilter.':'.&escape($descfilter).':'.
                   3826:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3827:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3828:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3829:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3830:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3831:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3832:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3833:                          &escape($creationcontext).':'.$domcloner,
                   3834:                          $tryserver);
1.918     raeburn  3835:                 my @pairs=split(/\&/,$rep);
                   3836:                 foreach my $item (@pairs) {
                   3837:                     my ($key,$value)=split(/\=/,$item,2);
                   3838:                     $key = &unescape($key);
                   3839:                     next if ($key =~ /^error: 2 /);
                   3840:                     my $result = &thaw_unescape($value);
                   3841:                     if (ref($result) eq 'HASH') {
                   3842:                         $returnhash{$key}=$result;
                   3843:                     } else {
1.921     raeburn  3844:                         my @responses = split(/:/,$value);
                   3845:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3846:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3847:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3848:                         }
1.1008    raeburn  3849:                     }
1.353     www      3850:                 }
                   3851:             }
                   3852:         }
                   3853:     }
                   3854:     return %returnhash;
                   3855: }
                   3856: 
1.1055    raeburn  3857: sub courselastaccess {
                   3858:     my ($cdom,$cnum,$hostidref) = @_;
                   3859:     my %returnhash;
                   3860:     if ($cdom && $cnum) {
                   3861:         my $chome = &homeserver($cnum,$cdom);
                   3862:         if ($chome ne 'no_host') {
                   3863:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3864:             &extract_lastaccess(\%returnhash,$rep);
                   3865:         }
                   3866:     } else {
                   3867:         if (!$cdom) { $cdom=''; }
                   3868:         my %libserv = &all_library();
                   3869:         foreach my $tryserver (keys(%libserv)) {
                   3870:             if (ref($hostidref) eq 'ARRAY') {
                   3871:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3872:             } 
                   3873:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3874:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3875:                 &extract_lastaccess(\%returnhash,$rep);
                   3876:             }
                   3877:         }
                   3878:     }
                   3879:     return %returnhash;
                   3880: }
                   3881: 
                   3882: sub extract_lastaccess {
                   3883:     my ($returnhash,$rep) = @_;
                   3884:     if (ref($returnhash) eq 'HASH') {
                   3885:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3886:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3887:                  $rep eq '') {
                   3888:             my @pairs=split(/\&/,$rep);
                   3889:             foreach my $item (@pairs) {
                   3890:                 my ($key,$value)=split(/\=/,$item,2);
                   3891:                 $key = &unescape($key);
                   3892:                 next if ($key =~ /^error: 2 /);
                   3893:                 $returnhash->{$key} = &thaw_unescape($value);
                   3894:             }
                   3895:         }
                   3896:     }
                   3897:     return;
                   3898: }
                   3899: 
1.658     raeburn  3900: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3901: 
                   3902: sub dcmailput {
1.685     raeburn  3903:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3904:     my $status = &Apache::lonnet::critical(
1.740     www      3905:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3906:        &escape($message),$server);
1.662     raeburn  3907:     return $status;
                   3908: }
                   3909: 
1.658     raeburn  3910: sub dcmaildump {
                   3911:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3912:     my %returnhash=();
1.846     albertel 3913: 
                   3914:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3915:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3916:                                                          &escape($enddate).':';
                   3917: 	my @esc_senders=map { &escape($_)} @$senders;
                   3918: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3919: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3920:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3921:             if (($key) && ($value)) {
                   3922:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3923:             }
                   3924:         }
                   3925:     }
                   3926:     return %returnhash;
                   3927: }
1.662     raeburn  3928: # ---------------------------------------------------------- Domain roles
                   3929: 
                   3930: sub get_domain_roles {
                   3931:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3932:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3933:         $startdate = '.';
                   3934:     }
1.1018    raeburn  3935:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3936:         $enddate = '.';
                   3937:     }
1.922     raeburn  3938:     my $rolelist;
                   3939:     if (ref($roles) eq 'ARRAY') {
                   3940:         $rolelist = join(':',@{$roles});
                   3941:     }
1.662     raeburn  3942:     my %personnel = ();
1.841     albertel 3943: 
                   3944:     my %servers = &get_servers($dom,'library');
                   3945:     foreach my $tryserver (keys(%servers)) {
                   3946: 	%{$personnel{$tryserver}}=();
                   3947: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3948: 					    &escape($startdate).':'.
                   3949: 					    &escape($enddate).':'.
                   3950: 					    &escape($rolelist), $tryserver))) {
                   3951: 	    my ($key,$value) = split(/\=/,$line,2);
                   3952: 	    if (($key) && ($value)) {
                   3953: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3954: 	    }
                   3955: 	}
1.662     raeburn  3956:     }
                   3957:     return %personnel;
                   3958: }
1.658     raeburn  3959: 
1.1057    www      3960: # ----------------------------------------------------------- Interval timing 
1.149     www      3961: 
1.1153    www      3962: {
                   3963: # Caches needed for speedup of navmaps
                   3964: # We don't want to cache this for very long at all (5 seconds at most)
                   3965: # 
                   3966: # The user for whom we cache
                   3967: my $cachedkey='';
                   3968: # The cached times for this user
                   3969: my %cachedtimes=();
                   3970: # When this was last done
                   3971: my $cachedtime=();
                   3972: 
                   3973: sub load_all_first_access {
1.1154    raeburn  3974:     my ($uname,$udom)=@_;
1.1156    www      3975:     if (($cachedkey eq $uname.':'.$udom) &&
1.1154    raeburn  3976:         (abs($cachedtime-time)<5)) {
                   3977:         return;
                   3978:     }
                   3979:     $cachedtime=time;
                   3980:     $cachedkey=$uname.':'.$udom;
                   3981:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3982: }
                   3983: 
1.504     albertel 3984: sub get_first_access {
1.1162    raeburn  3985:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 3986:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3987:     if ($argsymb) { $symb=$argsymb; }
                   3988:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  3989:     if ($argmap) { $map = $argmap; }
1.926     albertel 3990:     if ($type eq 'course') {
                   3991: 	$res='course';
                   3992:     } elsif ($type eq 'map') {
1.588     albertel 3993: 	$res=&symbread($map);
                   3994:     } else {
                   3995: 	$res=$symb;
                   3996:     }
1.1153    www      3997:     &load_all_first_access($uname,$udom);
                   3998:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3999: }
                   4000: 
                   4001: sub set_first_access {
1.1162    raeburn  4002:     my ($type,$interval)=@_;
1.790     albertel 4003:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4004:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4005:     if ($type eq 'course') {
                   4006: 	$res='course';
                   4007:     } elsif ($type eq 'map') {
1.588     albertel 4008: 	$res=&symbread($map);
                   4009:     } else {
                   4010: 	$res=$symb;
                   4011:     }
1.1153    www      4012:     $cachedkey='';
1.1162    raeburn  4013:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4014:     if (!$firstaccess) {
1.1162    raeburn  4015:         my $start = time;
                   4016: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4017:                           $udom,$uname);
                   4018:         if ($putres eq 'ok') {
                   4019:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4020:                  $udom,$uname); 
                   4021:             &appenv(
                   4022:                      {
                   4023:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4024:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4025:                      }
                   4026:                   );
                   4027:         }
                   4028:         return $putres;
1.505     albertel 4029:     }
                   4030:     return 'already_set';
1.504     albertel 4031: }
1.1153    www      4032: }
1.110     www      4033: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4034: 
                   4035: sub expirespread {
                   4036:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4037:     my $cid=$env{'request.course.id'}; 
1.110     www      4038:     if ($cid) {
                   4039:        my $now=time;
                   4040:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4041:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4042:                             $env{'course.'.$cid.'.num'}.
1.110     www      4043: 	        	    ':nohist_expirationdates:'.
                   4044:                             &escape($key).'='.$now,
1.620     albertel 4045:                             $env{'course.'.$cid.'.home'})
1.110     www      4046:     }
                   4047:     return 'ok';
1.14      www      4048: }
                   4049: 
1.109     www      4050: # ----------------------------------------------------- Devalidate Spreadsheets
                   4051: 
                   4052: sub devalidate {
1.325     www      4053:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4054:     my $cid=$env{'request.course.id'}; 
1.109     www      4055:     if ($cid) {
1.391     matthew  4056:         # delete the stored spreadsheets for
                   4057:         # - the student level sheet of this user in course's homespace
                   4058:         # - the assessment level sheet for this resource 
                   4059:         #   for this user in user's homespace
1.553     albertel 4060: 	# - current conditional state info
1.325     www      4061: 	my $key=$uname.':'.$udom.':';
1.109     www      4062:         my $status=
1.299     matthew  4063: 	    &del('nohist_calculatedsheets',
1.391     matthew  4064: 		 [$key.'studentcalc:'],
1.620     albertel 4065: 		 $env{'course.'.$cid.'.domain'},
                   4066: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4067: 		.' '.
                   4068: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4069: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4070:         unless ($status eq 'ok ok') {
                   4071:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4072:                     $uname.' at '.$udom.' for '.
1.109     www      4073: 		    $symb.': '.$status);
1.133     albertel 4074:         }
1.553     albertel 4075: 	&delenv('user.state.'.$cid);
1.109     www      4076:     }
                   4077: }
                   4078: 
1.265     albertel 4079: sub get_scalar {
                   4080:     my ($string,$end) = @_;
                   4081:     my $value;
                   4082:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4083: 	$value = $1;
                   4084:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4085: 	$value = $1;
                   4086:     }
                   4087:     return &unescape($value);
                   4088: }
                   4089: 
                   4090: sub array2str {
                   4091:   my (@array) = @_;
                   4092:   my $result=&arrayref2str(\@array);
                   4093:   $result=~s/^__ARRAY_REF__//;
                   4094:   $result=~s/__END_ARRAY_REF__$//;
                   4095:   return $result;
                   4096: }
                   4097: 
1.204     albertel 4098: sub arrayref2str {
                   4099:   my ($arrayref) = @_;
1.265     albertel 4100:   my $result='__ARRAY_REF__';
1.204     albertel 4101:   foreach my $elem (@$arrayref) {
1.265     albertel 4102:     if(ref($elem) eq 'ARRAY') {
                   4103:       $result.=&arrayref2str($elem).'&';
                   4104:     } elsif(ref($elem) eq 'HASH') {
                   4105:       $result.=&hashref2str($elem).'&';
                   4106:     } elsif(ref($elem)) {
                   4107:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4108:     } else {
                   4109:       $result.=&escape($elem).'&';
                   4110:     }
                   4111:   }
                   4112:   $result=~s/\&$//;
1.265     albertel 4113:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4114:   return $result;
                   4115: }
                   4116: 
1.168     albertel 4117: sub hash2str {
1.204     albertel 4118:   my (%hash) = @_;
                   4119:   my $result=&hashref2str(\%hash);
1.265     albertel 4120:   $result=~s/^__HASH_REF__//;
                   4121:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4122:   return $result;
                   4123: }
                   4124: 
                   4125: sub hashref2str {
                   4126:   my ($hashref)=@_;
1.265     albertel 4127:   my $result='__HASH_REF__';
1.800     albertel 4128:   foreach my $key (sort(keys(%$hashref))) {
                   4129:     if (ref($key) eq 'ARRAY') {
                   4130:       $result.=&arrayref2str($key).'=';
                   4131:     } elsif (ref($key) eq 'HASH') {
                   4132:       $result.=&hashref2str($key).'=';
                   4133:     } elsif (ref($key)) {
1.265     albertel 4134:       $result.='=';
1.800     albertel 4135:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4136:     } else {
1.1132    raeburn  4137: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4138:     }
                   4139: 
1.800     albertel 4140:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4141:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4142:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4143:       $result.=&hashref2str($hashref->{$key}).'&';
                   4144:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4145:        $result.='&';
1.800     albertel 4146:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4147:     } else {
1.800     albertel 4148:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4149:     }
                   4150:   }
1.168     albertel 4151:   $result=~s/\&$//;
1.265     albertel 4152:   $result .= '__END_HASH_REF__';
1.168     albertel 4153:   return $result;
                   4154: }
                   4155: 
                   4156: sub str2hash {
1.265     albertel 4157:     my ($string)=@_;
                   4158:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4159:     return %$hash;
                   4160: }
                   4161: 
                   4162: sub str2hashref {
1.168     albertel 4163:   my ($string) = @_;
1.265     albertel 4164: 
                   4165:   my %hash;
                   4166: 
                   4167:   if($string !~ /^__HASH_REF__/) {
                   4168:       if (! ($string eq '' || !defined($string))) {
                   4169: 	  $hash{'error'}='Not hash reference';
                   4170:       }
                   4171:       return (\%hash, $string);
                   4172:   }
                   4173: 
                   4174:   $string =~ s/^__HASH_REF__//;
                   4175: 
                   4176:   while($string !~ /^__END_HASH_REF__/) {
                   4177:       #key
                   4178:       my $key='';
                   4179:       if($string =~ /^__HASH_REF__/) {
                   4180:           ($key, $string)=&str2hashref($string);
                   4181:           if(defined($key->{'error'})) {
                   4182:               $hash{'error'}='Bad data';
                   4183:               return (\%hash, $string);
                   4184:           }
                   4185:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4186:           ($key, $string)=&str2arrayref($string);
                   4187:           if($key->[0] eq 'Array reference error') {
                   4188:               $hash{'error'}='Bad data';
                   4189:               return (\%hash, $string);
                   4190:           }
                   4191:       } else {
                   4192:           $string =~ s/^(.*?)=//;
1.267     albertel 4193: 	  $key=&unescape($1);
1.265     albertel 4194:       }
                   4195:       $string =~ s/^=//;
                   4196: 
                   4197:       #value
                   4198:       my $value='';
                   4199:       if($string =~ /^__HASH_REF__/) {
                   4200:           ($value, $string)=&str2hashref($string);
                   4201:           if(defined($value->{'error'})) {
                   4202:               $hash{'error'}='Bad data';
                   4203:               return (\%hash, $string);
                   4204:           }
                   4205:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4206:           ($value, $string)=&str2arrayref($string);
                   4207:           if($value->[0] eq 'Array reference error') {
                   4208:               $hash{'error'}='Bad data';
                   4209:               return (\%hash, $string);
                   4210:           }
                   4211:       } else {
                   4212: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4213:       }
                   4214:       $string =~ s/^&//;
                   4215: 
                   4216:       $hash{$key}=$value;
1.204     albertel 4217:   }
1.265     albertel 4218: 
                   4219:   $string =~ s/^__END_HASH_REF__//;
                   4220: 
                   4221:   return (\%hash, $string);
1.204     albertel 4222: }
                   4223: 
                   4224: sub str2array {
1.265     albertel 4225:     my ($string)=@_;
                   4226:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4227:     return @$array;
                   4228: }
                   4229: 
                   4230: sub str2arrayref {
1.204     albertel 4231:   my ($string) = @_;
1.265     albertel 4232:   my @array;
                   4233: 
                   4234:   if($string !~ /^__ARRAY_REF__/) {
                   4235:       if (! ($string eq '' || !defined($string))) {
                   4236: 	  $array[0]='Array reference error';
                   4237:       }
                   4238:       return (\@array, $string);
                   4239:   }
                   4240: 
                   4241:   $string =~ s/^__ARRAY_REF__//;
                   4242: 
                   4243:   while($string !~ /^__END_ARRAY_REF__/) {
                   4244:       my $value='';
                   4245:       if($string =~ /^__HASH_REF__/) {
                   4246:           ($value, $string)=&str2hashref($string);
                   4247:           if(defined($value->{'error'})) {
                   4248:               $array[0] ='Array reference error';
                   4249:               return (\@array, $string);
                   4250:           }
                   4251:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4252:           ($value, $string)=&str2arrayref($string);
                   4253:           if($value->[0] eq 'Array reference error') {
                   4254:               $array[0] ='Array reference error';
                   4255:               return (\@array, $string);
                   4256:           }
                   4257:       } else {
                   4258: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4259:       }
                   4260:       $string =~ s/^&//;
                   4261: 
                   4262:       push(@array, $value);
1.191     harris41 4263:   }
1.265     albertel 4264: 
                   4265:   $string =~ s/^__END_ARRAY_REF__//;
                   4266: 
                   4267:   return (\@array, $string);
1.168     albertel 4268: }
                   4269: 
1.167     albertel 4270: # -------------------------------------------------------------------Temp Store
                   4271: 
1.168     albertel 4272: sub tmpreset {
                   4273:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4274:   if (!$symb) {
                   4275:     $symb=&symbread();
1.620     albertel 4276:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4277:   }
                   4278:   $symb=escape($symb);
                   4279: 
1.620     albertel 4280:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4281:   $namespace=~s/\//\_/g;
                   4282:   $namespace=~s/\W//g;
                   4283: 
1.620     albertel 4284:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4285:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4286:   if ($domain eq 'public' && $stuname eq 'public') {
                   4287:       $stuname=$ENV{'REMOTE_ADDR'};
                   4288:   }
1.1117    foxr     4289:   my $path=LONCAPA::tempdir();
1.168     albertel 4290:   my %hash;
                   4291:   if (tie(%hash,'GDBM_File',
                   4292: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4293: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4294:     foreach my $key (keys(%hash)) {
1.180     albertel 4295:       if ($key=~ /:$symb/) {
1.168     albertel 4296: 	delete($hash{$key});
                   4297:       }
                   4298:     }
                   4299:   }
                   4300: }
                   4301: 
1.167     albertel 4302: sub tmpstore {
1.168     albertel 4303:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4304: 
                   4305:   if (!$symb) {
                   4306:     $symb=&symbread();
1.620     albertel 4307:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4308:   }
                   4309:   $symb=escape($symb);
                   4310: 
                   4311:   if (!$namespace) {
                   4312:     # I don't think we would ever want to store this for a course.
                   4313:     # it seems this will only be used if we don't have a course.
1.620     albertel 4314:     #$namespace=$env{'request.course.id'};
1.168     albertel 4315:     #if (!$namespace) {
1.620     albertel 4316:       $namespace=$env{'request.state'};
1.168     albertel 4317:     #}
                   4318:   }
                   4319:   $namespace=~s/\//\_/g;
                   4320:   $namespace=~s/\W//g;
1.620     albertel 4321:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4322:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4323:   if ($domain eq 'public' && $stuname eq 'public') {
                   4324:       $stuname=$ENV{'REMOTE_ADDR'};
                   4325:   }
1.168     albertel 4326:   my $now=time;
                   4327:   my %hash;
1.1117    foxr     4328:   my $path=LONCAPA::tempdir();
1.168     albertel 4329:   if (tie(%hash,'GDBM_File',
                   4330: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4331: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4332:     $hash{"version:$symb"}++;
                   4333:     my $version=$hash{"version:$symb"};
                   4334:     my $allkeys=''; 
                   4335:     foreach my $key (keys(%$storehash)) {
                   4336:       $allkeys.=$key.':';
1.591     albertel 4337:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4338:     }
                   4339:     $hash{"$version:$symb:timestamp"}=$now;
                   4340:     $allkeys.='timestamp';
                   4341:     $hash{"$version:keys:$symb"}=$allkeys;
                   4342:     if (untie(%hash)) {
                   4343:       return 'ok';
                   4344:     } else {
                   4345:       return "error:$!";
                   4346:     }
                   4347:   } else {
                   4348:     return "error:$!";
                   4349:   }
                   4350: }
1.167     albertel 4351: 
1.168     albertel 4352: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4353: 
1.168     albertel 4354: sub tmprestore {
                   4355:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4356: 
1.168     albertel 4357:   if (!$symb) {
                   4358:     $symb=&symbread();
1.620     albertel 4359:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4360:   }
                   4361:   $symb=escape($symb);
                   4362: 
1.620     albertel 4363:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4364: 
1.620     albertel 4365:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4366:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4367:   if ($domain eq 'public' && $stuname eq 'public') {
                   4368:       $stuname=$ENV{'REMOTE_ADDR'};
                   4369:   }
1.168     albertel 4370:   my %returnhash;
                   4371:   $namespace=~s/\//\_/g;
                   4372:   $namespace=~s/\W//g;
                   4373:   my %hash;
1.1117    foxr     4374:   my $path=LONCAPA::tempdir();
1.168     albertel 4375:   if (tie(%hash,'GDBM_File',
                   4376: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4377: 	  &GDBM_READER(),0640)) {
1.168     albertel 4378:     my $version=$hash{"version:$symb"};
                   4379:     $returnhash{'version'}=$version;
                   4380:     my $scope;
                   4381:     for ($scope=1;$scope<=$version;$scope++) {
                   4382:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4383:       my @keys=split(/:/,$vkeys);
                   4384:       my $key;
                   4385:       $returnhash{"$scope:keys"}=$vkeys;
                   4386:       foreach $key (@keys) {
1.591     albertel 4387: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4388: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4389:       }
                   4390:     }
1.168     albertel 4391:     if (!(untie(%hash))) {
                   4392:       return "error:$!";
                   4393:     }
                   4394:   } else {
                   4395:     return "error:$!";
                   4396:   }
                   4397:   return %returnhash;
1.167     albertel 4398: }
                   4399: 
1.9       www      4400: # ----------------------------------------------------------------------- Store
                   4401: 
                   4402: sub store {
1.124     www      4403:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4404:     my $home='';
                   4405: 
1.168     albertel 4406:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4407: 
1.213     www      4408:     $symb=&symbclean($symb);
1.122     albertel 4409:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4410: 
1.620     albertel 4411:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4412:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4413: 
                   4414:     &devalidate($symb,$stuname,$domain);
1.109     www      4415: 
                   4416:     $symb=escape($symb);
1.187     www      4417:     if (!$namespace) { 
1.620     albertel 4418:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4419:           return ''; 
                   4420:        } 
                   4421:     }
1.620     albertel 4422:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4423: 
                   4424:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4425:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4426: 
1.12      www      4427:     my $namevalue='';
1.800     albertel 4428:     foreach my $key (keys(%$storehash)) {
                   4429:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4430:     }
1.12      www      4431:     $namevalue=~s/\&$//;
1.187     www      4432:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4433:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4434: }
                   4435: 
1.47      www      4436: # -------------------------------------------------------------- Critical Store
                   4437: 
                   4438: sub cstore {
1.124     www      4439:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4440:     my $home='';
                   4441: 
1.168     albertel 4442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4443: 
1.213     www      4444:     $symb=&symbclean($symb);
1.122     albertel 4445:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4446: 
1.620     albertel 4447:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4448:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4449: 
                   4450:     &devalidate($symb,$stuname,$domain);
1.109     www      4451: 
                   4452:     $symb=escape($symb);
1.187     www      4453:     if (!$namespace) { 
1.620     albertel 4454:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4455:           return ''; 
                   4456:        } 
                   4457:     }
1.620     albertel 4458:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4459: 
                   4460:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4461:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4462: 
1.47      www      4463:     my $namevalue='';
1.800     albertel 4464:     foreach my $key (keys(%$storehash)) {
                   4465:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4466:     }
1.47      www      4467:     $namevalue=~s/\&$//;
1.187     www      4468:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4469:     return critical
                   4470:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4471: }
                   4472: 
1.9       www      4473: # --------------------------------------------------------------------- Restore
                   4474: 
                   4475: sub restore {
1.124     www      4476:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4477:     my $home='';
                   4478: 
1.168     albertel 4479:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4480: 
1.122     albertel 4481:     if (!$symb) {
                   4482:       unless ($symb=escape(&symbread())) { return ''; }
                   4483:     } else {
1.213     www      4484:       $symb=&escape(&symbclean($symb));
1.122     albertel 4485:     }
1.188     www      4486:     if (!$namespace) { 
1.620     albertel 4487:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4488:           return ''; 
                   4489:        } 
                   4490:     }
1.620     albertel 4491:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4492:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4493:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4494:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4495: 
1.12      www      4496:     my %returnhash=();
1.800     albertel 4497:     foreach my $line (split(/\&/,$answer)) {
                   4498: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4499:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4500:     }
1.75      www      4501:     my $version;
                   4502:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4503:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4504:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4505:        }
1.75      www      4506:     }
1.13      www      4507:     return %returnhash;
1.34      www      4508: }
                   4509: 
                   4510: # ---------------------------------------------------------- Course Description
1.1118    foxr     4511: #
                   4512: #  
1.34      www      4513: 
                   4514: sub coursedescription {
1.731     albertel 4515:     my ($courseid,$args)=@_;
1.34      www      4516:     $courseid=~s/^\///;
1.49      www      4517:     $courseid=~s/\_/\//g;
1.34      www      4518:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4519:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4520:     my $normalid=$cdomain.'_'.$cnum;
                   4521:     # need to always cache even if we get errors otherwise we keep 
                   4522:     # trying and trying and trying to get the course description.
                   4523:     my %envhash=();
                   4524:     my %returnhash=();
1.731     albertel 4525:     
                   4526:     my $expiretime=600;
                   4527:     if ($env{'request.course.id'} eq $normalid) {
                   4528: 	$expiretime=120;
                   4529:     }
                   4530: 
                   4531:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4532:     if (!$args->{'freshen_cache'}
                   4533: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4534: 	foreach my $key (keys(%env)) {
                   4535: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4536: 	    my ($setting) = $1;
                   4537: 	    $returnhash{$setting} = $env{$key};
                   4538: 	}
                   4539: 	return %returnhash;
                   4540:     }
                   4541: 
1.1118    foxr     4542:     # get the data again
                   4543: 
1.731     albertel 4544:     if (!$args->{'one_time'}) {
                   4545: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4546:     }
1.811     albertel 4547: 
1.34      www      4548:     if ($chome ne 'no_host') {
1.302     albertel 4549:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4550:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4551: 	   my $username = $env{'user.name'}; # Defult username
                   4552: 	   if(defined $args->{'user'}) {
                   4553: 	       $username = $args->{'user'};
                   4554: 	   }
1.129     albertel 4555:            $returnhash{'home'}= $chome;
                   4556: 	   $returnhash{'domain'} = $cdomain;
                   4557: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4558:            if (!defined($returnhash{'type'})) {
                   4559:                $returnhash{'type'} = 'Course';
                   4560:            }
1.130     albertel 4561:            while (my ($name,$value) = each %returnhash) {
1.53      www      4562:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4563:            }
1.270     www      4564:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4565:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4566: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4567:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4568:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4569:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4570:        }
                   4571:     }
1.731     albertel 4572:     if (!$args->{'one_time'}) {
1.949     raeburn  4573: 	&appenv(\%envhash);
1.731     albertel 4574:     }
1.302     albertel 4575:     return %returnhash;
1.461     www      4576: }
                   4577: 
1.1080    raeburn  4578: sub update_released_required {
                   4579:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4580:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4581:         $cid = $env{'request.course.id'};
                   4582:         $cdom = $env{'course.'.$cid.'.domain'};
                   4583:         $cnum = $env{'course.'.$cid.'.num'};
                   4584:         $chome = $env{'course.'.$cid.'.home'};
                   4585:     }
                   4586:     if ($needsrelease) {
                   4587:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4588:         my $needsupdate;
                   4589:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4590:             $needsupdate = 1;
                   4591:         } else {
                   4592:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4593:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4594:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4595:                 $needsupdate = 1;
                   4596:             }
                   4597:         }
                   4598:         if ($needsupdate) {
                   4599:             my %needshash = (
                   4600:                              'internal.releaserequired' => $needsrelease,
                   4601:                             );
                   4602:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4603:             if ($putresult eq 'ok') {
                   4604:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4605:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4606:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4607:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4608:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4609:                 }
                   4610:             }
                   4611:         }
                   4612:     }
                   4613:     return;
                   4614: }
                   4615: 
1.461     www      4616: # -------------------------------------------------See if a user is privileged
                   4617: 
                   4618: sub privileged {
                   4619:     my ($username,$domain)=@_;
                   4620:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4621: 			&homeserver($username,$domain));
1.1033    raeburn  4622:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4623:         ($rolesdump =~ /^error:/)) {
                   4624:         return 0;
                   4625:     }
1.461     www      4626:     my $now=time;
                   4627:     if ($rolesdump ne '') {
1.800     albertel 4628:         foreach my $entry (split(/&/,$rolesdump)) {
                   4629: 	    if ($entry!~/^rolesdef_/) {
                   4630: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4631: 		$area=~s/\_\w\w$//;
                   4632: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4633: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4634: 		    my $active=1;
                   4635: 		    if ($tend) {
                   4636: 			if ($tend<$now) { $active=0; }
                   4637: 		    }
                   4638: 		    if ($tstart) {
                   4639: 			if ($tstart>$now) { $active=0; }
                   4640: 		    }
                   4641: 		    if ($active) { return 1; }
                   4642: 		}
                   4643: 	    }
                   4644: 	}
                   4645:     }
                   4646:     return 0;
1.9       www      4647: }
1.1       albertel 4648: 
1.103     harris41 4649: # -------------------------------------------------------- Get user privileges
1.11      www      4650: 
                   4651: sub rolesinit {
                   4652:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4653:     my $now=time;
                   4654:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4655:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4656:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4657:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4658:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4659:         return \%userroles;
                   4660:     }
1.1162    raeburn  4661:     my %firstaccess = &dump('firstaccesstimes',$domain,$username);
                   4662:     my %timerinterval = &dump('timerinterval',$domain,$username);
                   4663:     my (%coursetimerstarts,%firstaccchk,%firstaccenv,
                   4664:         %coursetimerintervals,%timerintchk,%timerintenv);
                   4665:     foreach my $key (keys(%firstaccess)) {
                   4666:         my ($cid,$rest) = split(/\0/,$key);
                   4667:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4668:     }
                   4669:     foreach my $key (keys(%timerinterval)) {
                   4670:         my ($cid,$rest) = split(/\0/,$key);
                   4671:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4672:     }
1.11      www      4673:     my %allroles=();
1.1162    raeburn  4674:     my %allgroups=();
1.11      www      4675: 
                   4676:     if ($rolesdump ne '') {
1.800     albertel 4677:         foreach my $entry (split(/&/,$rolesdump)) {
                   4678: 	  if ($entry!~/^rolesdef_/) {
                   4679:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4680: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4681:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4682: 	    if ($role=~/^cr/) { 
1.807     albertel 4683: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4684: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4685: 		    ($tend,$tstart)=split('_',$trest);
                   4686: 		} else {
                   4687: 		    $trole=$role;
                   4688: 		}
1.678     raeburn  4689:             } elsif ($role =~ m|^gr/|) {
                   4690:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4691:                 next if ($tstart eq '-1');
1.678     raeburn  4692:                 ($trole,$group_privs) = split(/\//,$trole);
                   4693:                 $group_privs = &unescape($group_privs);
1.587     albertel 4694: 	    } else {
                   4695: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4696: 	    }
1.743     albertel 4697: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4698: 					 $username);
                   4699: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4700:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4701:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4702:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4703: 		my $spec=$trole.'.'.$area;
                   4704: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4705: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4706:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4707:                 } elsif ($trole eq 'gr') {
                   4708:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4709: 		} else {
1.567     raeburn  4710:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4711: 		}
1.1162    raeburn  4712:                 if ($trole ne 'gr') {
                   4713:                     my $cid = $tdomain.'_'.$trest;
                   4714:                     unless ($firstaccchk{$cid}) {
                   4715:                         if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4716:                             foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4717:                                 $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4718:                                     $coursetimerstarts{$cid}{$item}; 
                   4719:                             }
                   4720:                         }
                   4721:                         $firstaccchk{$cid} = 1;
                   4722:                     }
                   4723:                     unless ($timerintchk{$cid}) {
                   4724:                         if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4725:                             foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4726:                                 $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4727:                                    $coursetimerintervals{$cid}{$item};
                   4728:                             }
                   4729:                         }
                   4730:                         $timerintchk{$cid} = 1;
                   4731:                     }
                   4732:                 }
1.12      www      4733:             }
1.662     raeburn  4734:           }
1.191     harris41 4735:         }
1.743     albertel 4736:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4737:         $userroles{'user.adv'}    = $adv;
                   4738: 	$userroles{'user.author'} = $author;
1.620     albertel 4739:         $env{'user.adv'}=$adv;
1.11      www      4740:     }
1.1162    raeburn  4741:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4742: }
                   4743: 
1.567     raeburn  4744: sub set_arearole {
                   4745:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4746: # log the associated role with the area
                   4747:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4748:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4749: }
                   4750: 
                   4751: sub custom_roleprivs {
                   4752:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4753:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4754:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4755:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4756:         my ($rdummy,$roledef)=
                   4757:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4758:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4759:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4760:             if (defined($syspriv)) {
1.1043    raeburn  4761:                 if ($trest =~ /^$match_community$/) {
                   4762:                     $syspriv =~ s/bre\&S//; 
                   4763:                 }
1.567     raeburn  4764:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4765:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4766:             }
                   4767:             if ($tdomain ne '') {
                   4768:                 if (defined($dompriv)) {
                   4769:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4770:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4771:                 }
                   4772:                 if (($trest ne '') && (defined($coursepriv))) {
                   4773:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4774:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4775:                 }
                   4776:             }
                   4777:         }
                   4778:     }
                   4779: }
                   4780: 
1.678     raeburn  4781: sub group_roleprivs {
                   4782:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4783:     my $access = 1;
                   4784:     my $now = time;
                   4785:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4786:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4787:     if ($access) {
1.811     albertel 4788:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4789:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4790:     }
                   4791: }
1.567     raeburn  4792: 
                   4793: sub standard_roleprivs {
                   4794:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4795:     if (defined($pr{$trole.':s'})) {
                   4796:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4797:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4798:     }
                   4799:     if ($tdomain ne '') {
                   4800:         if (defined($pr{$trole.':d'})) {
                   4801:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4802:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4803:         }
                   4804:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4805:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4806:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4807:         }
                   4808:     }
                   4809: }
                   4810: 
                   4811: sub set_userprivs {
1.1064    raeburn  4812:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4813:     my $author=0;
                   4814:     my $adv=0;
1.678     raeburn  4815:     my %grouproles = ();
                   4816:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4817:         my @groupkeys; 
1.1000    raeburn  4818:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4819:             push(@groupkeys,$role);
                   4820:         }
                   4821:         if (ref($groups_roles) eq 'HASH') {
                   4822:             foreach my $key (keys(%{$groups_roles})) {
                   4823:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4824:                     push(@groupkeys,$key);
                   4825:                 }
                   4826:             }
                   4827:         }
                   4828:         if (@groupkeys > 0) {
                   4829:             foreach my $role (@groupkeys) {
                   4830:                 my ($trole,$area,$sec,$extendedarea);
                   4831:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4832:                     $trole = $1;
                   4833:                     $area = $2;
                   4834:                     $sec = $3;
                   4835:                     $extendedarea = $area.$sec;
                   4836:                     if (exists($$allgroups{$area})) {
                   4837:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4838:                             my $spec = $trole.'.'.$extendedarea;
                   4839:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4840:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4841:                         }
1.678     raeburn  4842:                     }
                   4843:                 }
                   4844:             }
                   4845:         }
                   4846:     }
1.800     albertel 4847:     foreach my $group (keys(%grouproles)) {
                   4848:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4849:     }
1.800     albertel 4850:     foreach my $role (keys(%{$allroles})) {
                   4851:         my %thesepriv;
1.941     raeburn  4852:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4853:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4854:             if ($item ne '') {
                   4855:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4856:                 if ($restrictions eq '') {
                   4857:                     $thesepriv{$privilege}='F';
                   4858:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4859:                     $thesepriv{$privilege}.=$restrictions;
                   4860:                 }
                   4861:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4862:             }
                   4863:         }
                   4864:         my $thesestr='';
1.1104    raeburn  4865:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4866: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4867: 	}
                   4868:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4869:     }
                   4870:     return ($author,$adv);
                   4871: }
                   4872: 
1.994     raeburn  4873: sub role_status {
1.1104    raeburn  4874:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4875:     my @pwhere = ();
                   4876:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4877:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4878:         unless (!defined($$role) || $$role eq '') {
                   4879:             $$where=join('.',@pwhere);
                   4880:             $$trolecode=$$role.'.'.$$where;
                   4881:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4882:             $$tstatus='is';
1.1104    raeburn  4883:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4884:                 $$tstatus='future';
1.1034    raeburn  4885:                 if ($$tstart<$now) {
                   4886:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4887:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4888:                             my (%allroles,%allgroups,$group_privs,
                   4889:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4890:                             my %userroles = (
                   4891:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4892:                             );
1.1064    raeburn  4893:                             @rolecodes = ('cm'); 
1.1002    raeburn  4894:                             my $spec=$$role.'.'.$$where;
                   4895:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4896:                             if ($$role =~ /^cr\//) {
                   4897:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4898:                                 push(@rolecodes,'cr');
1.1002    raeburn  4899:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4900:                                 push(@rolecodes,$$role);
1.1002    raeburn  4901:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4902:                                                     $env{'user.name'});
1.1064    raeburn  4903:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4904:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4905:                                 $group_privs = &unescape($group_privs);
                   4906:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4907:                                 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  4908:                                 &get_groups_roles($tdomain,$trest,
                   4909:                                                   \%course_roles,\@rolecodes,
                   4910:                                                   \%groups_roles);
1.1002    raeburn  4911:                             } else {
1.1064    raeburn  4912:                                 push(@rolecodes,$$role);
1.1002    raeburn  4913:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4914:                             }
1.1064    raeburn  4915:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4916:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4917:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4918:                         }
                   4919:                     }
1.1034    raeburn  4920:                     $$tstatus = 'is';
1.1002    raeburn  4921:                 }
1.994     raeburn  4922:             }
                   4923:             if ($$tend) {
1.1104    raeburn  4924:                 if ($$tend<$update) {
1.994     raeburn  4925:                     $$tstatus='expired';
                   4926:                 } elsif ($$tend<$now) {
                   4927:                     $$tstatus='will_not';
                   4928:                 }
                   4929:             }
                   4930:         }
                   4931:     }
                   4932: }
                   4933: 
1.1104    raeburn  4934: sub get_groups_roles {
                   4935:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4936:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4937:                   (ref($rolecodes) eq 'ARRAY') && 
                   4938:                   (ref($groups_roles) eq 'HASH')); 
                   4939:     if (keys(%{$cdom_courseroles}) > 0) {
                   4940:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4941:         if ($cdom ne '' && $cnum ne '') {
                   4942:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4943:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4944:                     my $crsrole = $1;
                   4945:                     my $crssec = $2;
                   4946:                     if ($crsrole =~ /^cr/) {
                   4947:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4948:                             push(@{$rolecodes},'cr');
                   4949:                         }
                   4950:                     } else {
                   4951:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4952:                             push(@{$rolecodes},$crsrole);
                   4953:                         }
                   4954:                     }
                   4955:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4956:                     if ($crssec ne '') {
                   4957:                         $rolekey .= "/$crssec";
                   4958:                     }
                   4959:                     $rolekey .= './';
                   4960:                     $groups_roles->{$rolekey} = $rolecodes;
                   4961:                 }
                   4962:             }
                   4963:         }
                   4964:     }
                   4965:     return;
                   4966: }
                   4967: 
                   4968: sub delete_env_groupprivs {
                   4969:     my ($where,$courseroles,$possroles) = @_;
                   4970:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4971:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4972:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4973:         %{$courseroles->{$udom}} =
                   4974:             &get_my_roles('','','userroles',['active'],
                   4975:                           $possroles,[$udom],1);
                   4976:     }
                   4977:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4978:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4979:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4980:             my $area = '/'.$cdom.'/'.$cnum;
                   4981:             my $privkey = "user.priv.$crsrole.$area";
                   4982:             if ($crssec ne '') {
                   4983:                 $privkey .= '/'.$crssec;
                   4984:             }
                   4985:             $privkey .= ".$area/$group";
                   4986:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4987:         }
                   4988:     }
                   4989:     return;
                   4990: }
                   4991: 
1.994     raeburn  4992: sub check_adhoc_privs {
1.1104    raeburn  4993:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4994:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4995:     if ($env{$cckey}) {
                   4996:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4997:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4998:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4999:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5000:         }
                   5001:     } else {
1.1088    raeburn  5002:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5003:     }
                   5004: }
                   5005: 
                   5006: sub set_adhoc_privileges {
                   5007: # role can be cc or ca
1.1088    raeburn  5008:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5009:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5010:     my $spec = $role.'.'.$area;
                   5011:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5012:                                   $env{'user.name'});
                   5013:     my %ccrole = ();
                   5014:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5015:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5016:     &appenv(\%userroles,[$role,'cm']);
                   5017:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5018:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5019:         &appenv( {'request.role'        => $spec,
                   5020:                   'request.role.domain' => $dcdom,
                   5021:                   'request.course.sec'  => ''
                   5022:                  }
                   5023:                );
                   5024:         my $tadv=0;
                   5025:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5026:         &appenv({'request.role.adv'    => $tadv});
                   5027:     }
1.994     raeburn  5028: }
                   5029: 
1.12      www      5030: # --------------------------------------------------------------- get interface
                   5031: 
                   5032: sub get {
1.131     albertel 5033:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5034:    my $items='';
1.800     albertel 5035:    foreach my $item (@$storearr) {
                   5036:        $items.=&escape($item).'&';
1.191     harris41 5037:    }
1.12      www      5038:    $items=~s/\&$//;
1.620     albertel 5039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5040:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5041:    my $uhome=&homeserver($uname,$udomain);
                   5042: 
1.133     albertel 5043:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5044:    my @pairs=split(/\&/,$rep);
1.273     albertel 5045:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5046:      return @pairs;
                   5047:    }
1.15      www      5048:    my %returnhash=();
1.42      www      5049:    my $i=0;
1.800     albertel 5050:    foreach my $item (@$storearr) {
                   5051:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5052:       $i++;
1.191     harris41 5053:    }
1.15      www      5054:    return %returnhash;
1.27      www      5055: }
                   5056: 
                   5057: # --------------------------------------------------------------- del interface
                   5058: 
                   5059: sub del {
1.133     albertel 5060:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5061:    my $items='';
1.800     albertel 5062:    foreach my $item (@$storearr) {
                   5063:        $items.=&escape($item).'&';
1.191     harris41 5064:    }
1.984     neumanie 5065: 
1.27      www      5066:    $items=~s/\&$//;
1.620     albertel 5067:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5068:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5069:    my $uhome=&homeserver($uname,$udomain);
                   5070:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5071: }
                   5072: 
                   5073: # -------------------------------------------------------------- dump interface
                   5074: 
                   5075: sub dump {
1.1086    raeburn  5076:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 5077:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5078:     if (!$uname) { $uname=$env{'user.name'}; }
                   5079:     my $uhome=&homeserver($uname,$udomain);
                   5080:     if ($regexp) {
                   5081: 	$regexp=&escape($regexp);
                   5082:     } else {
                   5083: 	$regexp='.';
                   5084:     }
1.1086    raeburn  5085:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 5086:     my @pairs=split(/\&/,$rep);
                   5087:     my %returnhash=();
1.1098    foxr     5088:     if (!($rep =~ /^error/ )) {
                   5089: 	foreach my $item (@pairs) {
                   5090: 	    my ($key,$value)=split(/=/,$item,2);
                   5091: 	    $key = &unescape($key);
                   5092: 	    next if ($key =~ /^error: 2 /);
                   5093: 	    $returnhash{$key}=&thaw_unescape($value);
                   5094: 	}
1.755     albertel 5095:     }
                   5096:     return %returnhash;
1.407     www      5097: }
                   5098: 
1.1098    foxr     5099: 
1.717     albertel 5100: # --------------------------------------------------------- dumpstore interface
                   5101: 
                   5102: sub dumpstore {
                   5103:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5105:    if (!$uname) { $uname=$env{'user.name'}; }
                   5106:    my $uhome=&homeserver($uname,$udomain);
                   5107:    if ($regexp) {
                   5108:        $regexp=&escape($regexp);
                   5109:    } else {
                   5110:        $regexp='.';
                   5111:    }
                   5112:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5113:    my @pairs=split(/\&/,$rep);
                   5114:    my %returnhash=();
                   5115:    foreach my $item (@pairs) {
                   5116:        my ($key,$value)=split(/=/,$item,2);
                   5117:        next if ($key =~ /^error: 2 /);
                   5118:        $returnhash{$key}=&thaw_unescape($value);
                   5119:    }
                   5120:    return %returnhash;
1.717     albertel 5121: }
                   5122: 
1.407     www      5123: # -------------------------------------------------------------- keys interface
                   5124: 
                   5125: sub getkeys {
                   5126:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5127:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5128:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5129:    my $uhome=&homeserver($uname,$udomain);
                   5130:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5131:    my @keyarray=();
1.800     albertel 5132:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5133:       next if ($key =~ /^error: 2 /);
1.800     albertel 5134:       push(@keyarray,&unescape($key));
1.407     www      5135:    }
                   5136:    return @keyarray;
1.318     matthew  5137: }
                   5138: 
1.319     matthew  5139: # --------------------------------------------------------------- currentdump
                   5140: sub currentdump {
1.328     matthew  5141:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5142:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5143:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5144:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5145:    my $uhome = &homeserver($sname,$sdom);
                   5146:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5147:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5148:    #
1.318     matthew  5149:    my %returnhash=();
1.319     matthew  5150:    #
                   5151:    if ($rep eq "unknown_cmd") { 
                   5152:        # an old lond will not know currentdump
                   5153:        # Do a dump and make it look like a currentdump
1.822     albertel 5154:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5155:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5156:        my %hash = @tmp;
                   5157:        @tmp=();
1.424     matthew  5158:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5159:    } else {
                   5160:        my @pairs=split(/\&/,$rep);
1.800     albertel 5161:        foreach my $pair (@pairs) {
                   5162:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5163:            my ($symb,$param) = split(/:/,$key);
                   5164:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5165:                                                         &thaw_unescape($value);
1.319     matthew  5166:        }
1.191     harris41 5167:    }
1.12      www      5168:    return %returnhash;
1.424     matthew  5169: }
                   5170: 
                   5171: sub convert_dump_to_currentdump{
                   5172:     my %hash = %{shift()};
                   5173:     my %returnhash;
                   5174:     # Code ripped from lond, essentially.  The only difference
                   5175:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5176:     # we might run in to problems with parameter names =~ /^v\./
                   5177:     while (my ($key,$value) = each(%hash)) {
                   5178:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5179: 	$symb  = &unescape($symb);
                   5180: 	$param = &unescape($param);
1.424     matthew  5181:         next if ($v eq 'version' || $symb eq 'keys');
                   5182:         next if (exists($returnhash{$symb}) &&
                   5183:                  exists($returnhash{$symb}->{$param}) &&
                   5184:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5185:         $returnhash{$symb}->{$param}=$value;
                   5186:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5187:     }
                   5188:     #
                   5189:     # Remove all of the keys in the hashes which keep track of
                   5190:     # the version of the parameter.
                   5191:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5192:         # use a foreach because we are going to delete from the hash.
                   5193:         foreach my $key (keys(%$param_hash)) {
                   5194:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5195:         }
                   5196:     }
                   5197:     return \%returnhash;
1.12      www      5198: }
                   5199: 
1.627     albertel 5200: # ------------------------------------------------------ critical inc interface
                   5201: 
                   5202: sub cinc {
                   5203:     return &inc(@_,'critical');
                   5204: }
                   5205: 
1.449     matthew  5206: # --------------------------------------------------------------- inc interface
                   5207: 
                   5208: sub inc {
1.627     albertel 5209:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5210:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5211:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5212:     my $uhome=&homeserver($uname,$udomain);
                   5213:     my $items='';
                   5214:     if (! ref($store)) {
                   5215:         # got a single value, so use that instead
                   5216:         $items = &escape($store).'=&';
                   5217:     } elsif (ref($store) eq 'SCALAR') {
                   5218:         $items = &escape($$store).'=&';        
                   5219:     } elsif (ref($store) eq 'ARRAY') {
                   5220:         $items = join('=&',map {&escape($_);} @{$store});
                   5221:     } elsif (ref($store) eq 'HASH') {
                   5222:         while (my($key,$value) = each(%{$store})) {
                   5223:             $items.= &escape($key).'='.&escape($value).'&';
                   5224:         }
                   5225:     }
                   5226:     $items=~s/\&$//;
1.627     albertel 5227:     if ($critical) {
                   5228: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5229:     } else {
                   5230: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5231:     }
1.449     matthew  5232: }
                   5233: 
1.12      www      5234: # --------------------------------------------------------------- put interface
                   5235: 
                   5236: sub put {
1.134     albertel 5237:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5239:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5240:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5241:    my $items='';
1.800     albertel 5242:    foreach my $item (keys(%$storehash)) {
                   5243:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5244:    }
1.12      www      5245:    $items=~s/\&$//;
1.134     albertel 5246:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5247: }
                   5248: 
1.631     albertel 5249: # ------------------------------------------------------------ newput interface
                   5250: 
                   5251: sub newput {
                   5252:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5254:    if (!$uname) { $uname=$env{'user.name'}; }
                   5255:    my $uhome=&homeserver($uname,$udomain);
                   5256:    my $items='';
                   5257:    foreach my $key (keys(%$storehash)) {
                   5258:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5259:    }
                   5260:    $items=~s/\&$//;
                   5261:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5262: }
                   5263: 
                   5264: # ---------------------------------------------------------  putstore interface
                   5265: 
1.524     raeburn  5266: sub putstore {
1.715     albertel 5267:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5268:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5269:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5270:    my $uhome=&homeserver($uname,$udomain);
                   5271:    my $items='';
1.715     albertel 5272:    foreach my $key (keys(%$storehash)) {
                   5273:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5274:    }
1.715     albertel 5275:    $items=~s/\&$//;
1.716     albertel 5276:    my $esc_symb=&escape($symb);
                   5277:    my $esc_v=&escape($version);
1.715     albertel 5278:    my $reply =
1.716     albertel 5279:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5280: 	      $uhome);
                   5281:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5282:        # gfall back to way things use to be done
1.715     albertel 5283:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5284: 			    $uname);
1.524     raeburn  5285:    }
1.715     albertel 5286:    return $reply;
                   5287: }
                   5288: 
                   5289: sub old_putstore {
1.716     albertel 5290:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5291:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5292:     if (!$uname) { $uname=$env{'user.name'}; }
                   5293:     my $uhome=&homeserver($uname,$udomain);
                   5294:     my %newstorehash;
1.800     albertel 5295:     foreach my $item (keys(%$storehash)) {
                   5296: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5297: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5298:     }
                   5299:     my $items='';
                   5300:     my %allitems = ();
1.800     albertel 5301:     foreach my $item (keys(%newstorehash)) {
                   5302: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5303: 	    my $key = $1.':keys:'.$2;
                   5304: 	    $allitems{$key} .= $3.':';
                   5305: 	}
1.800     albertel 5306: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5307:     }
1.800     albertel 5308:     foreach my $item (keys(%allitems)) {
                   5309: 	$allitems{$item} =~ s/\:$//;
                   5310: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5311:     }
                   5312:     $items=~s/\&$//;
                   5313:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5314: }
                   5315: 
1.47      www      5316: # ------------------------------------------------------ critical put interface
                   5317: 
                   5318: sub cput {
1.134     albertel 5319:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5320:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5321:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5322:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5323:    my $items='';
1.800     albertel 5324:    foreach my $item (keys(%$storehash)) {
                   5325:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5326:    }
1.47      www      5327:    $items=~s/\&$//;
1.134     albertel 5328:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5329: }
                   5330: 
                   5331: # -------------------------------------------------------------- eget interface
                   5332: 
                   5333: sub eget {
1.133     albertel 5334:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5335:    my $items='';
1.800     albertel 5336:    foreach my $item (@$storearr) {
                   5337:        $items.=&escape($item).'&';
1.191     harris41 5338:    }
1.12      www      5339:    $items=~s/\&$//;
1.620     albertel 5340:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5341:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5342:    my $uhome=&homeserver($uname,$udomain);
                   5343:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5344:    my @pairs=split(/\&/,$rep);
                   5345:    my %returnhash=();
1.42      www      5346:    my $i=0;
1.800     albertel 5347:    foreach my $item (@$storearr) {
                   5348:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5349:       $i++;
1.191     harris41 5350:    }
1.12      www      5351:    return %returnhash;
                   5352: }
                   5353: 
1.667     albertel 5354: # ------------------------------------------------------------ tmpput interface
                   5355: sub tmpput {
1.802     raeburn  5356:     my ($storehash,$server,$context)=@_;
1.667     albertel 5357:     my $items='';
1.800     albertel 5358:     foreach my $item (keys(%$storehash)) {
                   5359: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5360:     }
                   5361:     $items=~s/\&$//;
1.802     raeburn  5362:     if (defined($context)) {
                   5363:         $items .= ':'.&escape($context);
                   5364:     }
1.667     albertel 5365:     return &reply("tmpput:$items",$server);
                   5366: }
                   5367: 
                   5368: # ------------------------------------------------------------ tmpget interface
                   5369: sub tmpget {
1.688     albertel 5370:     my ($token,$server)=@_;
                   5371:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5372:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5373:     my %returnhash;
                   5374:     foreach my $item (split(/\&/,$rep)) {
                   5375: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5376:         next if ($key =~ /^error: 2 /);
1.667     albertel 5377: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5378:     }
                   5379:     return %returnhash;
                   5380: }
                   5381: 
1.1113    raeburn  5382: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5383: sub tmpdel {
                   5384:     my ($token,$server)=@_;
                   5385:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5386:     return &reply("tmpdel:$token",$server);
                   5387: }
                   5388: 
1.765     albertel 5389: # -------------------------------------------------- portfolio access checking
                   5390: 
                   5391: sub portfolio_access {
1.766     albertel 5392:     my ($requrl) = @_;
1.765     albertel 5393:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5394:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5395:     if ($result) {
                   5396:         my %setters;
                   5397:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5398:             my ($startblock,$endblock) =
                   5399:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5400:             if ($startblock && $endblock) {
                   5401:                 return 'B';
                   5402:             }
                   5403:         } else {
                   5404:             my ($startblock,$endblock) =
                   5405:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5406:             if ($startblock && $endblock) {
                   5407:                 return 'B';
                   5408:             }
                   5409:         }
                   5410:     }
1.765     albertel 5411:     if ($result eq 'ok') {
1.766     albertel 5412:        return 'F';
1.765     albertel 5413:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5414:        return 'A';
1.765     albertel 5415:     }
1.766     albertel 5416:     return '';
1.765     albertel 5417: }
                   5418: 
                   5419: sub get_portfolio_access {
1.767     albertel 5420:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5421: 
                   5422:     if (!ref($access_hash)) {
                   5423: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5424: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5425: 						   $file_name);
                   5426: 	$access_hash = $access_controls{$file_name};
                   5427:     }
                   5428: 
1.765     albertel 5429:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5430:     my $now = time;
                   5431:     if (ref($access_hash) eq 'HASH') {
                   5432:         foreach my $key (keys(%{$access_hash})) {
                   5433:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5434:             if ($start > $now) {
                   5435:                 next;
                   5436:             }
                   5437:             if ($end && $end<$now) {
                   5438:                 next;
                   5439:             }
                   5440:             if ($scope eq 'public') {
                   5441:                 $public = $key;
                   5442:                 last;
                   5443:             } elsif ($scope eq 'guest') {
                   5444:                 $guest = $key;
                   5445:             } elsif ($scope eq 'domains') {
                   5446:                 push(@domains,$key);
                   5447:             } elsif ($scope eq 'users') {
                   5448:                 push(@users,$key);
                   5449:             } elsif ($scope eq 'course') {
                   5450:                 push(@courses,$key);
                   5451:             } elsif ($scope eq 'group') {
                   5452:                 push(@groups,$key);
                   5453:             }
                   5454:         }
                   5455:         if ($public) {
                   5456:             return 'ok';
                   5457:         }
                   5458:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5459:             if ($guest) {
                   5460:                 return $guest;
                   5461:             }
                   5462:         } else {
                   5463:             if (@domains > 0) {
                   5464:                 foreach my $domkey (@domains) {
                   5465:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5466:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5467:                             return 'ok';
                   5468:                         }
                   5469:                     }
                   5470:                 }
                   5471:             }
                   5472:             if (@users > 0) {
                   5473:                 foreach my $userkey (@users) {
1.865     raeburn  5474:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5475:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5476:                             if (ref($item) eq 'HASH') {
                   5477:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5478:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5479:                                     return 'ok';
                   5480:                                 }
                   5481:                             }
                   5482:                         }
                   5483:                     } 
1.765     albertel 5484:                 }
                   5485:             }
                   5486:             my %roleshash;
                   5487:             my @courses_and_groups = @courses;
                   5488:             push(@courses_and_groups,@groups); 
                   5489:             if (@courses_and_groups > 0) {
                   5490:                 my (%allgroups,%allroles); 
                   5491:                 my ($start,$end,$role,$sec,$group);
                   5492:                 foreach my $envkey (%env) {
1.1060    raeburn  5493:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5494:                         my $cid = $2.'_'.$3; 
                   5495:                         if ($1 eq 'gr') {
                   5496:                             $group = $4;
                   5497:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5498:                         } else {
                   5499:                             if ($4 eq '') {
                   5500:                                 $sec = 'none';
                   5501:                             } else {
                   5502:                                 $sec = $4;
                   5503:                             }
                   5504:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5505:                         }
1.811     albertel 5506:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5507:                         my $cid = $2.'_'.$3;
                   5508:                         if ($4 eq '') {
                   5509:                             $sec = 'none';
                   5510:                         } else {
                   5511:                             $sec = $4;
                   5512:                         }
                   5513:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5514:                     }
                   5515:                 }
                   5516:                 if (keys(%allroles) == 0) {
                   5517:                     return;
                   5518:                 }
                   5519:                 foreach my $key (@courses_and_groups) {
                   5520:                     my %content = %{$$access_hash{$key}};
                   5521:                     my $cnum = $content{'number'};
                   5522:                     my $cdom = $content{'domain'};
                   5523:                     my $cid = $cdom.'_'.$cnum;
                   5524:                     if (!exists($allroles{$cid})) {
                   5525:                         next;
                   5526:                     }    
                   5527:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5528:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5529:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5530:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5531:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5532:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5533:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5534:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5535:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5536:                                         if (grep/^all$/,@sections) {
                   5537:                                             return 'ok';
                   5538:                                         } else {
                   5539:                                             if (grep/^$sec$/,@sections) {
                   5540:                                                 return 'ok';
                   5541:                                             }
                   5542:                                         }
                   5543:                                     }
                   5544:                                 }
                   5545:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5546:                                     if (grep/^none$/,@groups) {
                   5547:                                         return 'ok';
                   5548:                                     }
                   5549:                                 } else {
                   5550:                                     if (grep/^all$/,@groups) {
                   5551:                                         return 'ok';
                   5552:                                     } 
                   5553:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5554:                                         if (grep/^$group$/,@groups) {
                   5555:                                             return 'ok';
                   5556:                                         }
                   5557:                                     }
                   5558:                                 } 
                   5559:                             }
                   5560:                         }
                   5561:                     }
                   5562:                 }
                   5563:             }
                   5564:             if ($guest) {
                   5565:                 return $guest;
                   5566:             }
                   5567:         }
                   5568:     }
                   5569:     return;
                   5570: }
                   5571: 
                   5572: sub course_group_datechecker {
                   5573:     my ($dates,$now,$status) = @_;
                   5574:     my ($start,$end) = split(/\./,$dates);
                   5575:     if (!$start && !$end) {
                   5576:         return 'ok';
                   5577:     }
                   5578:     if (grep/^active$/,@{$status}) {
                   5579:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5580:             return 'ok';
                   5581:         }
                   5582:     }
                   5583:     if (grep/^previous$/,@{$status}) {
                   5584:         if ($end > $now ) {
                   5585:             return 'ok';
                   5586:         }
                   5587:     }
                   5588:     if (grep/^future$/,@{$status}) {
                   5589:         if ($start > $now) {
                   5590:             return 'ok';
                   5591:         }
                   5592:     }
                   5593:     return; 
                   5594: }
                   5595: 
                   5596: sub parse_portfolio_url {
                   5597:     my ($url) = @_;
                   5598: 
                   5599:     my ($type,$udom,$unum,$group,$file_name);
                   5600:     
1.823     albertel 5601:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5602: 	$type = 1;
                   5603:         $udom = $1;
                   5604:         $unum = $2;
                   5605:         $file_name = $3;
1.823     albertel 5606:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5607: 	$type = 2;
                   5608:         $udom = $1;
                   5609:         $unum = $2;
                   5610:         $group = $3;
                   5611:         $file_name = $3.'/'.$4;
                   5612:     }
                   5613:     if (wantarray) {
                   5614: 	return ($type,$udom,$unum,$file_name,$group);
                   5615:     }
                   5616:     return $type;
                   5617: }
                   5618: 
                   5619: sub is_portfolio_url {
                   5620:     my ($url) = @_;
                   5621:     return scalar(&parse_portfolio_url($url));
                   5622: }
                   5623: 
1.798     raeburn  5624: sub is_portfolio_file {
                   5625:     my ($file) = @_;
1.820     raeburn  5626:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5627:         return 1;
                   5628:     }
                   5629:     return;
                   5630: }
                   5631: 
1.976     raeburn  5632: sub usertools_access {
1.1084    raeburn  5633:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5634:     my ($access,%tools);
                   5635:     if ($context eq '') {
                   5636:         $context = 'tools';
                   5637:     }
                   5638:     if ($context eq 'requestcourses') {
                   5639:         %tools = (
                   5640:                       official   => 1,
                   5641:                       unofficial => 1,
1.1006    raeburn  5642:                       community  => 1,
1.985     raeburn  5643:                  );
                   5644:     } else {
                   5645:         %tools = (
                   5646:                       aboutme   => 1,
                   5647:                       blog      => 1,
                   5648:                       portfolio => 1,
                   5649:                  );
                   5650:     }
1.976     raeburn  5651:     return if (!defined($tools{$tool}));
                   5652: 
                   5653:     if ((!defined($udom)) || (!defined($uname))) {
                   5654:         $udom = $env{'user.domain'};
                   5655:         $uname = $env{'user.name'};
                   5656:     }
                   5657: 
1.978     raeburn  5658:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5659:         if ($action ne 'reload') {
1.985     raeburn  5660:             if ($context eq 'requestcourses') {
                   5661:                 return $env{'environment.canrequest.'.$tool};
                   5662:             } else {
                   5663:                 return $env{'environment.availabletools.'.$tool};
                   5664:             }
                   5665:         }
1.976     raeburn  5666:     }
                   5667: 
                   5668:     my ($toolstatus,$inststatus);
                   5669: 
1.985     raeburn  5670:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5671:          ($action ne 'reload')) {
                   5672:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5673:         $inststatus = $env{'environment.inststatus'};
                   5674:     } else {
1.1084    raeburn  5675:         if (ref($userenvref) eq 'HASH') {
                   5676:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5677:             $inststatus = $userenvref->{'inststatus'};
                   5678:         } else {
                   5679:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5680:             $toolstatus = $userenv{$context.'.'.$tool};
                   5681:             $inststatus = $userenv{'inststatus'};
                   5682:         }
1.976     raeburn  5683:     }
                   5684: 
                   5685:     if ($toolstatus ne '') {
                   5686:         if ($toolstatus) {
                   5687:             $access = 1;
                   5688:         } else {
                   5689:             $access = 0;
                   5690:         }
                   5691:         return $access;
                   5692:     }
                   5693: 
1.1084    raeburn  5694:     my ($is_adv,%domdef);
                   5695:     if (ref($is_advref) eq 'HASH') {
                   5696:         $is_adv = $is_advref->{'is_adv'};
                   5697:     } else {
                   5698:         $is_adv = &is_advanced_user($udom,$uname);
                   5699:     }
                   5700:     if (ref($domdefref) eq 'HASH') {
                   5701:         %domdef = %{$domdefref};
                   5702:     } else {
                   5703:         %domdef = &get_domain_defaults($udom);
                   5704:     }
1.976     raeburn  5705:     if (ref($domdef{$tool}) eq 'HASH') {
                   5706:         if ($is_adv) {
                   5707:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5708:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5709:                     $access = 1;
                   5710:                 } else {
                   5711:                     $access = 0;
                   5712:                 }
                   5713:                 return $access;
                   5714:             }
                   5715:         }
                   5716:         if ($inststatus ne '') {
                   5717:             my ($hasaccess,$hasnoaccess);
                   5718:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5719:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5720:                     if ($domdef{$tool}{$affiliation}) {
                   5721:                         $hasaccess = 1;
                   5722:                     } else {
                   5723:                         $hasnoaccess = 1;
                   5724:                     }
                   5725:                 }
                   5726:             }
                   5727:             if ($hasaccess || $hasnoaccess) {
                   5728:                 if ($hasaccess) {
                   5729:                     $access = 1;
                   5730:                 } elsif ($hasnoaccess) {
                   5731:                     $access = 0; 
                   5732:                 }
                   5733:                 return $access;
                   5734:             }
                   5735:         } else {
                   5736:             if ($domdef{$tool}{'default'} ne '') {
                   5737:                 if ($domdef{$tool}{'default'}) {
                   5738:                     $access = 1;
                   5739:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5740:                     $access = 0;
                   5741:                 }
                   5742:                 return $access;
                   5743:             }
                   5744:         }
                   5745:     } else {
1.985     raeburn  5746:         if ($context eq 'tools') {
                   5747:             $access = 1;
                   5748:         } else {
                   5749:             $access = 0;
                   5750:         }
1.976     raeburn  5751:         return $access;
                   5752:     }
                   5753: }
                   5754: 
1.1050    raeburn  5755: sub is_course_owner {
                   5756:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5757:     if (($udom eq '') || ($uname eq '')) {
                   5758:         $udom = $env{'user.domain'};
                   5759:         $uname = $env{'user.name'};
                   5760:     }
                   5761:     unless (($udom eq '') || ($uname eq '')) {
                   5762:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5763:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5764:                 return 1;
                   5765:             } else {
                   5766:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5767:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5768:                     return 1;
                   5769:                 }
                   5770:             }
                   5771:         }
                   5772:     }
                   5773:     return;
                   5774: }
                   5775: 
1.976     raeburn  5776: sub is_advanced_user {
                   5777:     my ($udom,$uname) = @_;
1.1085    raeburn  5778:     if ($udom ne '' && $uname ne '') {
                   5779:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5780:             if (wantarray) {
                   5781:                 return ($env{'user.adv'},$env{'user.author'});
                   5782:             } else {
                   5783:                 return $env{'user.adv'};
                   5784:             }
1.1085    raeburn  5785:         }
                   5786:     }
1.976     raeburn  5787:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5788:     my %allroles;
1.1128    raeburn  5789:     my ($is_adv,$is_author);
1.976     raeburn  5790:     foreach my $role (keys(%roleshash)) {
                   5791:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5792:         my $area = '/'.$tdomain.'/'.$trest;
                   5793:         if ($sec ne '') {
                   5794:             $area .= '/'.$sec;
                   5795:         }
                   5796:         if (($area ne '') && ($trole ne '')) {
                   5797:             my $spec=$trole.'.'.$area;
                   5798:             if ($trole =~ /^cr\//) {
                   5799:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5800:             } elsif ($trole ne 'gr') {
                   5801:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5802:             }
1.1128    raeburn  5803:             if ($trole eq 'au') {
                   5804:                 $is_author = 1;
                   5805:             }
1.976     raeburn  5806:         }
                   5807:     }
                   5808:     foreach my $role (keys(%allroles)) {
                   5809:         last if ($is_adv);
                   5810:         foreach my $item (split(/:/,$allroles{$role})) {
                   5811:             if ($item ne '') {
                   5812:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5813:                 if ($privilege eq 'adv') {
                   5814:                     $is_adv = 1;
                   5815:                     last;
                   5816:                 }
                   5817:             }
                   5818:         }
                   5819:     }
1.1128    raeburn  5820:     if (wantarray) {
                   5821:         return ($is_adv,$is_author);
                   5822:     }
1.976     raeburn  5823:     return $is_adv;
                   5824: }
1.798     raeburn  5825: 
1.1035    raeburn  5826: sub check_can_request {
1.1036    raeburn  5827:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5828:     my $canreq = 0;
                   5829:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5830:     my @options = ('approval','validate','autolimit');
                   5831:     my $optregex = join('|',@options);
                   5832:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5833:         foreach my $type (@{$types}) {
                   5834:             if (&usertools_access($env{'user.name'},
                   5835:                                   $env{'user.domain'},
                   5836:                                   $type,undef,'requestcourses')) {
                   5837:                 $canreq ++;
1.1036    raeburn  5838:                 if (ref($request_domains) eq 'HASH') {
                   5839:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5840:                 }
1.1035    raeburn  5841:                 if ($dom eq $env{'user.domain'}) {
                   5842:                     $can_request->{$type} = 1;
                   5843:                 }
                   5844:             }
                   5845:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5846:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5847:                 if (@curr > 0) {
1.1036    raeburn  5848:                     foreach my $item (@curr) {
                   5849:                         if (ref($request_domains) eq 'HASH') {
                   5850:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5851:                             if ($otherdom ne '') {
                   5852:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5853:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5854:                                         push(@{$request_domains->{$type}},$otherdom);
                   5855:                                     }
                   5856:                                 } else {
                   5857:                                     push(@{$request_domains->{$type}},$otherdom);
                   5858:                                 }
                   5859:                             }
                   5860:                         }
                   5861:                     }
                   5862:                     unless($dom eq $env{'user.domain'}) {
                   5863:                         $canreq ++;
1.1035    raeburn  5864:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5865:                             $can_request->{$type} = 1;
                   5866:                         }
                   5867:                     }
                   5868:                 }
                   5869:             }
                   5870:         }
                   5871:     }
                   5872:     return $canreq;
                   5873: }
                   5874: 
1.341     www      5875: # ---------------------------------------------- Custom access rule evaluation
                   5876: 
                   5877: sub customaccess {
                   5878:     my ($priv,$uri)=@_;
1.807     albertel 5879:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5880:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5881:     $udom = &LONCAPA::clean_domain($udom);
                   5882:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5883:     my $access=0;
1.800     albertel 5884:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5885: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5886: 	if ($type eq 'user') {
                   5887: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5888: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5889: 		if ($tdom) {
                   5890: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5891: 		}
1.896     albertel 5892: 		if ($tuname) {
                   5893: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5894: 		}
                   5895: 		$access=($effect eq 'allow');
                   5896: 		last;
                   5897: 	    }
                   5898: 	} else {
                   5899: 	    if ($role) {
                   5900: 		if ($role ne $urole) { next; }
                   5901: 	    }
                   5902: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5903: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5904: 		if ($tdom) {
                   5905: 		    if ($tdom ne $udom) { next; }
                   5906: 		}
                   5907: 		if ($tcrs) {
                   5908: 		    if ($tcrs ne $ucrs) { next; }
                   5909: 		}
                   5910: 		if ($tsec) {
                   5911: 		    if ($tsec ne $usec) { next; }
                   5912: 		}
                   5913: 		$access=($effect eq 'allow');
                   5914: 		last;
                   5915: 	    }
                   5916: 	    if ($realm eq '' && $role eq '') {
                   5917: 		$access=($effect eq 'allow');
                   5918: 	    }
1.402     bowersj2 5919: 	}
1.341     www      5920:     }
                   5921:     return $access;
                   5922: }
                   5923: 
1.103     harris41 5924: # ------------------------------------------------- Check for a user privilege
1.12      www      5925: 
                   5926: sub allowed {
1.810     raeburn  5927:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5928:     my $ver_orguri=$uri;
1.439     www      5929:     $uri=&deversion($uri);
1.152     www      5930:     my $orguri=$uri;
1.52      www      5931:     $uri=&declutter($uri);
1.809     raeburn  5932: 
1.810     raeburn  5933:     if ($priv eq 'evb') {
                   5934: # Evade communication block restrictions for specified role in a course
                   5935:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5936:             return $1;
                   5937:         } else {
                   5938:             return;
                   5939:         }
                   5940:     }
                   5941: 
1.620     albertel 5942:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5943: # Free bre access to adm and meta resources
1.775     albertel 5944:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5945: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5946: 	&& ($priv eq 'bre')) {
1.14      www      5947: 	return 'F';
1.159     www      5948:     }
                   5949: 
1.545     banghart 5950: # Free bre access to user's own portfolio contents
1.714     raeburn  5951:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5952:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5953: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5954:         my %setters;
                   5955:         my ($startblock,$endblock) = 
                   5956:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5957:         if ($startblock && $endblock) {
                   5958:             return 'B';
                   5959:         } else {
                   5960:             return 'F';
                   5961:         }
1.545     banghart 5962:     }
                   5963: 
1.762     raeburn  5964: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5965:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5966:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5967:         if (exists($env{'request.course.id'})) {
                   5968:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5969:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5970:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5971:                 my $courseprivid=$env{'request.course.id'};
                   5972:                 $courseprivid=~s/\_/\//;
                   5973:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5974:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5975:                     return $1; 
1.762     raeburn  5976:                 } else {
                   5977:                     if ($env{'request.course.sec'}) {
                   5978:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5979:                     }
                   5980:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5981:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5982:                         return $2;
                   5983:                     }
1.714     raeburn  5984:                 }
                   5985:             }
                   5986:         }
                   5987:     }
                   5988: 
1.159     www      5989: # Free bre to public access
                   5990: 
                   5991:     if ($priv eq 'bre') {
1.238     www      5992:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5993: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5994:            return 'F'; 
                   5995:         }
1.238     www      5996:         if ($copyright eq 'priv') {
                   5997:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5998: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5999: 		return '';
                   6000:             }
                   6001:         }
                   6002:         if ($copyright eq 'domain') {
                   6003:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6004: 	    unless (($env{'user.domain'} eq $1) ||
                   6005:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6006: 		return '';
                   6007:             }
1.262     matthew  6008:         }
1.620     albertel 6009:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6010:             # Library role, so allow browsing of resources in this domain.
                   6011:             return 'F';
1.238     www      6012:         }
1.341     www      6013:         if ($copyright eq 'custom') {
                   6014: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6015:         }
1.14      www      6016:     }
1.264     matthew  6017:     # Domain coordinator is trying to create a course
1.620     albertel 6018:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6019:         # uri is the requested domain in this case.
                   6020:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6021:         # a role of dc for the domain in question.
1.620     albertel 6022:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6023:     }
1.29      www      6024: 
1.52      www      6025:     my $thisallowed='';
                   6026:     my $statecond=0;
                   6027:     my $courseprivid='';
                   6028: 
1.1039    raeburn  6029:     my $ownaccess;
1.1043    raeburn  6030:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6031:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6032:         if ($uri eq '') {
                   6033:             $ownaccess = 1;
                   6034:         } else {
                   6035:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6036:                 my $udom = $env{'user.domain'};
                   6037:                 my $uname = $env{'user.name'};
                   6038:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6039:                     $ownaccess = 1;
1.1040    raeburn  6040:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6041:                     unless ($uri =~ m{\.\./}) {
                   6042:                         $ownaccess = 1;
                   6043:                     }
                   6044:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6045:                     my $now = time;
                   6046:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6047:                         my $adom = $1;
                   6048:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6049:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6050:                                 my ($start,$end) = split('.',$env{$key});
                   6051:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6052:                                     $ownaccess = 1;
                   6053:                                     last;
                   6054:                                 }
                   6055:                             }
                   6056:                         }
                   6057:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6058:                         my $adom = $1;
                   6059:                         my $aname = $2;
1.1042    raeburn  6060:                         foreach my $role ('ca','aa') { 
                   6061:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6062:                                 my ($start,$end) =
                   6063:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6064:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6065:                                     $ownaccess = 1;
                   6066:                                     last;
                   6067:                                 }
1.1039    raeburn  6068:                             }
                   6069:                         }
                   6070:                     }
                   6071:                 }
                   6072:             }
                   6073:         }
                   6074:     }
                   6075: 
1.52      www      6076: # Course
                   6077: 
1.620     albertel 6078:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6079:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6080:             $thisallowed.=$1;
                   6081:         }
1.52      www      6082:     }
1.29      www      6083: 
1.52      www      6084: # Domain
                   6085: 
1.620     albertel 6086:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6087:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6088:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6089:             $thisallowed.=$1;
                   6090:         }
1.12      www      6091:     }
1.52      www      6092: 
1.1141    raeburn  6093: # User who is not author or co-author might still be able to edit
                   6094: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6095:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6096:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6097:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6098:             $thisallowed.=$1;
                   6099:         }
                   6100:     }
                   6101: 
1.52      www      6102: # Course: uri itself is a course
1.66      www      6103:     my $courseuri=$uri;
                   6104:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6105:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6106: 
1.620     albertel 6107:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6108:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6109:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6110:             $thisallowed.=$1;
                   6111:         }
1.12      www      6112:     }
1.29      www      6113: 
1.665     albertel 6114: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6115: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6116:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6117: 	$thisallowed='';
1.671     raeburn  6118:         my ($match)=&is_on_map($uri);
                   6119:         if ($match) {
                   6120:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6121:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6122:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6123:                 if (@blockers > 0) {
                   6124:                     $thisallowed = 'B';
                   6125:                 } else {
                   6126:                     $thisallowed.=$1;
                   6127:                 }
1.671     raeburn  6128:             }
                   6129:         } else {
1.705     albertel 6130:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6131:             if ($refuri) {
                   6132:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6133:                     $thisallowed='F';
1.671     raeburn  6134:                 } else {
                   6135:                     $refuri=&declutter($refuri);
                   6136:                     my ($match) = &is_on_map($refuri);
                   6137:                     if ($match) {
1.1162    raeburn  6138:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6139:                         if (@blockers > 0) {
                   6140:                             $thisallowed = 'B';
                   6141:                         } else {
                   6142:                             $thisallowed='F';
                   6143:                         }
1.671     raeburn  6144:                     }
1.669     raeburn  6145:                 }
1.671     raeburn  6146:             }
                   6147:         }
1.314     www      6148:     }
1.492     albertel 6149: 
1.766     albertel 6150:     if ($priv eq 'bre'
                   6151: 	&& $thisallowed ne 'F' 
                   6152: 	&& $thisallowed ne '2'
                   6153: 	&& &is_portfolio_url($uri)) {
                   6154: 	$thisallowed = &portfolio_access($uri);
                   6155:     }
                   6156:     
1.52      www      6157: # Full access at system, domain or course-wide level? Exit.
1.29      www      6158:     if ($thisallowed=~/F/) {
                   6159: 	return 'F';
                   6160:     }
                   6161: 
1.52      www      6162: # If this is generating or modifying users, exit with special codes
1.29      www      6163: 
1.643     www      6164:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6165: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6166: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6167: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6168: 	    unless ($auname) { return $thisallowed; }
                   6169: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6170: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6171: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6172: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6173: 	}
1.52      www      6174: 	return $thisallowed;
                   6175:     }
                   6176: #
1.103     harris41 6177: # Gathered so far: system, domain and course wide privileges
1.52      www      6178: #
                   6179: # Course: See if uri or referer is an individual resource that is part of 
                   6180: # the course
                   6181: 
1.620     albertel 6182:     if ($env{'request.course.id'}) {
1.232     www      6183: 
1.620     albertel 6184:        $courseprivid=$env{'request.course.id'};
                   6185:        if ($env{'request.course.sec'}) {
                   6186:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6187:        }
                   6188:        $courseprivid=~s/\_/\//;
                   6189:        my $checkreferer=1;
1.232     www      6190:        my ($match,$cond)=&is_on_map($uri);
                   6191:        if ($match) {
                   6192:            $statecond=$cond;
1.620     albertel 6193:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6194:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6195:                my $value = $1;
                   6196:                if ($priv eq 'bre') {
                   6197:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6198:                    if (@blockers > 0) {
                   6199:                        $thisallowed = 'B';
                   6200:                    } else {
                   6201:                        $thisallowed.=$value;
                   6202:                    }
                   6203:                } else {
                   6204:                    $thisallowed.=$value;
                   6205:                }
1.52      www      6206:                $checkreferer=0;
                   6207:            }
1.29      www      6208:        }
1.83      www      6209:        
1.148     www      6210:        if ($checkreferer) {
1.620     albertel 6211: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6212:             unless ($refuri) {
1.800     albertel 6213:                 foreach my $key (keys(%env)) {
                   6214: 		    if ($key=~/^httpref\..*\*/) {
                   6215: 			my $pattern=$key;
1.156     www      6216:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6217:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6218:                         $pattern=~s/\//\\\//g;
1.152     www      6219:                         if ($orguri=~/$pattern/) {
1.800     albertel 6220: 			    $refuri=$env{$key};
1.148     www      6221:                         }
                   6222:                     }
1.191     harris41 6223:                 }
1.148     www      6224:             }
1.232     www      6225: 
1.148     www      6226:          if ($refuri) { 
1.152     www      6227: 	  $refuri=&declutter($refuri);
1.232     www      6228:           my ($match,$cond)=&is_on_map($refuri);
                   6229:             if ($match) {
                   6230:               my $refstatecond=$cond;
1.620     albertel 6231:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6232:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6233:                   my $value = $1;
                   6234:                   if ($priv eq 'bre') {
                   6235:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6236:                       if (@blockers > 0) {
                   6237:                           $thisallowed = 'B';
                   6238:                       } else {
                   6239:                           $thisallowed.=$value;
                   6240:                       }
                   6241:                   } else {
                   6242:                       $thisallowed.=$value;
                   6243:                   }
1.53      www      6244:                   $uri=$refuri;
                   6245:                   $statecond=$refstatecond;
1.52      www      6246:               }
                   6247:           }
1.148     www      6248:         }
1.29      www      6249:        }
1.52      www      6250:    }
1.29      www      6251: 
1.52      www      6252: #
1.103     harris41 6253: # Gathered now: all privileges that could apply, and condition number
1.52      www      6254: # 
                   6255: #
                   6256: # Full or no access?
                   6257: #
1.29      www      6258: 
1.52      www      6259:     if ($thisallowed=~/F/) {
                   6260: 	return 'F';
                   6261:     }
1.29      www      6262: 
1.52      www      6263:     unless ($thisallowed) {
                   6264:         return '';
                   6265:     }
1.29      www      6266: 
1.52      www      6267: # Restrictions exist, deal with them
                   6268: #
                   6269: #   C:according to course preferences
                   6270: #   R:according to resource settings
                   6271: #   L:unless locked
                   6272: #   X:according to user session state
                   6273: #
                   6274: 
                   6275: # Possibly locked functionality, check all courses
1.54      www      6276: # Locks might take effect only after 10 minutes cache expiration for other
                   6277: # courses, and 2 minutes for current course
1.52      www      6278: 
                   6279:     my $envkey;
                   6280:     if ($thisallowed=~/L/) {
1.1000    raeburn  6281:         foreach $envkey (keys(%env)) {
1.54      www      6282:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6283:                my $courseid=$2;
                   6284:                my $roleid=$1.'.'.$2;
1.92      www      6285:                $courseid=~s/^\///;
1.54      www      6286:                my $expiretime=600;
1.620     albertel 6287:                if ($env{'request.role'} eq $roleid) {
1.54      www      6288: 		  $expiretime=120;
                   6289:                }
                   6290: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6291:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6292:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6293: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6294:                }
1.620     albertel 6295:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6296:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6297: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6298:                        &log($env{'user.domain'},$env{'user.name'},
                   6299:                             $env{'user.home'},
1.57      www      6300:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6301:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6302:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6303: 		       return '';
                   6304:                    }
                   6305:                }
1.620     albertel 6306:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6307:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6308: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6309:                        &log($env{'user.domain'},$env{'user.name'},
                   6310:                             $env{'user.home'},
1.57      www      6311:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6312:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6313:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6314: 		       return '';
                   6315:                    }
                   6316:                }
                   6317: 	   }
1.29      www      6318:        }
1.52      www      6319:     }
                   6320:    
                   6321: #
                   6322: # Rest of the restrictions depend on selected course
                   6323: #
                   6324: 
1.620     albertel 6325:     unless ($env{'request.course.id'}) {
1.766     albertel 6326: 	if ($thisallowed eq 'A') {
                   6327: 	    return 'A';
1.814     raeburn  6328:         } elsif ($thisallowed eq 'B') {
                   6329:             return 'B';
1.766     albertel 6330: 	} else {
                   6331: 	    return '1';
                   6332: 	}
1.52      www      6333:     }
1.29      www      6334: 
1.52      www      6335: #
                   6336: # Now user is definitely in a course
                   6337: #
1.53      www      6338: 
                   6339: 
                   6340: # Course preferences
                   6341: 
                   6342:    if ($thisallowed=~/C/) {
1.620     albertel 6343:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6344:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6345:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6346: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6347: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6348: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6349: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6350: 			$env{'request.course.id'});
                   6351: 	   }
1.237     www      6352:            return '';
                   6353:        }
                   6354: 
1.620     albertel 6355:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6356: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6357: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6358: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6359: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6360: 			$env{'request.course.id'});
                   6361: 	   }
1.54      www      6362:            return '';
                   6363:        }
1.53      www      6364:    }
                   6365: 
                   6366: # Resource preferences
                   6367: 
                   6368:    if ($thisallowed=~/R/) {
1.620     albertel 6369:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6370:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6371: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6372: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6373: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6374: 	   }
                   6375: 	   return '';
1.54      www      6376:        }
1.53      www      6377:    }
1.30      www      6378: 
1.246     www      6379: # Restricted by state or randomout?
1.30      www      6380: 
1.52      www      6381:    if ($thisallowed=~/X/) {
1.620     albertel 6382:       if ($env{'acc.randomout'}) {
1.579     albertel 6383: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6384:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6385:             return ''; 
                   6386:          }
1.247     www      6387:       }
                   6388:       if (&condval($statecond)) {
1.52      www      6389: 	 return '2';
                   6390:       } else {
                   6391:          return '';
                   6392:       }
                   6393:    }
1.30      www      6394: 
1.766     albertel 6395:     if ($thisallowed eq 'A') {
                   6396: 	return 'A';
1.814     raeburn  6397:     } elsif ($thisallowed eq 'B') {
                   6398:         return 'B';
1.766     albertel 6399:     }
1.52      www      6400:    return 'F';
1.232     www      6401: }
1.1162    raeburn  6402: 
                   6403: sub get_comm_blocks {
                   6404:     my ($cdom,$cnum) = @_;
                   6405:     if ($cdom eq '' || $cnum eq '') {
                   6406:         return unless ($env{'request.course.id'});
                   6407:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6408:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6409:     }
                   6410:     my %commblocks;
                   6411:     my $hashid=$cdom.'_'.$cnum;
                   6412:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6413:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6414:         %commblocks = %{$blocksref};
                   6415:     } else {
                   6416:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6417:         my $cachetime = 600;
                   6418:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6419:     }
                   6420:     return %commblocks;
                   6421: }
                   6422: 
                   6423: sub has_comm_blocking {
                   6424:     my ($priv,$symb,$uri,$blocks) = @_;
                   6425:     return unless ($env{'request.course.id'});
                   6426:     return unless ($priv eq 'bre');
                   6427:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6428:     my %commblocks;
                   6429:     if (ref($blocks) eq 'HASH') {
                   6430:         %commblocks = %{$blocks};
                   6431:     } else {
                   6432:         %commblocks = &get_comm_blocks();
                   6433:     }
                   6434:     return unless (keys(%commblocks) > 0);
                   6435:     if (!$symb) { $symb=&symbread($uri,1); }
                   6436:     my ($map,$resid,undef)=&decode_symb($symb);
                   6437:     my %tocheck = (
                   6438:                     maps      => $map,
                   6439:                     resources => $symb,
                   6440:                   );
                   6441:     my @blockers;
                   6442:     my $now = time;
1.1163    raeburn  6443:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6444:     foreach my $block (keys(%commblocks)) {
                   6445:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6446:             my ($start,$end) = ($1,$2);
                   6447:             if ($start <= $now && $end >= $now) {
                   6448:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6449:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6450:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6451:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6452:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6453:                                     push(@blockers,$block);
                   6454:                                 }
                   6455:                             }
                   6456:                         }
                   6457:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6458:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6459:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6460:                                     push(@blockers,$block);
                   6461:                                 }
                   6462:                             }
                   6463:                         }
                   6464:                     }
                   6465:                 }
                   6466:             }
                   6467:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6468:             my $item = $1;
1.1163    raeburn  6469:             my @to_test;
1.1162    raeburn  6470:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6471:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6472:                     my $check_interval;
                   6473:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6474:                         my @interval;
                   6475:                         my $type = 'map';
                   6476:                         if ($item eq 'course') {
                   6477:                             $type = 'course';
                   6478:                             @interval=&EXT("resource.0.interval");
                   6479:                         } else {
                   6480:                             if ($item =~ /___\d+___/) {
                   6481:                                 $type = 'resource';
                   6482:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6483:                                 if (ref($navmap)) {                        
                   6484:                                     my $res = $navmap->getBySymb($item); 
                   6485:                                     push(@to_test,$res);
                   6486:                                 }
1.1162    raeburn  6487:                             } else {
                   6488:                                 my $mapsymb = &symbread($item,1);
                   6489:                                 if ($mapsymb) {
                   6490:                                     if (ref($navmap)) {
                   6491:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6492:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6493:                                         foreach my $res (@to_test) {
1.1162    raeburn  6494:                                             my $symb = $res->symb();
                   6495:                                             next if ($symb eq $mapsymb);
                   6496:                                             if ($symb ne '') {
                   6497:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6498:                                                 last;
                   6499:                                             }
                   6500:                                         }
                   6501:                                     }
                   6502:                                 }
                   6503:                             }
                   6504:                         }
                   6505:                         if ($interval[0] =~ /\d+/) {
                   6506:                             my $first_access;
                   6507:                             if ($type eq 'resource') {
                   6508:                                 $first_access=&get_first_access($interval[1],$item);
                   6509:                             } elsif ($type eq 'map') {
                   6510:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6511:                             } else {
                   6512:                                 $first_access=&get_first_access($interval[1]);
                   6513:                             }
                   6514:                             if ($first_access) {
                   6515:                                 my $timesup = $first_access+$interval[0];
                   6516:                                 if ($timesup > $now) {
1.1163    raeburn  6517:                                     foreach my $res (@to_test) {
                   6518:                                         if ($res->is_problem()) {
                   6519:                                             if ($res->completable()) {
                   6520:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6521:                                                     push(@blockers,$block);
                   6522:                                                 }
                   6523:                                                 last;
                   6524:                                             }
                   6525:                                         }
1.1162    raeburn  6526:                                     }
                   6527:                                 }
                   6528:                             }
                   6529:                         }
                   6530:                     }
                   6531:                 }
                   6532:             }
                   6533:         }
                   6534:     }
                   6535:     return @blockers;
                   6536: }
                   6537: 
                   6538: sub check_docs_block {
                   6539:     my ($docsblock,$tocheck) =@_;
                   6540:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6541:         return;
                   6542:     }
                   6543:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6544:         if ($tocheck->{'maps'}) {
                   6545:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6546:                 return 1;
                   6547:             }
                   6548:         }
                   6549:     }
                   6550:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6551:         if ($tocheck->{'resources'}) {
                   6552:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6553:                 return 1;
                   6554:             }
                   6555:         }
                   6556:     }
                   6557:     return;
                   6558: }
                   6559: 
1.1133    foxr     6560: #
                   6561: #   Removes the versino from a URI and
                   6562: #   splits it in to its filename and path to the filename.
                   6563: #   Seems like File::Basename could have done this more clearly.
                   6564: #   Parameters:
                   6565: #      $uri   - input URI
                   6566: #   Returns:
                   6567: #     Two element list consisting of 
                   6568: #     $pathname  - the URI up to and excluding the trailing /
                   6569: #     $filename  - The part of the URI following the last /
                   6570: #  NOTE:
                   6571: #    Another realization of this is simply:
                   6572: #    use File::Basename;
                   6573: #    ...
                   6574: #    $uri = shift;
                   6575: #    $filename = basename($uri);
                   6576: #    $path     = dirname($uri);
                   6577: #    return ($filename, $path);
                   6578: #
                   6579: #     The implementation below is probably faster however.
                   6580: #
1.710     albertel 6581: sub split_uri_for_cond {
                   6582:     my $uri=&deversion(&declutter(shift));
                   6583:     my @uriparts=split(/\//,$uri);
                   6584:     my $filename=pop(@uriparts);
                   6585:     my $pathname=join('/',@uriparts);
                   6586:     return ($pathname,$filename);
                   6587: }
1.232     www      6588: # --------------------------------------------------- Is a resource on the map?
                   6589: 
                   6590: sub is_on_map {
1.710     albertel 6591:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6592:     #Trying to find the conditional for the file
1.620     albertel 6593:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6594: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6595:     if ($match) {
1.289     bowersj2 6596: 	return (1,$1);
                   6597:     } else {
1.434     www      6598: 	return (0,0);
1.289     bowersj2 6599:     }
1.12      www      6600: }
                   6601: 
1.427     www      6602: # --------------------------------------------------------- Get symb from alias
                   6603: 
                   6604: sub get_symb_from_alias {
                   6605:     my $symb=shift;
                   6606:     my ($map,$resid,$url)=&decode_symb($symb);
                   6607: # Already is a symb
                   6608:     if ($url) { return $symb; }
                   6609: # Must be an alias
                   6610:     my $aliassymb='';
                   6611:     my %bighash;
1.620     albertel 6612:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6613:                             &GDBM_READER(),0640)) {
                   6614:         my $rid=$bighash{'mapalias_'.$symb};
                   6615: 	if ($rid) {
                   6616: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6617: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6618: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6619: 	}
                   6620:         untie %bighash;
                   6621:     }
                   6622:     return $aliassymb;
                   6623: }
                   6624: 
1.12      www      6625: # ----------------------------------------------------------------- Define Role
                   6626: 
                   6627: sub definerole {
                   6628:   if (allowed('mcr','/')) {
                   6629:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6630:     foreach my $role (split(':',$sysrole)) {
                   6631: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6632:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6633:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6634: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6635:                return "refused:s:$crole&$cqual"; 
                   6636:             }
                   6637:         }
1.191     harris41 6638:     }
1.800     albertel 6639:     foreach my $role (split(':',$domrole)) {
                   6640: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6641:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6642:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6643: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6644:                return "refused:d:$crole&$cqual"; 
                   6645:             }
                   6646:         }
1.191     harris41 6647:     }
1.800     albertel 6648:     foreach my $role (split(':',$courole)) {
                   6649: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6650:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6651:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6652: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6653:                return "refused:c:$crole&$cqual"; 
                   6654:             }
                   6655:         }
1.191     harris41 6656:     }
1.620     albertel 6657:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6658:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6659: 	        "rolesdef_$rolename=".
                   6660:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6661:     return reply($command,$env{'user.home'});
1.12      www      6662:   } else {
                   6663:     return 'refused';
                   6664:   }
1.105     harris41 6665: }
                   6666: 
                   6667: # ---------------- Make a metadata query against the network of library servers
                   6668: 
                   6669: sub metadata_query {
1.244     matthew  6670:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6671:     my %rhash;
1.845     albertel 6672:     my %libserv = &all_library();
1.244     matthew  6673:     my @server_list = (defined($server_array) ? @$server_array
                   6674:                                               : keys(%libserv) );
                   6675:     for my $server (@server_list) {
1.118     harris41 6676: 	unless ($custom or $customshow) {
                   6677: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6678: 	    $rhash{$server}=$reply;
                   6679: 	}
                   6680: 	else {
                   6681: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6682: 			     &escape($custom).':'.&escape($customshow),
                   6683: 			     $server);
                   6684: 	    $rhash{$server}=$reply;
                   6685: 	}
1.112     harris41 6686:     }
1.118     harris41 6687:     return \%rhash;
1.240     www      6688: }
                   6689: 
                   6690: # ----------------------------------------- Send log queries and wait for reply
                   6691: 
                   6692: sub log_query {
                   6693:     my ($uname,$udom,$query,%filters)=@_;
                   6694:     my $uhome=&homeserver($uname,$udom);
                   6695:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6696:     my $uhost=&hostname($uhome);
1.800     albertel 6697:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6698:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6699:                        $uhome);
1.479     albertel 6700:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6701:     return get_query_reply($queryid);
                   6702: }
                   6703: 
1.818     raeburn  6704: # -------------------------- Update MySQL table for portfolio file
                   6705: 
                   6706: sub update_portfolio_table {
1.821     raeburn  6707:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6708:     if ($group ne '') {
                   6709:         $file_name =~s /^\Q$group\E//;
                   6710:     }
1.818     raeburn  6711:     my $homeserver = &homeserver($uname,$udom);
                   6712:     my $queryid=
1.821     raeburn  6713:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6714:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6715:     my $reply = &get_query_reply($queryid);
                   6716:     return $reply;
                   6717: }
                   6718: 
1.899     raeburn  6719: # -------------------------- Update MySQL allusers table
                   6720: 
                   6721: sub update_allusers_table {
                   6722:     my ($uname,$udom,$names) = @_;
                   6723:     my $homeserver = &homeserver($uname,$udom);
                   6724:     my $queryid=
                   6725:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6726:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6727:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6728:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6729:                'generation='.&escape($names->{'generation'}).'%%'.
                   6730:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6731:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6732:     return;
1.899     raeburn  6733: }
                   6734: 
1.508     raeburn  6735: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6736: 
                   6737: sub fetch_enrollment_query {
1.511     raeburn  6738:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6739:     my $homeserver;
1.547     raeburn  6740:     my $maxtries = 1;
1.508     raeburn  6741:     if ($context eq 'automated') {
                   6742:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6743:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6744:     } else {
                   6745:         $homeserver = &homeserver($cnum,$dom);
                   6746:     }
1.838     albertel 6747:     my $host=&hostname($homeserver);
1.506     raeburn  6748:     my $cmd = '';
1.1000    raeburn  6749:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6750:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6751:     }
                   6752:     $cmd =~ s/%%$//;
                   6753:     $cmd = &escape($cmd);
                   6754:     my $query = 'fetchenrollment';
1.620     albertel 6755:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6756:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6757:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6758:         return 'error: '.$queryid;
                   6759:     }
1.506     raeburn  6760:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6761:     my $tries = 1;
                   6762:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6763:         $reply = &get_query_reply($queryid);
                   6764:         $tries ++;
                   6765:     }
1.526     raeburn  6766:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6767:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6768:     } else {
1.901     albertel 6769:         my @responses = split(/:/,$reply);
1.515     raeburn  6770:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6771:             foreach my $line (@responses) {
                   6772:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6773:                 $$replyref{$key} = $value;
                   6774:             }
                   6775:         } else {
1.1117    foxr     6776:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6777:             foreach my $line (@responses) {
                   6778:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6779:                 $$replyref{$key} = $value;
                   6780:                 if ($value > 0) {
1.800     albertel 6781:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6782:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6783:                         my $destname = $pathname.'/'.$filename;
                   6784:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6785:                         if ($xml_classlist =~ /^error/) {
                   6786:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6787:                         } else {
1.506     raeburn  6788:                             if ( open(FILE,">$destname") ) {
                   6789:                                 print FILE &unescape($xml_classlist);
                   6790:                                 close(FILE);
1.526     raeburn  6791:                             } else {
                   6792:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6793:                             }
                   6794:                         }
                   6795:                     }
                   6796:                 }
                   6797:             }
                   6798:         }
                   6799:         return 'ok';
                   6800:     }
                   6801:     return 'error';
                   6802: }
                   6803: 
1.242     www      6804: sub get_query_reply {
                   6805:     my $queryid=shift;
1.1117    foxr     6806:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6807:     my $reply='';
                   6808:     for (1..100) {
                   6809: 	sleep 2;
                   6810:         if (-e $replyfile.'.end') {
1.448     albertel 6811: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6812: 		$reply = join('',<$fh>);
                   6813: 		close($fh);
1.240     www      6814: 	   } else { return 'error: reply_file_error'; }
1.242     www      6815:            return &unescape($reply);
                   6816: 	}
1.240     www      6817:     }
1.242     www      6818:     return 'timeout:'.$queryid;
1.240     www      6819: }
                   6820: 
                   6821: sub courselog_query {
1.241     www      6822: #
                   6823: # possible filters:
                   6824: # url: url or symb
                   6825: # username
                   6826: # domain
                   6827: # action: view, submit, grade
                   6828: # start: timestamp
                   6829: # end: timestamp
                   6830: #
1.240     www      6831:     my (%filters)=@_;
1.620     albertel 6832:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6833:     if ($filters{'url'}) {
                   6834: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6835:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6836:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6837:     }
1.620     albertel 6838:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6839:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6840:     return &log_query($cname,$cdom,'courselog',%filters);
                   6841: }
                   6842: 
                   6843: sub userlog_query {
1.858     raeburn  6844: #
                   6845: # possible filters:
                   6846: # action: log check role
                   6847: # start: timestamp
                   6848: # end: timestamp
                   6849: #
1.240     www      6850:     my ($uname,$udom,%filters)=@_;
                   6851:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6852: }
                   6853: 
1.506     raeburn  6854: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6855: 
                   6856: sub auto_run {
1.508     raeburn  6857:     my ($cnum,$cdom) = @_;
1.876     raeburn  6858:     my $response = 0;
                   6859:     my $settings;
                   6860:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6861:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6862:         $settings = $domconfig{'autoenroll'};
                   6863:         if ($settings->{'run'} eq '1') {
                   6864:             $response = 1;
                   6865:         }
                   6866:     } else {
1.934     raeburn  6867:         my $homeserver;
                   6868:         if (&is_course($cdom,$cnum)) {
                   6869:             $homeserver = &homeserver($cnum,$cdom);
                   6870:         } else {
                   6871:             $homeserver = &domain($cdom,'primary');
                   6872:         }
                   6873:         if ($homeserver ne 'no_host') {
                   6874:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6875:         }
1.876     raeburn  6876:     }
1.506     raeburn  6877:     return $response;
                   6878: }
1.776     albertel 6879: 
1.506     raeburn  6880: sub auto_get_sections {
1.508     raeburn  6881:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6882:     my $homeserver;
                   6883:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6884:         $homeserver = &homeserver($cnum,$cdom);
                   6885:     }
                   6886:     if (!defined($homeserver)) { 
                   6887:         if ($cdom =~ /^$match_domain$/) {
                   6888:             $homeserver = &domain($cdom,'primary');
                   6889:         }
                   6890:     }
                   6891:     my @secs;
                   6892:     if (defined($homeserver)) {
                   6893:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6894:         unless ($response eq 'refused') {
                   6895:             @secs = split(/:/,$response);
                   6896:         }
1.506     raeburn  6897:     }
                   6898:     return @secs;
                   6899: }
1.776     albertel 6900: 
1.506     raeburn  6901: sub auto_new_course {
1.1099    raeburn  6902:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6903:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6904:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6905:     return $response;
                   6906: }
1.776     albertel 6907: 
1.506     raeburn  6908: sub auto_validate_courseID {
1.508     raeburn  6909:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6910:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6911:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6912:     return $response;
                   6913: }
1.776     albertel 6914: 
1.1007    raeburn  6915: sub auto_validate_instcode {
1.1020    raeburn  6916:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6917:     my ($homeserver,$response);
                   6918:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6919:         $homeserver = &homeserver($cnum,$cdom);
                   6920:     }
                   6921:     if (!defined($homeserver)) {
                   6922:         if ($cdom =~ /^$match_domain$/) {
                   6923:             $homeserver = &domain($cdom,'primary');
                   6924:         }
                   6925:     }
1.1065    raeburn  6926:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6927:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6928:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6929:     return ($outcome,$description);
1.1007    raeburn  6930: }
                   6931: 
1.506     raeburn  6932: sub auto_create_password {
1.873     raeburn  6933:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6934:     my ($homeserver,$response);
1.506     raeburn  6935:     my $create_passwd = 0;
                   6936:     my $authchk = '';
1.873     raeburn  6937:     if ($udom =~ /^$match_domain$/) {
                   6938:         $homeserver = &domain($udom,'primary');
                   6939:     }
                   6940:     if ($homeserver eq '') {
                   6941:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6942:             $homeserver = &homeserver($cnum,$cdom);
                   6943:         }
                   6944:     }
                   6945:     if ($homeserver eq '') {
                   6946:         $authchk = 'nodomain';
1.506     raeburn  6947:     } else {
1.873     raeburn  6948:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6949:         if ($response eq 'refused') {
                   6950:             $authchk = 'refused';
                   6951:         } else {
1.901     albertel 6952:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6953:         }
1.506     raeburn  6954:     }
                   6955:     return ($authparam,$create_passwd,$authchk);
                   6956: }
                   6957: 
1.706     raeburn  6958: sub auto_photo_permission {
                   6959:     my ($cnum,$cdom,$students) = @_;
                   6960:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6961:     my ($outcome,$perm_reqd,$conditions) = 
                   6962: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6963:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6964: 	return (undef,undef);
                   6965:     }
1.706     raeburn  6966:     return ($outcome,$perm_reqd,$conditions);
                   6967: }
                   6968: 
                   6969: sub auto_checkphotos {
                   6970:     my ($uname,$udom,$pid) = @_;
                   6971:     my $homeserver = &homeserver($uname,$udom);
                   6972:     my ($result,$resulttype);
                   6973:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6974: 				   &escape($uname).':'.&escape($pid),
                   6975: 				   $homeserver));
1.709     albertel 6976:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6977: 	return (undef,undef);
                   6978:     }
1.706     raeburn  6979:     if ($outcome) {
                   6980:         ($result,$resulttype) = split(/:/,$outcome);
                   6981:     } 
                   6982:     return ($result,$resulttype);
                   6983: }
                   6984: 
                   6985: sub auto_photochoice {
                   6986:     my ($cnum,$cdom) = @_;
                   6987:     my $homeserver = &homeserver($cnum,$cdom);
                   6988:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6989: 						       &escape($cdom),
                   6990: 						       $homeserver)));
1.709     albertel 6991:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6992: 	return (undef,undef);
                   6993:     }
1.706     raeburn  6994:     return ($update,$comment);
                   6995: }
                   6996: 
                   6997: sub auto_photoupdate {
                   6998:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6999:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7000:     my $host=&hostname($homeserver);
1.706     raeburn  7001:     my $cmd = '';
                   7002:     my $maxtries = 1;
1.800     albertel 7003:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7004:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7005:     }
                   7006:     $cmd =~ s/%%$//;
                   7007:     $cmd = &escape($cmd);
                   7008:     my $query = 'institutionalphotos';
                   7009:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7010:     unless ($queryid=~/^\Q$host\E\_/) {
                   7011:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7012:         return 'error: '.$queryid;
                   7013:     }
                   7014:     my $reply = &get_query_reply($queryid);
                   7015:     my $tries = 1;
                   7016:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7017:         $reply = &get_query_reply($queryid);
                   7018:         $tries ++;
                   7019:     }
                   7020:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7021:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7022:     } else {
                   7023:         my @responses = split(/:/,$reply);
                   7024:         my $outcome = shift(@responses); 
                   7025:         foreach my $item (@responses) {
                   7026:             my ($key,$value) = split(/=/,$item);
                   7027:             $$photo{$key} = $value;
                   7028:         }
                   7029:         return $outcome;
                   7030:     }
                   7031:     return 'error';
                   7032: }
                   7033: 
1.521     raeburn  7034: sub auto_instcode_format {
1.793     albertel 7035:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7036: 	$cat_order) = @_;
1.521     raeburn  7037:     my $courses = '';
1.772     raeburn  7038:     my @homeservers;
1.521     raeburn  7039:     if ($caller eq 'global') {
1.841     albertel 7040: 	my %servers = &get_servers($codedom,'library');
                   7041: 	foreach my $tryserver (keys(%servers)) {
                   7042: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7043: 		push(@homeservers,$tryserver);
                   7044: 	    }
1.584     raeburn  7045:         }
1.1022    raeburn  7046:     } elsif ($caller eq 'requests') {
                   7047:         if ($codedom =~ /^$match_domain$/) {
                   7048:             my $chome = &domain($codedom,'primary');
                   7049:             unless ($chome eq 'no_host') {
                   7050:                 push(@homeservers,$chome);
                   7051:             }
                   7052:         }
1.521     raeburn  7053:     } else {
1.772     raeburn  7054:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7055:     }
1.793     albertel 7056:     foreach my $code (keys(%{$instcodes})) {
                   7057:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7058:     }
                   7059:     chop($courses);
1.772     raeburn  7060:     my $ok_response = 0;
                   7061:     my $response;
                   7062:     while (@homeservers > 0 && $ok_response == 0) {
                   7063:         my $server = shift(@homeservers); 
                   7064:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7065:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7066:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7067: 		split(/:/,$response);
1.772     raeburn  7068:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7069:             push(@{$codetitles},&str2array($codetitles_str));
                   7070:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7071:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7072:             $ok_response = 1;
                   7073:         }
                   7074:     }
                   7075:     if ($ok_response) {
1.521     raeburn  7076:         return 'ok';
1.772     raeburn  7077:     } else {
                   7078:         return $response;
1.521     raeburn  7079:     }
                   7080: }
                   7081: 
1.792     raeburn  7082: sub auto_instcode_defaults {
                   7083:     my ($domain,$returnhash,$code_order) = @_;
                   7084:     my @homeservers;
1.841     albertel 7085: 
                   7086:     my %servers = &get_servers($domain,'library');
                   7087:     foreach my $tryserver (keys(%servers)) {
                   7088: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7089: 	    push(@homeservers,$tryserver);
                   7090: 	}
1.792     raeburn  7091:     }
1.841     albertel 7092: 
1.792     raeburn  7093:     my $response;
1.841     albertel 7094:     foreach my $server (@homeservers) {
1.792     raeburn  7095:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7096:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7097: 	
                   7098: 	foreach my $pair (split(/\&/,$response)) {
                   7099: 	    my ($name,$value)=split(/\=/,$pair);
                   7100: 	    if ($name eq 'code_order') {
                   7101: 		@{$code_order} = split(/\&/,&unescape($value));
                   7102: 	    } else {
                   7103: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7104: 	    }
                   7105: 	}
                   7106: 	return 'ok';
1.792     raeburn  7107:     }
1.841     albertel 7108: 
                   7109:     return $response;
1.1003    raeburn  7110: }
                   7111: 
                   7112: sub auto_possible_instcodes {
1.1007    raeburn  7113:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7114:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7115:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7116:         return;
                   7117:     }
1.1003    raeburn  7118:     my (@homeservers,$uhome);
                   7119:     if (defined(&domain($domain,'primary'))) {
                   7120:         $uhome=&domain($domain,'primary');
                   7121:         push(@homeservers,&domain($domain,'primary'));
                   7122:     } else {
                   7123:         my %servers = &get_servers($domain,'library');
                   7124:         foreach my $tryserver (keys(%servers)) {
                   7125:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7126:                 push(@homeservers,$tryserver);
                   7127:             }
                   7128:         }
                   7129:     }
                   7130:     my $response;
                   7131:     foreach my $server (@homeservers) {
                   7132:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7133:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7134:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7135:             split(':',$response);
                   7136:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7137:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7138:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7139:             my ($name,$value)=split('=',$item);
                   7140:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7141:         }
                   7142:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7143:             my ($name,$value)=split('=',$item);
                   7144:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7145:         }
                   7146:         return 'ok';
                   7147:     }
                   7148:     return $response;
                   7149: }
1.792     raeburn  7150: 
1.1010    raeburn  7151: sub auto_courserequest_checks {
                   7152:     my ($dom) = @_;
1.1020    raeburn  7153:     my ($homeserver,%validations);
                   7154:     if ($dom =~ /^$match_domain$/) {
                   7155:         $homeserver = &domain($dom,'primary');
                   7156:     }
                   7157:     unless ($homeserver eq 'no_host') {
                   7158:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7159:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7160:             my @items = split(/&/,$response);
                   7161:             foreach my $item (@items) {
                   7162:                 my ($key,$value) = split('=',$item);
                   7163:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7164:             }
                   7165:         }
                   7166:     }
1.1010    raeburn  7167:     return %validations; 
                   7168: }
                   7169: 
1.1020    raeburn  7170: sub auto_courserequest_validation {
                   7171:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7172:     my ($homeserver,$response);
                   7173:     if ($dom =~ /^$match_domain$/) {
                   7174:         $homeserver = &domain($dom,'primary');
                   7175:     }
                   7176:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7177:           
1.1020    raeburn  7178:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7179:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7180:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7181:                                     $homeserver));
                   7182:     }
                   7183:     return $response;
                   7184: }
                   7185: 
1.777     albertel 7186: sub auto_validate_class_sec {
1.918     raeburn  7187:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7188:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7189:     my $ownerlist;
                   7190:     if (ref($owners) eq 'ARRAY') {
                   7191:         $ownerlist = join(',',@{$owners});
                   7192:     } else {
                   7193:         $ownerlist = $owners;
                   7194:     }
1.773     raeburn  7195:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7196:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7197:     return $response;
                   7198: }
                   7199: 
1.679     raeburn  7200: # ------------------------------------------------------- Course Group routines
                   7201: 
                   7202: sub get_coursegroups {
1.809     raeburn  7203:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7204:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7205: }
                   7206: 
1.679     raeburn  7207: sub modify_coursegroup {
                   7208:     my ($cdom,$cnum,$groupsettings) = @_;
                   7209:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7210: }
                   7211: 
1.809     raeburn  7212: sub toggle_coursegroup_status {
                   7213:     my ($cdom,$cnum,$group,$action) = @_;
                   7214:     my ($from_namespace,$to_namespace);
                   7215:     if ($action eq 'delete') {
                   7216:         $from_namespace = 'coursegroups';
                   7217:         $to_namespace = 'deleted_groups';
                   7218:     } else {
                   7219:         $from_namespace = 'deleted_groups';
                   7220:         $to_namespace = 'coursegroups';
                   7221:     }
                   7222:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7223:     if (my $tmp = &error(%curr_group)) {
                   7224:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7225:         return ('read error',$tmp);
                   7226:     } else {
                   7227:         my %savedsettings = %curr_group; 
1.809     raeburn  7228:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7229:         my $deloutcome;
                   7230:         if ($result eq 'ok') {
1.809     raeburn  7231:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7232:         } else {
                   7233:             return ('write error',$result);
                   7234:         }
                   7235:         if ($deloutcome eq 'ok') {
                   7236:             return 'ok';
                   7237:         } else {
                   7238:             return ('delete error',$deloutcome);
                   7239:         }
                   7240:     }
                   7241: }
                   7242: 
1.679     raeburn  7243: sub modify_group_roles {
1.957     raeburn  7244:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7245:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7246:     my $role = 'gr/'.&escape($userprivs);
                   7247:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7248:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7249:     if ($result eq 'ok') {
                   7250:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7251:     }
1.679     raeburn  7252:     return $result;
                   7253: }
                   7254: 
                   7255: sub modify_coursegroup_membership {
                   7256:     my ($cdom,$cnum,$membership) = @_;
                   7257:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7258:     return $result;
                   7259: }
                   7260: 
1.682     raeburn  7261: sub get_active_groups {
                   7262:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7263:     my $now = time;
                   7264:     my %groups = ();
                   7265:     foreach my $key (keys(%env)) {
1.811     albertel 7266:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7267:             my ($start,$end) = split(/\./,$env{$key});
                   7268:             if (($end!=0) && ($end<$now)) { next; }
                   7269:             if (($start!=0) && ($start>$now)) { next; }
                   7270:             if ($1 eq $cdom && $2 eq $cnum) {
                   7271:                 $groups{$3} = $env{$key} ;
                   7272:             }
                   7273:         }
                   7274:     }
                   7275:     return %groups;
                   7276: }
                   7277: 
1.683     raeburn  7278: sub get_group_membership {
                   7279:     my ($cdom,$cnum,$group) = @_;
                   7280:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7281: }
                   7282: 
                   7283: sub get_users_groups {
                   7284:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7285:     my @usersgroups;
1.683     raeburn  7286:     my $cachetime=1800;
                   7287: 
                   7288:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7289:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7290:     if (defined($cached)) {
1.734     albertel 7291:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7292:     } else {  
                   7293:         $grouplist = '';
1.816     raeburn  7294:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  7295:         my $extra = &freeze_escape({'skipcheck' => 1});
                   7296:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  7297:         my $access_end = $env{'course.'.$courseid.
                   7298:                               '.default_enrollment_end_date'};
                   7299:         my $now = time;
                   7300:         foreach my $key (keys(%roleshash)) {
                   7301:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7302:                 my $group = $1;
                   7303:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7304:                     my $start = $2;
                   7305:                     my $end = $1;
                   7306:                     if ($start == -1) { next; } # deleted from group
                   7307:                     if (($start!=0) && ($start>$now)) { next; }
                   7308:                     if (($end!=0) && ($end<$now)) {
                   7309:                         if ($access_end && $access_end < $now) {
                   7310:                             if ($access_end - $end < 86400) {
                   7311:                                 push(@usersgroups,$group);
1.733     raeburn  7312:                             }
                   7313:                         }
1.817     raeburn  7314:                         next;
1.733     raeburn  7315:                     }
1.817     raeburn  7316:                     push(@usersgroups,$group);
1.683     raeburn  7317:                 }
                   7318:             }
                   7319:         }
1.817     raeburn  7320:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7321:         $grouplist = join(':',@usersgroups);
                   7322:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7323:     }
1.733     raeburn  7324:     return @usersgroups;
1.683     raeburn  7325: }
                   7326: 
                   7327: sub devalidate_getgroups_cache {
                   7328:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7329:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7330: 
1.683     raeburn  7331:     my $hashid="$udom:$uname:$courseid";
                   7332:     &devalidate_cache_new('getgroups',$hashid);
                   7333: }
                   7334: 
1.12      www      7335: # ------------------------------------------------------------------ Plain Text
                   7336: 
                   7337: sub plaintext {
1.988     raeburn  7338:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7339:     if ($short =~ m{^cr/}) {
1.758     albertel 7340: 	return (split('/',$short))[-1];
                   7341:     }
1.742     raeburn  7342:     if (!defined($cid)) {
                   7343:         $cid = $env{'request.course.id'};
                   7344:     }
                   7345:     my %rolenames = (
1.1008    raeburn  7346:                       Course    => 'std',
                   7347:                       Community => 'alt1',
1.742     raeburn  7348:                     );
1.1037    raeburn  7349:     if ($cid ne '') {
                   7350:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7351:             unless ($forcedefault) {
                   7352:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7353:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7354:                 return &Apache::lonlocal::mt($roletext);
                   7355:             }
                   7356:         }
                   7357:     }
                   7358:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7359:         (defined($rolenames{$type})) && 
                   7360:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7361:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7362:     } elsif ($cid ne '') {
                   7363:         my $crstype = $env{'course.'.$cid.'.type'};
                   7364:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7365:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7366:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7367:         }
1.742     raeburn  7368:     }
1.1037    raeburn  7369:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7370: }
                   7371: 
                   7372: # ----------------------------------------------------------------- Assign Role
                   7373: 
                   7374: sub assignrole {
1.957     raeburn  7375:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7376:         $context)=@_;
1.21      www      7377:     my $mrole;
                   7378:     if ($role =~ /^cr\//) {
1.393     www      7379:         my $cwosec=$url;
1.811     albertel 7380:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7381: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7382:            my $refused = 1;
                   7383:            if ($context eq 'requestcourses') {
                   7384:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7385:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7386:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7387:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7388:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7389:                            if ($crsenv{'internal.courseowner'} eq
                   7390:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7391:                                $refused = '';
                   7392:                            }
                   7393:                        }
                   7394:                    }
                   7395:                }
                   7396:            }
                   7397:            if ($refused) {
                   7398:                &logthis('Refused custom assignrole: '.
                   7399:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7400:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7401:                return 'refused';
                   7402:            }
1.104     www      7403:         }
1.21      www      7404:         $mrole='cr';
1.678     raeburn  7405:     } elsif ($role =~ /^gr\//) {
                   7406:         my $cwogrp=$url;
1.811     albertel 7407:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7408:         unless (&allowed('mdg',$cwogrp)) {
                   7409:             &logthis('Refused group assignrole: '.
                   7410:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7411:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7412:             return 'refused';
                   7413:         }
                   7414:         $mrole='gr';
1.21      www      7415:     } else {
1.82      www      7416:         my $cwosec=$url;
1.811     albertel 7417:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7418:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7419:             my $refused;
                   7420:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7421:                 if (!(&allowed('c'.$role,$url))) {
                   7422:                     $refused = 1;
                   7423:                 }
                   7424:             } else {
                   7425:                 $refused = 1;
                   7426:             }
1.947     raeburn  7427:             if ($refused) {
1.1045    raeburn  7428:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7429:                 if (!$selfenroll && $context eq 'course') {
                   7430:                     my %crsenv;
                   7431:                     if ($role eq 'cc' || $role eq 'co') {
                   7432:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7433:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7434:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7435:                                 if ($crsenv{'internal.courseowner'} eq 
                   7436:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7437:                                     $refused = '';
                   7438:                                 }
                   7439:                             }
                   7440:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7441:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7442:                                 if ($crsenv{'internal.courseowner'} eq 
                   7443:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7444:                                     $refused = '';
                   7445:                                 }
                   7446:                             }
                   7447:                         }
                   7448:                     }
                   7449:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7450:                     $refused = '';
1.1017    raeburn  7451:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7452:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7453:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7454:                         my $wrongcc;
                   7455:                         if ($cnum =~ /^$match_community$/) {
                   7456:                             $wrongcc = 1 if ($role eq 'cc');
                   7457:                         } else {
                   7458:                             $wrongcc = 1 if ($role eq 'co');
                   7459:                         }
                   7460:                         unless ($wrongcc) {
                   7461:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7462:                             if ($crsenv{'internal.courseowner'} eq 
                   7463:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7464:                                 $refused = '';
                   7465:                             }
1.1017    raeburn  7466:                         }
                   7467:                     }
                   7468:                 }
                   7469:                 if ($refused) {
1.947     raeburn  7470:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7471:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7472: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7473:                     return 'refused';
                   7474:                 }
1.932     raeburn  7475:             }
1.1131    raeburn  7476:         } elsif ($role eq 'au') {
                   7477:             if ($url ne '/'.$udom.'/') {
                   7478:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7479:                          ' to assign author role for '.$uname.':'.$udom.
                   7480:                          ' in domain: '.$url.' refused (wrong domain).');
                   7481:                 return 'refused';
                   7482:             }
1.104     www      7483:         }
1.21      www      7484:         $mrole=$role;
                   7485:     }
1.620     albertel 7486:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7487:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7488:     if ($end) { $command.='_'.$end; }
1.21      www      7489:     if ($start) {
                   7490: 	if ($end) { 
1.81      www      7491:            $command.='_'.$start; 
1.21      www      7492:         } else {
1.81      www      7493:            $command.='_0_'.$start;
1.21      www      7494:         }
                   7495:     }
1.739     raeburn  7496:     my $origstart = $start;
                   7497:     my $origend = $end;
1.957     raeburn  7498:     my $delflag;
1.357     www      7499: # actually delete
                   7500:     if ($deleteflag) {
1.373     www      7501: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7502: # modify command to delete the role
1.620     albertel 7503:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7504:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7505: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7506: # set start and finish to negative values for userrolelog
                   7507:            $start=-1;
                   7508:            $end=-1;
1.957     raeburn  7509:            $delflag = 1;
1.357     www      7510:         }
                   7511:     }
                   7512: # send command
1.349     www      7513:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7514: # log new user role if status is ok
1.349     www      7515:     if ($answer eq 'ok') {
1.663     raeburn  7516: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7517: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7518:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7519:         unless ($role =~ /^gr/) {
                   7520:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7521:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7522:         }
1.1053    raeburn  7523:         if ($role eq 'cc') {
                   7524:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7525:         }
1.349     www      7526:     }
                   7527:     return $answer;
1.169     harris41 7528: }
                   7529: 
1.1053    raeburn  7530: sub autoupdate_coowners {
                   7531:     my ($url,$end,$start,$uname,$udom) = @_;
                   7532:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7533:     if (($cdom ne '') && ($cnum ne '')) {
                   7534:         my $now = time;
                   7535:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7536:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7537:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7538:             my $instcode = $coursehash{'internal.coursecode'};
                   7539:             if ($instcode ne '') {
1.1056    raeburn  7540:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7541:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7542:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7543:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7544:                         if ($result eq 'valid') {
                   7545:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7546:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7547:                                     push(@newcoowners,$coowner);
                   7548:                                 }
                   7549:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7550:                                     push(@newcoowners,$uname.':'.$udom);
                   7551:                                 }
                   7552:                                 @newcoowners = sort(@newcoowners);
                   7553:                             } else {
                   7554:                                 push(@newcoowners,$uname.':'.$udom);
                   7555:                             }
                   7556:                         } else {
                   7557:                             if ($coursehash{'internal.co-owners'}) {
                   7558:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7559:                                     unless ($coowner eq $uname.':'.$udom) {
                   7560:                                         push(@newcoowners,$coowner);
                   7561:                                     }
                   7562:                                 }
                   7563:                                 unless (@newcoowners > 0) {
                   7564:                                     $delcoowners = 1;
                   7565:                                     $coowners = '';
                   7566:                                 }
                   7567:                             }
                   7568:                         }
                   7569:                         if (@newcoowners || $delcoowners) {
                   7570:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7571:                                             $delcoowners,@newcoowners);
                   7572:                         }
                   7573:                     }
                   7574:                 }
                   7575:             }
                   7576:         }
                   7577:     }
                   7578: }
                   7579: 
                   7580: sub store_coowners {
                   7581:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7582:     my $cid = $cdom.'_'.$cnum;
                   7583:     my ($coowners,$delresult,$putresult);
                   7584:     if (@newcoowners) {
                   7585:         $coowners = join(',',@newcoowners);
                   7586:         my %coownershash = (
                   7587:                             'internal.co-owners' => $coowners,
                   7588:                            );
                   7589:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7590:         if ($putresult eq 'ok') {
                   7591:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7592:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7593:             }
                   7594:         }
                   7595:     }
                   7596:     if ($delcoowners) {
                   7597:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7598:         if ($delresult eq 'ok') {
                   7599:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7600:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7601:             }
                   7602:         }
                   7603:     }
                   7604:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7605:         my %crsinfo =
                   7606:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7607:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7608:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7609:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7610:         }
                   7611:     }
                   7612: }
                   7613: 
1.169     harris41 7614: # -------------------------------------------------- Modify user authentication
1.197     www      7615: # Overrides without validation
                   7616: 
1.169     harris41 7617: sub modifyuserauth {
                   7618:     my ($udom,$uname,$umode,$upass)=@_;
                   7619:     my $uhome=&homeserver($uname,$udom);
1.197     www      7620:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7621:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7622:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7623:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7624:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7625: 		     &escape($upass),$uhome);
1.620     albertel 7626:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7627:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7628:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7629:     &log($udom,,$uname,$uhome,
1.620     albertel 7630:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7631:                                      $env{'user.name'}.', '.$umode.
1.197     www      7632:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7633:     unless ($reply eq 'ok') {
1.197     www      7634:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7635: 	return 'error: '.$reply;
                   7636:     }   
1.170     harris41 7637:     return 'ok';
1.80      www      7638: }
                   7639: 
1.81      www      7640: # --------------------------------------------------------------- Modify a user
1.80      www      7641: 
1.81      www      7642: sub modifyuser {
1.206     matthew  7643:     my ($udom,    $uname, $uid,
                   7644:         $umode,   $upass, $first,
                   7645:         $middle,  $last,  $gene,
1.1058    raeburn  7646:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7647:     $udom= &LONCAPA::clean_domain($udom);
                   7648:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7649:     my $showcandelete = 'none';
                   7650:     if (ref($candelete) eq 'ARRAY') {
                   7651:         if (@{$candelete} > 0) {
                   7652:             $showcandelete = join(', ',@{$candelete});
                   7653:         }
                   7654:     }
1.81      www      7655:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7656:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7657: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7658:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7659:                                      ' desiredhome not specified'). 
1.620     albertel 7660:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7661:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7662:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7663:     my $newuser;
                   7664:     if ($uhome eq 'no_host') {
                   7665:         $newuser = 1;
                   7666:     }
1.80      www      7667: # ----------------------------------------------------------------- Create User
1.406     albertel 7668:     if (($uhome eq 'no_host') && 
                   7669: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7670:         my $unhome='';
1.844     albertel 7671:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7672:             $unhome = $desiredhome;
1.620     albertel 7673: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7674: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7675:         } else { # load balancing routine for determining $unhome
1.81      www      7676:             my $loadm=10000000;
1.841     albertel 7677: 	    my %servers = &get_servers($udom,'library');
                   7678: 	    foreach my $tryserver (keys(%servers)) {
                   7679: 		my $answer=reply('load',$tryserver);
                   7680: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7681: 		    $loadm=$answer;
                   7682: 		    $unhome=$tryserver;
                   7683: 		}
1.80      www      7684: 	    }
                   7685:         }
                   7686:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7687: 	    return 'error: unable to find a home server for '.$uname.
                   7688:                    ' in domain '.$udom;
1.80      www      7689:         }
                   7690:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7691:                          &escape($upass),$unhome);
                   7692: 	unless ($reply eq 'ok') {
                   7693:             return 'error: '.$reply;
                   7694:         }   
1.230     stredwic 7695:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7696:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7697: 	    return 'error: unable verify users home machine.';
1.80      www      7698:         }
1.209     matthew  7699:     }   # End of creation of new user
1.80      www      7700: # ---------------------------------------------------------------------- Add ID
                   7701:     if ($uid) {
                   7702:        $uid=~tr/A-Z/a-z/;
                   7703:        my %uidhash=&idrget($udom,$uname);
1.196     www      7704:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7705:          && (!$forceid)) {
1.80      www      7706: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7707: 	      return 'error: user id "'.$uid.'" does not match '.
                   7708:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7709:           }
                   7710:        } else {
                   7711: 	  &idput($udom,($uname => $uid));
                   7712:        }
                   7713:     }
                   7714: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7715:     my @tmp=&get('environment',
1.899     raeburn  7716: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7717:                     'permanentemail','inststatus'],
1.134     albertel 7718: 		   $udom,$uname);
1.1075    raeburn  7719:     my (%names,%oldnames);
1.313     matthew  7720:     if ($tmp[0] =~ m/^error:.*/) { 
                   7721:         %names=(); 
                   7722:     } else {
                   7723:         %names = @tmp;
1.1075    raeburn  7724:         %oldnames = %names;
1.313     matthew  7725:     }
1.388     www      7726: #
1.1058    raeburn  7727: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7728: # of users did not contain them), do not overwrite existing values
                   7729: # unless field is in $candelete array ref.  
                   7730: #
                   7731: 
                   7732:     my @fields = ('firstname','middlename','lastname','generation',
                   7733:                   'permanentemail','id');
                   7734:     my %newvalues;
                   7735:     if (ref($candelete) eq 'ARRAY') {
                   7736:         foreach my $field (@fields) {
                   7737:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7738:                 if ($field eq 'firstname') {
                   7739:                     $names{$field} = $first;
                   7740:                 } elsif ($field eq 'middlename') {
                   7741:                     $names{$field} = $middle;
                   7742:                 } elsif ($field eq 'lastname') {
                   7743:                     $names{$field} = $last;
                   7744:                 } elsif ($field eq 'generation') { 
                   7745:                     $names{$field} = $gene;
                   7746:                 } elsif ($field eq 'permanentemail') {
                   7747:                     $names{$field} = $email;
                   7748:                 } elsif ($field eq 'id') {
                   7749:                     $names{$field}  = $uid;
                   7750:                 }
                   7751:             }
                   7752:         }
                   7753:     }
1.388     www      7754:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7755:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7756:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7757:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7758:     if ($email) {
                   7759:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7760:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7761:     }
1.899     raeburn  7762:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7763:     if (defined($inststatus)) {
                   7764:         $names{'inststatus'} = '';
                   7765:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7766:         if (ref($usertypes) eq 'HASH') {
                   7767:             my @okstatuses; 
                   7768:             foreach my $item (split(/:/,$inststatus)) {
                   7769:                 if (defined($usertypes->{$item})) {
                   7770:                     push(@okstatuses,$item);  
                   7771:                 }
                   7772:             }
                   7773:             if (@okstatuses) {
                   7774:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7775:             }
                   7776:         }
                   7777:     }
1.1075    raeburn  7778:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7779:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7780:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7781:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7782:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7783:     } else {
                   7784:         $logmsg .= ' during self creation';
                   7785:     }
1.1075    raeburn  7786:     my $changed;
                   7787:     if ($newuser) {
                   7788:         $changed = 1;
                   7789:     } else {
                   7790:         foreach my $field (@fields) {
                   7791:             if ($names{$field} ne $oldnames{$field}) {
                   7792:                 $changed = 1;
                   7793:                 last;
                   7794:             }
                   7795:         }
                   7796:     }
                   7797:     unless ($changed) {
                   7798:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7799:         &logthis($logmsg);
                   7800:         return 'ok';
                   7801:     }
                   7802:     my $reply = &put('environment', \%names, $udom,$uname);
                   7803:     if ($reply ne 'ok') { 
                   7804:         return 'error: '.$reply;
                   7805:     }
1.1087    raeburn  7806:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7807:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7808:     }
1.1075    raeburn  7809:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7810:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7811:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7812:     &logthis($logmsg);
1.134     albertel 7813:     return 'ok';
1.80      www      7814: }
                   7815: 
1.81      www      7816: # -------------------------------------------------------------- Modify student
1.80      www      7817: 
1.81      www      7818: sub modifystudent {
                   7819:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7820:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7821:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7822:     if (!$cid) {
1.620     albertel 7823: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7824: 	    return 'not_in_class';
                   7825: 	}
1.80      www      7826:     }
                   7827: # --------------------------------------------------------------- Make the user
1.81      www      7828:     my $reply=&modifyuser
1.209     matthew  7829: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7830:          $desiredhome,$email,$inststatus);
1.80      www      7831:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7832:     # This will cause &modify_student_enrollment to get the uid from the
                   7833:     # students environment
                   7834:     $uid = undef if (!$forceid);
1.455     albertel 7835:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7836: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7837:     return $reply;
                   7838: }
                   7839: 
                   7840: sub modify_student_enrollment {
1.957     raeburn  7841:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7842:     my ($cdom,$cnum,$chome);
                   7843:     if (!$cid) {
1.620     albertel 7844: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7845: 	    return 'not_in_class';
                   7846: 	}
1.620     albertel 7847: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7848: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7849:     } else {
                   7850: 	($cdom,$cnum)=split(/_/,$cid);
                   7851:     }
1.620     albertel 7852:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7853:     if (!$chome) {
1.457     raeburn  7854: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7855:     }
1.455     albertel 7856:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7857:     # Make sure the user exists
1.81      www      7858:     my $uhome=&homeserver($uname,$udom);
                   7859:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7860: 	return 'error: no such user';
                   7861:     }
1.297     matthew  7862:     # Get student data if we were not given enough information
                   7863:     if (!defined($first)  || $first  eq '' || 
                   7864:         !defined($last)   || $last   eq '' || 
                   7865:         !defined($uid)    || $uid    eq '' || 
                   7866:         !defined($middle) || $middle eq '' || 
                   7867:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7868:         # They did not supply us with enough data to enroll the student, so
                   7869:         # we need to pick up more information.
1.297     matthew  7870:         my %tmp = &get('environment',
1.294     matthew  7871:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7872:                        ,$udom,$uname);
                   7873: 
1.800     albertel 7874:         #foreach my $key (keys(%tmp)) {
                   7875:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7876:         #}
1.294     matthew  7877:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7878:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7879:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7880:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7881:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7882:     }
1.556     albertel 7883:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7884:     my $user = "$uname:$udom";
                   7885:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7886:     my $reply=cput('classlist',
1.1148    raeburn  7887: 		   {$user => 
1.515     raeburn  7888: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7889: 		   $cdom,$cnum);
1.1148    raeburn  7890:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7891:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7892:     } else { 
1.81      www      7893: 	return 'error: '.$reply;
                   7894:     }
1.297     matthew  7895:     # Add student role to user
1.83      www      7896:     my $uurl='/'.$cid;
1.81      www      7897:     $uurl=~s/\_/\//g;
                   7898:     if ($usec) {
                   7899: 	$uurl.='/'.$usec;
                   7900:     }
1.1148    raeburn  7901:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7902:                              $selfenroll,$context);
                   7903:     if ($result ne 'ok') {
                   7904:         if ($old_entry{$user} ne '') {
                   7905:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7906:         } else {
                   7907:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7908:         }
                   7909:     }
                   7910:     return $result; 
1.21      www      7911: }
                   7912: 
1.556     albertel 7913: sub format_name {
                   7914:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7915:     my $name;
                   7916:     if ($first ne 'lastname') {
                   7917: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7918:     } else {
                   7919: 	if ($lastname=~/\S/) {
                   7920: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7921: 	    $name=~s/\s+,/,/;
                   7922: 	} else {
                   7923: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7924: 	}
                   7925:     }
                   7926:     $name=~s/^\s+//;
                   7927:     $name=~s/\s+$//;
                   7928:     $name=~s/\s+/ /g;
                   7929:     return $name;
                   7930: }
                   7931: 
1.84      www      7932: # ------------------------------------------------- Write to course preferences
                   7933: 
                   7934: sub writecoursepref {
                   7935:     my ($courseid,%prefs)=@_;
                   7936:     $courseid=~s/^\///;
                   7937:     $courseid=~s/\_/\//g;
                   7938:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7939:     my $chome=homeserver($cnum,$cdomain);
                   7940:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7941: 	return 'error: no such course';
                   7942:     }
                   7943:     my $cstring='';
1.800     albertel 7944:     foreach my $pref (keys(%prefs)) {
                   7945: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7946:     }
1.84      www      7947:     $cstring=~s/\&$//;
                   7948:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7949: }
                   7950: 
                   7951: # ---------------------------------------------------------- Make/modify course
                   7952: 
                   7953: sub createcourse {
1.741     raeburn  7954:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7955:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7956:     $url=&declutter($url);
                   7957:     my $cid='';
1.1028    raeburn  7958:     if ($context eq 'requestcourses') {
                   7959:         my $can_create = 0;
                   7960:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7961:         if ($udom eq $ownerdom) {
                   7962:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7963:                                   $context)) {
                   7964:                 $can_create = 1;
                   7965:             }
                   7966:         } else {
                   7967:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7968:                                            $category);
                   7969:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7970:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7971:                 if (@curr > 0) {
                   7972:                     my @options = qw(approval validate autolimit);
                   7973:                     my $optregex = join('|',@options);
                   7974:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7975:                         $can_create = 1;
                   7976:                     }
                   7977:                 }
                   7978:             }
                   7979:         }
                   7980:         if ($can_create) {
                   7981:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7982:                 unless (&allowed('ccc',$udom)) {
                   7983:                     return 'refused'; 
                   7984:                 }
1.1017    raeburn  7985:             }
                   7986:         } else {
                   7987:             return 'refused';
                   7988:         }
1.1028    raeburn  7989:     } elsif (!&allowed('ccc',$udom)) {
                   7990:         return 'refused';
1.84      www      7991:     }
1.1011    raeburn  7992: # --------------------------------------------------------------- Get Unique ID
                   7993:     my $uname;
                   7994:     if ($cnum =~ /^$match_courseid$/) {
                   7995:         my $chome=&homeserver($cnum,$udom,'true');
                   7996:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7997:             $uname = $cnum;
                   7998:         } else {
1.1038    raeburn  7999:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8000:         }
                   8001:     } else {
1.1038    raeburn  8002:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8003:     }
                   8004:     return $uname if ($uname =~ /^error/);
                   8005: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8006:     if (!defined($course_server)) {
                   8007:         if (defined(&domain($udom,'primary'))) {
                   8008:             $course_server = &domain($udom,'primary');
                   8009:         } else {
                   8010:             $course_server = $env{'user.home'}; 
                   8011:         }
                   8012:     }
                   8013:     my %host_servers =
                   8014:         &Apache::lonnet::get_servers($udom,'library');
                   8015:     unless ($host_servers{$course_server}) {
                   8016:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8017:     }
1.84      www      8018: # ------------------------------------------------------------- Make the course
                   8019:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8020:                       $course_server);
1.84      www      8021:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8022:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8023:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8024: 	return 'error: no such course';
                   8025:     }
1.271     www      8026: # ----------------------------------------------------------------- Course made
1.516     raeburn  8027: # log existence
1.1029    raeburn  8028:     my $now = time;
1.918     raeburn  8029:     my $newcourse = {
                   8030:                     $udom.'_'.$uname => {
1.921     raeburn  8031:                                      description => $description,
                   8032:                                      inst_code   => $inst_code,
                   8033:                                      owner       => $course_owner,
                   8034:                                      type        => $crstype,
1.1029    raeburn  8035:                                      creator     => $env{'user.name'}.':'.
                   8036:                                                     $env{'user.domain'},
                   8037:                                      created     => $now,
                   8038:                                      context     => $context,
1.918     raeburn  8039:                                                 },
                   8040:                     };
1.921     raeburn  8041:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8042: # set toplevel url
1.271     www      8043:     my $topurl=$url;
                   8044:     unless ($nonstandard) {
                   8045: # ------------------------------------------ For standard courses, make top url
                   8046:         my $mapurl=&clutter($url);
1.278     www      8047:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8048:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8049: <map>
                   8050: <resource id="1" type="start"></resource>
                   8051: <resource id="2" src="$mapurl"></resource>
                   8052: <resource id="3" type="finish"></resource>
                   8053: <link index="1" from="1" to="2"></link>
                   8054: <link index="2" from="2" to="3"></link>
                   8055: </map>
                   8056: ENDINITMAP
                   8057:         $topurl=&declutter(
1.638     albertel 8058:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8059:                           );
                   8060:     }
                   8061: # ----------------------------------------------------------- Write preferences
1.84      www      8062:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8063:                      ('description'              => $description,
                   8064:                       'url'                      => $topurl,
                   8065:                       'internal.creator'         => $env{'user.name'}.':'.
                   8066:                                                     $env{'user.domain'},
                   8067:                       'internal.created'         => $now,
                   8068:                       'internal.creationcontext' => $context)
                   8069:                     );
1.84      www      8070:     return '/'.$udom.'/'.$uname;
                   8071: }
                   8072: 
1.1011    raeburn  8073: # ------------------------------------------------------------------- Create ID
                   8074: sub generate_coursenum {
1.1038    raeburn  8075:     my ($udom,$crstype) = @_;
1.1011    raeburn  8076:     my $domdesc = &domain($udom);
                   8077:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8078:     my $first;
                   8079:     if ($crstype eq 'Community') {
                   8080:         $first = '0';
                   8081:     } else {
                   8082:         $first = int(1+rand(9)); 
                   8083:     } 
                   8084:     my $uname=$first.
1.1011    raeburn  8085:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8086:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8087:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8088: # ----------------------------------------------- Make sure that does not exist
                   8089:     my $uhome=&homeserver($uname,$udom,'true');
                   8090:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8091:         if ($crstype eq 'Community') {
                   8092:             $first = '0';
                   8093:         } else {
                   8094:             $first = int(1+rand(9));
                   8095:         }
                   8096:         $uname=$first.
1.1011    raeburn  8097:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8098:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8099:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8100:         $uhome=&homeserver($uname,$udom,'true');
                   8101:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8102:             return 'error: unable to generate unique course-ID';
                   8103:         }
                   8104:     }
                   8105:     return $uname;
                   8106: }
                   8107: 
1.813     albertel 8108: sub is_course {
                   8109:     my ($cdom,$cnum) = @_;
                   8110:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  8111: 				undef,'.');
1.813     albertel 8112:     if (exists($courses{$cdom.'_'.$cnum})) {
                   8113:         return 1;
                   8114:     }
                   8115:     return 0;
                   8116: }
                   8117: 
1.1015    raeburn  8118: sub store_userdata {
                   8119:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8120:     my $result;
1.1016    raeburn  8121:     if ($datakey ne '') {
1.1013    raeburn  8122:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8123:             if ($udom eq '' || $uname eq '') {
                   8124:                 $udom = $env{'user.domain'};
                   8125:                 $uname = $env{'user.name'};
                   8126:             }
                   8127:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8128:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8129:                 $result = 'error: no_host';
                   8130:             } else {
                   8131:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8132:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8133: 
                   8134:                 my $namevalue='';
                   8135:                 foreach my $key (keys(%{$storehash})) {
                   8136:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8137:                 }
                   8138:                 $namevalue=~s/\&$//;
1.1105    raeburn  8139:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8140:                                   $namevalue,$uhome);
1.1013    raeburn  8141:             }
                   8142:         } else {
                   8143:             $result = 'error: data to store was not a hash reference'; 
                   8144:         }
                   8145:     } else {
                   8146:         $result= 'error: invalid requestkey'; 
                   8147:     }
                   8148:     return $result;
                   8149: }
                   8150: 
1.21      www      8151: # ---------------------------------------------------------- Assign Custom Role
                   8152: 
                   8153: sub assigncustomrole {
1.957     raeburn  8154:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8155:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8156:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8157: }
                   8158: 
                   8159: # ----------------------------------------------------------------- Revoke Role
                   8160: 
                   8161: sub revokerole {
1.957     raeburn  8162:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8163:     my $now=time;
1.965     raeburn  8164:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8165: }
                   8166: 
                   8167: # ---------------------------------------------------------- Revoke Custom Role
                   8168: 
                   8169: sub revokecustomrole {
1.957     raeburn  8170:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8171:     my $now=time;
1.357     www      8172:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8173:            $deleteflag,$selfenroll,$context);
1.17      www      8174: }
                   8175: 
1.533     banghart 8176: # ------------------------------------------------------------ Disk usage
1.535     albertel 8177: sub diskusage {
1.955     raeburn  8178:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8179:     $directorypath =~ s/\/$//;
                   8180:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8181:                        .&escape($getpropath).':'.&escape($uname).':'
                   8182:                        .&escape($udom),homeserver($uname,$udom));
                   8183:     if ($listing eq 'unknown_cmd') {
                   8184:         if ($getpropath) {
                   8185:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8186:         }
                   8187:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8188:     }
1.514     albertel 8189:     return $listing;
1.512     banghart 8190: }
                   8191: 
1.566     banghart 8192: sub is_locked {
1.1096    raeburn  8193:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8194:     my @check;
                   8195:     my $is_locked;
1.1093    raeburn  8196:     push (@check,$file_name);
1.613     albertel 8197:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8198: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8199:     my ($tmp)=keys(%locked);
                   8200:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8201:     
1.566     banghart 8202:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8203:         $is_locked = 'false';
                   8204:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8205:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8206:                $is_locked = 'true';
1.1096    raeburn  8207:                if (ref($which) eq 'ARRAY') {
                   8208:                    push(@{$which},$entry);
                   8209:                } else {
                   8210:                    last;
                   8211:                }
1.745     raeburn  8212:            }
                   8213:        }
1.566     banghart 8214:     } else {
                   8215:         $is_locked = 'false';
                   8216:     }
1.1093    raeburn  8217:     return $is_locked;
1.566     banghart 8218: }
                   8219: 
1.759     albertel 8220: sub declutter_portfile {
                   8221:     my ($file) = @_;
1.833     albertel 8222:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8223:     return $file;
                   8224: }
                   8225: 
1.559     banghart 8226: # ------------------------------------------------------------- Mark as Read Only
                   8227: 
                   8228: sub mark_as_readonly {
                   8229:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8230:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8231:     my ($tmp)=keys(%current_permissions);
                   8232:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8233:     foreach my $file (@{$files}) {
1.759     albertel 8234: 	$file = &declutter_portfile($file);
1.561     banghart 8235:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8236:     }
1.613     albertel 8237:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8238:     return;
                   8239: }
                   8240: 
1.572     banghart 8241: # ------------------------------------------------------------Save Selected Files
                   8242: 
                   8243: sub save_selected_files {
                   8244:     my ($user, $path, @files) = @_;
                   8245:     my $filename = $user."savedfiles";
1.573     banghart 8246:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8247:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8248:     foreach my $file (@files) {
1.620     albertel 8249:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8250:     }
                   8251:     foreach my $file (@other_files) {
1.574     banghart 8252:         print (OUT $file."\n");
1.572     banghart 8253:     }
1.574     banghart 8254:     close (OUT);
1.572     banghart 8255:     return 'ok';
                   8256: }
                   8257: 
1.574     banghart 8258: sub clear_selected_files {
                   8259:     my ($user) = @_;
                   8260:     my $filename = $user."savedfiles";
1.1117    foxr     8261:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8262:     print (OUT undef);
                   8263:     close (OUT);
                   8264:     return ("ok");    
                   8265: }
                   8266: 
1.572     banghart 8267: sub files_in_path {
                   8268:     my ($user, $path) = @_;
                   8269:     my $filename = $user."savedfiles";
                   8270:     my %return_files;
1.1117    foxr     8271:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8272:     while (my $line_in = <IN>) {
1.574     banghart 8273:         chomp ($line_in);
                   8274:         my @paths_and_file = split (m!/!, $line_in);
                   8275:         my $file_part = pop (@paths_and_file);
                   8276:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8277:         $path_part.='/';
                   8278:         my $path_and_file = $path_part.$file_part;
                   8279:         if ($path_part eq $path) {
                   8280:             $return_files{$file_part}= 'selected';
                   8281:         }
                   8282:     }
1.574     banghart 8283:     close (IN);
                   8284:     return (\%return_files);
1.572     banghart 8285: }
                   8286: 
                   8287: # called in portfolio select mode, to show files selected NOT in current directory
                   8288: sub files_not_in_path {
                   8289:     my ($user, $path) = @_;
                   8290:     my $filename = $user."savedfiles";
                   8291:     my @return_files;
                   8292:     my $path_part;
1.1117    foxr     8293:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8294:     while (my $line = <IN>) {
1.572     banghart 8295:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8296:         my @paths_and_file = split(m|/|, $line);
                   8297:         my $file_part = pop(@paths_and_file);
                   8298:         chomp($file_part);
                   8299:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8300:         $path_part .= '/';
                   8301:         my $path_and_file = $path_part.$file_part;
                   8302:         if ($path_part ne $path) {
1.800     albertel 8303:             push(@return_files, ($path_and_file));
1.572     banghart 8304:         }
                   8305:     }
1.800     albertel 8306:     close(OUT);
1.574     banghart 8307:     return (@return_files);
1.572     banghart 8308: }
                   8309: 
1.745     raeburn  8310: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8311: 
1.745     raeburn  8312: sub get_portfile_permissions {
                   8313:     my ($domain,$user) = @_;
1.613     albertel 8314:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8315:     my ($tmp)=keys(%current_permissions);
                   8316:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8317:     return \%current_permissions;
                   8318: }
                   8319: 
                   8320: #---------------------------------------------Get portfolio file access controls
                   8321: 
1.749     raeburn  8322: sub get_access_controls {
1.745     raeburn  8323:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8324:     my %access;
                   8325:     my $real_file = $file;
                   8326:     $file =~ s/\.meta$//;
1.745     raeburn  8327:     if (defined($file)) {
1.749     raeburn  8328:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8329:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8330:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8331:             }
                   8332:         }
1.745     raeburn  8333:     } else {
1.749     raeburn  8334:         foreach my $key (keys(%{$current_permissions})) {
                   8335:             if ($key =~ /\0accesscontrol$/) {
                   8336:                 if (defined($group)) {
                   8337:                     if ($key !~ m-^\Q$group\E/-) {
                   8338:                         next;
                   8339:                     }
                   8340:                 }
                   8341:                 my ($fullpath) = split(/\0/,$key);
                   8342:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8343:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8344:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8345:                     }
                   8346:                 }
                   8347:             }
                   8348:         }
                   8349:     }
                   8350:     return %access;
                   8351: }
                   8352: 
                   8353: sub modify_access_controls {
                   8354:     my ($file_name,$changes,$domain,$user)=@_;
                   8355:     my ($outcome,$deloutcome);
                   8356:     my %store_permissions;
                   8357:     my %new_values;
                   8358:     my %new_control;
                   8359:     my %translation;
                   8360:     my @deletions = ();
                   8361:     my $now = time;
                   8362:     if (exists($$changes{'activate'})) {
                   8363:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8364:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8365:             my $numnew = scalar(@newitems);
                   8366:             for (my $i=0; $i<$numnew; $i++) {
                   8367:                 my $newkey = $newitems[$i];
                   8368:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8369:                 if ($newkey =~ /^\d+:/) { 
                   8370:                     $newkey =~ s/^(\d+)/$newid/;
                   8371:                     $translation{$1} = $newid;
                   8372:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8373:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8374:                     $translation{$1} = $newid;
                   8375:                 }
1.749     raeburn  8376:                 $new_values{$file_name."\0".$newkey} = 
                   8377:                                           $$changes{'activate'}{$newitems[$i]};
                   8378:                 $new_control{$newkey} = $now;
                   8379:             }
                   8380:         }
                   8381:     }
                   8382:     my %todelete;
                   8383:     my %changed_items;
                   8384:     foreach my $action ('delete','update') {
                   8385:         if (exists($$changes{$action})) {
                   8386:             if (ref($$changes{$action}) eq 'HASH') {
                   8387:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8388:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8389:                     if ($action eq 'delete') { 
                   8390:                         $todelete{$itemnum} = 1;
                   8391:                     } else {
                   8392:                         $changed_items{$itemnum} = $key;
                   8393:                     }
                   8394:                 }
1.745     raeburn  8395:             }
                   8396:         }
1.749     raeburn  8397:     }
                   8398:     # get lock on access controls for file.
                   8399:     my $lockhash = {
                   8400:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8401:                                                        ':'.$env{'user.domain'},
                   8402:                    }; 
                   8403:     my $tries = 0;
                   8404:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8405:    
                   8406:     while (($gotlock ne 'ok') && $tries <3) {
                   8407:         $tries ++;
                   8408:         sleep 1;
                   8409:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8410:     }
                   8411:     if ($gotlock eq 'ok') {
                   8412:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8413:         my ($tmp)=keys(%curr_permissions);
                   8414:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8415:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8416:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8417:             if (ref($curr_controls) eq 'HASH') {
                   8418:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8419:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8420:                     if (defined($todelete{$itemnum})) {
                   8421:                         push(@deletions,$file_name."\0".$control_item);
                   8422:                     } else {
                   8423:                         if (defined($changed_items{$itemnum})) {
                   8424:                             $new_control{$changed_items{$itemnum}} = $now;
                   8425:                             push(@deletions,$file_name."\0".$control_item);
                   8426:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8427:                         } else {
                   8428:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8429:                         }
                   8430:                     }
1.745     raeburn  8431:                 }
                   8432:             }
                   8433:         }
1.970     raeburn  8434:         my ($group);
                   8435:         if (&is_course($domain,$user)) {
                   8436:             ($group,my $file) = split(/\//,$file_name,2);
                   8437:         }
1.749     raeburn  8438:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8439:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8440:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8441:         #  remove lock
                   8442:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8443:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8444:         my $sqlresult =
1.970     raeburn  8445:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8446:                                     $group);
1.749     raeburn  8447:     } else {
                   8448:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8449:     }
1.749     raeburn  8450:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8451: }
                   8452: 
1.827     raeburn  8453: sub make_public_indefinitely {
                   8454:     my ($requrl) = @_;
                   8455:     my $now = time;
                   8456:     my $action = 'activate';
                   8457:     my $aclnum = 0;
                   8458:     if (&is_portfolio_url($requrl)) {
                   8459:         my (undef,$udom,$unum,$file_name,$group) =
                   8460:             &parse_portfolio_url($requrl);
                   8461:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8462:         my %access_controls = &get_access_controls($current_perms,
                   8463:                                                    $group,$file_name);
                   8464:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8465:             my ($num,$scope,$end,$start) = 
                   8466:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8467:             if ($scope eq 'public') {
                   8468:                 if ($start <= $now && $end == 0) {
                   8469:                     $action = 'none';
                   8470:                 } else {
                   8471:                     $action = 'update';
                   8472:                     $aclnum = $num;
                   8473:                 }
                   8474:                 last;
                   8475:             }
                   8476:         }
                   8477:         if ($action eq 'none') {
                   8478:              return 'ok';
                   8479:         } else {
                   8480:             my %changes;
                   8481:             my $newend = 0;
                   8482:             my $newstart = $now;
                   8483:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8484:             $changes{$action}{$newkey} = {
                   8485:                 type => 'public',
                   8486:                 time => {
                   8487:                     start => $newstart,
                   8488:                     end   => $newend,
                   8489:                 },
                   8490:             };
                   8491:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8492:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8493:             return $outcome;
                   8494:         }
                   8495:     } else {
                   8496:         return 'invalid';
                   8497:     }
                   8498: }
                   8499: 
1.745     raeburn  8500: #------------------------------------------------------Get Marked as Read Only
                   8501: 
                   8502: sub get_marked_as_readonly {
                   8503:     my ($domain,$user,$what,$group) = @_;
                   8504:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8505:     my @readonly_files;
1.629     banghart 8506:     my $cmp1=$what;
                   8507:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8508:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8509:         if (defined($group)) {
                   8510:             if ($file_name !~ m-^\Q$group\E/-) {
                   8511:                 next;
                   8512:             }
                   8513:         }
1.561     banghart 8514:         if (ref($value) eq "ARRAY"){
                   8515:             foreach my $stored_what (@{$value}) {
1.629     banghart 8516:                 my $cmp2=$stored_what;
1.759     albertel 8517:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8518:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8519:                 }
1.629     banghart 8520:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8521:                     push(@readonly_files, $file_name);
1.745     raeburn  8522:                     last;
1.563     banghart 8523:                 } elsif (!defined($what)) {
                   8524:                     push(@readonly_files, $file_name);
1.745     raeburn  8525:                     last;
1.561     banghart 8526:                 }
                   8527:             }
1.745     raeburn  8528:         }
1.561     banghart 8529:     }
                   8530:     return @readonly_files;
                   8531: }
1.577     banghart 8532: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8533: 
1.577     banghart 8534: sub get_marked_as_readonly_hash {
1.745     raeburn  8535:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8536:     my %readonly_files;
1.745     raeburn  8537:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8538:         if (defined($group)) {
                   8539:             if ($file_name !~ m-^\Q$group\E/-) {
                   8540:                 next;
                   8541:             }
                   8542:         }
1.577     banghart 8543:         if (ref($value) eq "ARRAY"){
                   8544:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8545:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8546:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8547:                         if ($lock_descriptor eq 'graded') {
                   8548:                             $readonly_files{$file_name} = 'graded';
                   8549:                         } elsif ($lock_descriptor eq 'handback') {
                   8550:                             $readonly_files{$file_name} = 'handback';
                   8551:                         } else {
                   8552:                             if (!exists($readonly_files{$file_name})) {
                   8553:                                 $readonly_files{$file_name} = 'locked';
                   8554:                             }
                   8555:                         }
1.745     raeburn  8556:                     }
1.750     banghart 8557:                 } 
1.577     banghart 8558:             }
                   8559:         } 
                   8560:     }
                   8561:     return %readonly_files;
                   8562: }
1.559     banghart 8563: # ------------------------------------------------------------ Unmark as Read Only
                   8564: 
                   8565: sub unmark_as_readonly {
1.629     banghart 8566:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8567:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8568:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8569:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8570:     my $symb_crs = $what;
                   8571:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8572:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8573:     my ($tmp)=keys(%current_permissions);
                   8574:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8575:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8576:     foreach my $file (@readonly_files) {
1.759     albertel 8577: 	my $clean_file = &declutter_portfile($file);
                   8578: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8579: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8580:         my @new_locks;
                   8581:         my @del_keys;
                   8582:         if (ref($current_locks) eq "ARRAY"){
                   8583:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8584:                 my $compare=$locker;
1.749     raeburn  8585:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8586:                     $compare=join('',@{$locker});
1.746     raeburn  8587:                     if ($compare ne $symb_crs) {
                   8588:                         push(@new_locks, $locker);
                   8589:                     }
1.563     banghart 8590:                 }
                   8591:             }
1.650     albertel 8592:             if (scalar(@new_locks) > 0) {
1.563     banghart 8593:                 $current_permissions{$file} = \@new_locks;
                   8594:             } else {
                   8595:                 push(@del_keys, $file);
1.613     albertel 8596:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8597:                 delete($current_permissions{$file});
1.563     banghart 8598:             }
                   8599:         }
1.561     banghart 8600:     }
1.613     albertel 8601:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8602:     return;
                   8603: }
1.512     banghart 8604: 
1.17      www      8605: # ------------------------------------------------------------ Directory lister
                   8606: 
                   8607: sub dirlist {
1.955     raeburn  8608:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8609:     $uri=~s/^\///;
                   8610:     $uri=~s/\/$//;
1.253     stredwic 8611:     my ($udom, $uname);
1.955     raeburn  8612:     if ($getuserdir) {
1.253     stredwic 8613:         $udom = $userdomain;
                   8614:         $uname = $username;
1.955     raeburn  8615:     } else {
                   8616:         (undef,$udom,$uname)=split(/\//,$uri);
                   8617:         if(defined($userdomain)) {
                   8618:             $udom = $userdomain;
                   8619:         }
                   8620:         if(defined($username)) {
                   8621:             $uname = $username;
                   8622:         }
1.253     stredwic 8623:     }
1.955     raeburn  8624:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8625: 
1.955     raeburn  8626:     $dirRoot = $perlvar{'lonDocRoot'};
                   8627:     if (defined($getpropath)) {
                   8628:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8629:         $dirRoot =~ s/\/$//;
1.955     raeburn  8630:     } elsif (defined($getuserdir)) {
                   8631:         my $subdir=$uname.'__';
                   8632:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8633:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8634:                    ."/$udom/$subdir/$uname";
                   8635:     } elsif (defined($alternateRoot)) {
                   8636:         $dirRoot = $alternateRoot;
1.751     banghart 8637:     }
1.253     stredwic 8638: 
                   8639:     if($udom) {
                   8640:         if($uname) {
1.1135    raeburn  8641:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8642:             if ($uhome eq 'no_host') {
                   8643:                 return ([],'no_host');
                   8644:             }
1.955     raeburn  8645:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8646:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8647:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8648:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8649:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8650:             } else {
                   8651:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8652:             }
1.605     matthew  8653:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8654:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8655:                 @listing_results = split(/:/,$listing);
                   8656:             } else {
                   8657:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8658:             }
1.1135    raeburn  8659:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8660:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8661:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8662:                 return ([],$listing);
                   8663:             } else {
                   8664:                 return (\@listing_results);
1.1135    raeburn  8665:             }
1.955     raeburn  8666:         } elsif(!$alternateRoot) {
1.1136    raeburn  8667:             my (%allusers,%listerror);
1.841     albertel 8668: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8669:  	    foreach my $tryserver (keys(%servers)) {
                   8670:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8671:                                   &escape($udom),$tryserver);
                   8672:                 if ($listing eq 'unknown_cmd') {
                   8673: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8674: 				      $udom, $tryserver);
                   8675:                 } else {
                   8676:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8677:                 }
1.841     albertel 8678: 		if ($listing eq 'unknown_cmd') {
                   8679: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8680: 				      $udom, $tryserver);
                   8681: 		    @listing_results = split(/:/,$listing);
                   8682: 		} else {
                   8683: 		    @listing_results =
                   8684: 			map { &unescape($_); } split(/:/,$listing);
                   8685: 		}
1.1136    raeburn  8686:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8687:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8688:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8689:                     $listerror{$tryserver} = $listing;
                   8690:                 } else {
1.841     albertel 8691: 		    foreach my $line (@listing_results) {
                   8692: 			my ($entry) = split(/&/,$line,2);
                   8693: 			$allusers{$entry} = 1;
                   8694: 		    }
                   8695: 		}
1.253     stredwic 8696:             }
1.1136    raeburn  8697:             my @alluserslist=();
1.800     albertel 8698:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8699:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8700:             }
1.1136    raeburn  8701:             return (\@alluserslist);
1.253     stredwic 8702:         } else {
1.1136    raeburn  8703:             return ([],'missing username');
1.253     stredwic 8704:         }
1.955     raeburn  8705:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8706:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8707:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8708:         return (\@all_domains);
1.955     raeburn  8709:     } else {
1.1136    raeburn  8710:         return ([],'missing domain');
1.275     stredwic 8711:     }
                   8712: }
                   8713: 
                   8714: # --------------------------------------------- GetFileTimestamp
                   8715: # This function utilizes dirlist and returns the date stamp for
                   8716: # when it was last modified.  It will also return an error of -1
                   8717: # if an error occurs
                   8718: 
                   8719: sub GetFileTimestamp {
1.955     raeburn  8720:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8721:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8722:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8723:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8724:                                     undef,$getuserdir);
                   8725:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8726:         return -1;
                   8727:     }
                   8728:     if (ref($fileref) eq 'ARRAY') {
                   8729:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8730:         # @stats contains first the filename, then the stat output
                   8731:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8732:     } else {
                   8733:         return -1;
1.253     stredwic 8734:     }
1.26      www      8735: }
                   8736: 
1.712     albertel 8737: sub stat_file {
                   8738:     my ($uri) = @_;
1.787     albertel 8739:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8740: 
1.955     raeburn  8741:     my ($udom,$uname,$file);
1.712     albertel 8742:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8743: 	($udom,$uname,$file) =
1.811     albertel 8744: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8745: 	$file = 'userfiles/'.$file;
                   8746:     }
                   8747:     if ($uri =~ m-^/res/-) {
                   8748: 	($udom,$uname) = 
1.807     albertel 8749: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8750: 	$file = $uri;
                   8751:     }
                   8752: 
                   8753:     if (!$udom || !$uname || !$file) {
                   8754: 	# unable to handle the uri
                   8755: 	return ();
                   8756:     }
1.956     raeburn  8757:     my $getpropath;
                   8758:     if ($file =~ /^userfiles\//) {
                   8759:         $getpropath = 1;
                   8760:     }
1.1136    raeburn  8761:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8762:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8763:         return ();
                   8764:     } else {
                   8765:         if (ref($listref) eq 'ARRAY') {
                   8766:             my @stats = split('&',$listref->[0]);
                   8767: 	    shift(@stats); #filename is first
                   8768: 	    return @stats;
                   8769:         }
1.712     albertel 8770:     }
                   8771:     return ();
                   8772: }
                   8773: 
1.26      www      8774: # -------------------------------------------------------- Value of a Condition
                   8775: 
1.713     albertel 8776: # gets the value of a specific preevaluated condition
                   8777: #    stored in the string  $env{user.state.<cid>}
                   8778: # or looks up a condition reference in the bighash and if if hasn't
                   8779: # already been evaluated recurses into docondval to get the value of
                   8780: # the condition, then memoizing it to 
                   8781: #   $env{user.state.<cid>.<condition>}
1.40      www      8782: sub directcondval {
                   8783:     my $number=shift;
1.620     albertel 8784:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8785: 	&Apache::lonuserstate::evalstate();
                   8786:     }
1.713     albertel 8787:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8788: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8789:     } elsif ($number =~ /^_/) {
                   8790: 	my $sub_condition;
                   8791: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8792: 		&GDBM_READER(),0640)) {
                   8793: 	    $sub_condition=$bighash{'conditions'.$number};
                   8794: 	    untie(%bighash);
                   8795: 	}
                   8796: 	my $value = &docondval($sub_condition);
1.949     raeburn  8797: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8798: 	return $value;
                   8799:     }
1.620     albertel 8800:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8801:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8802:     } else {
                   8803:        return 2;
                   8804:     }
                   8805: }
                   8806: 
1.713     albertel 8807: # get the collection of conditions for this resource
1.26      www      8808: sub condval {
                   8809:     my $condidx=shift;
1.54      www      8810:     my $allpathcond='';
1.713     albertel 8811:     foreach my $cond (split(/\|/,$condidx)) {
                   8812: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8813: 	    $allpathcond.=
                   8814: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8815: 	}
1.191     harris41 8816:     }
1.54      www      8817:     $allpathcond=~s/\|$//;
1.713     albertel 8818:     return &docondval($allpathcond);
                   8819: }
                   8820: 
                   8821: #evaluates an expression of conditions
                   8822: sub docondval {
                   8823:     my ($allpathcond) = @_;
                   8824:     my $result=0;
                   8825:     if ($env{'request.course.id'}
                   8826: 	&& defined($allpathcond)) {
                   8827: 	my $operand='|';
                   8828: 	my @stack;
                   8829: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8830: 	    if ($chunk eq '(') {
                   8831: 		push @stack,($operand,$result);
                   8832: 	    } elsif ($chunk eq ')') {
                   8833: 		my $before=pop @stack;
                   8834: 		if (pop @stack eq '&') {
                   8835: 		    $result=$result>$before?$before:$result;
                   8836: 		} else {
                   8837: 		    $result=$result>$before?$result:$before;
                   8838: 		}
                   8839: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8840: 		$operand=$chunk;
                   8841: 	    } else {
                   8842: 		my $new=directcondval($chunk);
                   8843: 		if ($operand eq '&') {
                   8844: 		    $result=$result>$new?$new:$result;
                   8845: 		} else {
                   8846: 		    $result=$result>$new?$result:$new;
                   8847: 		}
                   8848: 	    }
                   8849: 	}
1.26      www      8850:     }
                   8851:     return $result;
1.421     albertel 8852: }
                   8853: 
                   8854: # ---------------------------------------------------- Devalidate courseresdata
                   8855: 
                   8856: sub devalidatecourseresdata {
                   8857:     my ($coursenum,$coursedomain)=@_;
                   8858:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8859:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8860: }
                   8861: 
1.763     www      8862: 
1.200     www      8863: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8864: #
                   8865: #  Parameters:
                   8866: #      $coursenum    - Number of the course.
                   8867: #      $coursedomain - Domain at which the course was created.
                   8868: #  Returns:
                   8869: #     A hash of the course parameters along (I think) with timestamps
                   8870: #     and version info.
1.877     foxr     8871: 
1.624     albertel 8872: sub get_courseresdata {
                   8873:     my ($coursenum,$coursedomain)=@_;
1.200     www      8874:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8875:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8876:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8877:     my %dumpreply;
1.417     albertel 8878:     unless (defined($cached)) {
1.624     albertel 8879: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8880: 	$result=\%dumpreply;
1.251     albertel 8881: 	my ($tmp) = keys(%dumpreply);
                   8882: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8883: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8884: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8885: 	    return $tmp;
1.416     albertel 8886: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8887: 	    $result=undef;
1.599     albertel 8888: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8889: 	}
                   8890:     }
1.624     albertel 8891:     return $result;
                   8892: }
                   8893: 
1.633     albertel 8894: sub devalidateuserresdata {
                   8895:     my ($uname,$udom)=@_;
                   8896:     my $hashid="$udom:$uname";
                   8897:     &devalidate_cache_new('userres',$hashid);
                   8898: }
                   8899: 
1.624     albertel 8900: sub get_userresdata {
                   8901:     my ($uname,$udom)=@_;
                   8902:     #most student don\'t have any data set, check if there is some data
                   8903:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8904: 
                   8905:     my $hashid="$udom:$uname";
                   8906:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8907:     if (!defined($cached)) {
                   8908: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8909: 	$result=\%resourcedata;
                   8910: 	&do_cache_new('userres',$hashid,$result,600);
                   8911:     }
                   8912:     my ($tmp)=keys(%$result);
                   8913:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8914: 	return $result;
                   8915:     }
                   8916:     #error 2 occurs when the .db doesn't exist
                   8917:     if ($tmp!~/error: 2 /) {
1.672     albertel 8918: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8919: 		 " Trying to get resource data for ".
                   8920: 		 $uname." at ".$udom.": ".
                   8921: 		 $tmp."</font>");
                   8922:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8923: 	#&EXT_cache_set($udom,$uname);
                   8924: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8925: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8926:     }
                   8927:     return $tmp;
                   8928: }
1.879     foxr     8929: #----------------------------------------------- resdata - return resource data
                   8930: #  Purpose:
                   8931: #    Return resource data for either users or for a course.
                   8932: #  Parameters:
                   8933: #     $name      - Course/user name.
                   8934: #     $domain    - Name of the domain the user/course is registered on.
                   8935: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8936: #     @which     - Array of names of resources desired.
                   8937: #  Returns:
                   8938: #     The value of the first reasource in @which that is found in the
                   8939: #     resource hash.
                   8940: #  Exceptional Conditions:
                   8941: #     If the $type passed in is not valid (not the string 'course' or 
                   8942: #     'user', an undefined  reference is returned.
                   8943: #     If none of the resources are found, an undef is returned
1.624     albertel 8944: sub resdata {
                   8945:     my ($name,$domain,$type,@which)=@_;
                   8946:     my $result;
                   8947:     if ($type eq 'course') {
                   8948: 	$result=&get_courseresdata($name,$domain);
                   8949:     } elsif ($type eq 'user') {
                   8950: 	$result=&get_userresdata($name,$domain);
                   8951:     }
                   8952:     if (!ref($result)) { return $result; }    
1.251     albertel 8953:     foreach my $item (@which) {
1.927     albertel 8954: 	if (defined($result->{$item->[0]})) {
                   8955: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8956: 	}
1.250     albertel 8957:     }
1.291     albertel 8958:     return undef;
1.200     www      8959: }
                   8960: 
1.379     matthew  8961: #
                   8962: # EXT resource caching routines
                   8963: #
                   8964: 
                   8965: sub clear_EXT_cache_status {
1.383     albertel 8966:     &delenv('cache.EXT.');
1.379     matthew  8967: }
                   8968: 
                   8969: sub EXT_cache_status {
                   8970:     my ($target_domain,$target_user) = @_;
1.383     albertel 8971:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8972:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8973:         # We know already the user has no data
                   8974:         return 1;
                   8975:     } else {
                   8976:         return 0;
                   8977:     }
                   8978: }
                   8979: 
                   8980: sub EXT_cache_set {
                   8981:     my ($target_domain,$target_user) = @_;
1.383     albertel 8982:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8983:     #&appenv({$cachename => time});
1.379     matthew  8984: }
                   8985: 
1.28      www      8986: # --------------------------------------------------------- Value of a Variable
1.58      www      8987: sub EXT {
1.715     albertel 8988: 
1.395     albertel 8989:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8990:     unless ($varname) { return ''; }
1.218     albertel 8991:     #get real user name/domain, courseid and symb
                   8992:     my $courseid;
1.359     albertel 8993:     my $publicuser;
1.427     www      8994:     if ($symbparm) {
                   8995: 	$symbparm=&get_symb_from_alias($symbparm);
                   8996:     }
1.218     albertel 8997:     if (!($uname && $udom)) {
1.790     albertel 8998:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8999:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9000:     } else {
1.620     albertel 9001: 	$courseid=$env{'request.course.id'};
1.218     albertel 9002:     }
1.48      www      9003:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9004:     my $rest;
1.320     albertel 9005:     if (defined($therest[0])) {
1.48      www      9006:        $rest=join('.',@therest);
                   9007:     } else {
                   9008:        $rest='';
                   9009:     }
1.320     albertel 9010: 
1.57      www      9011:     my $qualifierrest=$qualifier;
                   9012:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9013:     my $spacequalifierrest=$space;
                   9014:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9015:     if ($realm eq 'user') {
1.48      www      9016: # --------------------------------------------------------------- user.resource
                   9017: 	if ($space eq 'resource') {
1.651     albertel 9018: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9019: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9020: 		 &&
1.744     albertel 9021: 		 ($symbparm eq &symbread()) ) {	
                   9022: 		# if we are in the middle of processing the resource the
                   9023: 		# get the value we are planning on committing
                   9024:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9025:                     return $Apache::lonhomework::results{$qualifierrest};
                   9026:                 } else {
                   9027:                     return $Apache::lonhomework::history{$qualifierrest};
                   9028:                 }
1.335     albertel 9029: 	    } else {
1.359     albertel 9030: 		my %restored;
1.620     albertel 9031: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9032: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9033: 		} else {
                   9034: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9035: 		}
1.335     albertel 9036: 		return $restored{$qualifierrest};
                   9037: 	    }
1.48      www      9038: # ----------------------------------------------------------------- user.access
                   9039:         } elsif ($space eq 'access') {
1.218     albertel 9040: 	    # FIXME - not supporting calls for a specific user
1.48      www      9041:             return &allowed($qualifier,$rest);
                   9042: # ------------------------------------------ user.preferences, user.environment
                   9043:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9044: 	    if (($uname eq $env{'user.name'}) &&
                   9045: 		($udom eq $env{'user.domain'})) {
                   9046: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9047: 	    } else {
1.359     albertel 9048: 		my %returnhash;
                   9049: 		if (!$publicuser) {
                   9050: 		    %returnhash=&userenvironment($udom,$uname,
                   9051: 						 $qualifierrest);
                   9052: 		}
1.218     albertel 9053: 		return $returnhash{$qualifierrest};
                   9054: 	    }
1.48      www      9055: # ----------------------------------------------------------------- user.course
                   9056:         } elsif ($space eq 'course') {
1.218     albertel 9057: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9058:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9059: # ------------------------------------------------------------------- user.role
                   9060:         } elsif ($space eq 'role') {
1.218     albertel 9061: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9062:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9063:             if ($qualifier eq 'value') {
                   9064: 		return $role;
                   9065:             } elsif ($qualifier eq 'extent') {
                   9066:                 return $where;
                   9067:             }
                   9068: # ----------------------------------------------------------------- user.domain
                   9069:         } elsif ($space eq 'domain') {
1.218     albertel 9070:             return $udom;
1.48      www      9071: # ------------------------------------------------------------------- user.name
                   9072:         } elsif ($space eq 'name') {
1.218     albertel 9073:             return $uname;
1.48      www      9074: # ---------------------------------------------------- Any other user namespace
1.29      www      9075:         } else {
1.359     albertel 9076: 	    my %reply;
                   9077: 	    if (!$publicuser) {
                   9078: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9079: 	    }
                   9080: 	    return $reply{$qualifierrest};
1.48      www      9081:         }
1.236     www      9082:     } elsif ($realm eq 'query') {
                   9083: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9084:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9085: 						[$spacequalifierrest]);
1.620     albertel 9086: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9087:    } elsif ($realm eq 'request') {
1.48      www      9088: # ------------------------------------------------------------- request.browser
                   9089:         if ($space eq 'browser') {
1.1145    bisitz   9090:             return $env{'browser.'.$qualifier};
1.57      www      9091: # ------------------------------------------------------------ request.filename
                   9092:         } else {
1.620     albertel 9093:             return $env{'request.'.$spacequalifierrest};
1.29      www      9094:         }
1.28      www      9095:     } elsif ($realm eq 'course') {
1.48      www      9096: # ---------------------------------------------------------- course.description
1.620     albertel 9097:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9098:     } elsif ($realm eq 'resource') {
1.165     www      9099: 
1.620     albertel 9100: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9101: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9102: 	}
1.693     albertel 9103: 
                   9104: 	if ($space eq 'title') {
                   9105: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9106: 	    return &gettitle($symbparm);
                   9107: 	}
                   9108: 	
                   9109: 	if ($space eq 'map') {
                   9110: 	    my ($map) = &decode_symb($symbparm);
                   9111: 	    return &symbread($map);
                   9112: 	}
1.905     albertel 9113: 	if ($space eq 'filename') {
                   9114: 	    if ($symbparm) {
                   9115: 		return &clutter((&decode_symb($symbparm))[2]);
                   9116: 	    }
                   9117: 	    return &hreflocation('',$env{'request.filename'});
                   9118: 	}
1.693     albertel 9119: 
                   9120: 	my ($section, $group, @groups);
1.593     albertel 9121: 	my ($courselevelm,$courselevel);
1.539     albertel 9122: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9123: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9124: 
1.218     albertel 9125: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9126: 
1.60      www      9127: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9128: 	    my $symbp=$symbparm;
1.735     albertel 9129: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9130: 
                   9131: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9132: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9133: 
1.620     albertel 9134: 	    if (($env{'user.name'} eq $uname) &&
                   9135: 		($env{'user.domain'} eq $udom)) {
                   9136: 		$section=$env{'request.course.sec'};
1.733     raeburn  9137:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9138:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9139: 	    } else {
1.539     albertel 9140: 		if (! defined($usection)) {
1.551     albertel 9141: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9142: 		} else {
                   9143: 		    $section = $usection;
                   9144: 		}
1.733     raeburn  9145:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9146: 	    }
                   9147: 
                   9148: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9149: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9150: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9151: 
1.593     albertel 9152: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9153: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9154: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9155: 
1.60      www      9156: # ----------------------------------------------------------- first, check user
1.624     albertel 9157: 
                   9158: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9159: 				       ([$courselevelr,'resource'],
                   9160: 					[$courselevelm,'map'     ],
                   9161: 					[$courselevel, 'course'  ]));
1.931     albertel 9162: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9163: 
1.594     albertel 9164: # ------------------------------------------------ second, check some of course
1.684     raeburn  9165:             my $coursereply;
1.691     raeburn  9166:             if (@groups > 0) {
                   9167:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9168:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9169:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9170:             }
1.96      www      9171: 
1.684     raeburn  9172: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9173: 				  $env{'course.'.$courseid.'.domain'},
                   9174: 				  'course',
                   9175: 				  ([$seclevelr,   'resource'],
                   9176: 				   [$seclevelm,   'map'     ],
                   9177: 				   [$seclevel,    'course'  ],
                   9178: 				   [$courselevelr,'resource']));
                   9179: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9180: 
1.60      www      9181: # ------------------------------------------------------ third, check map parms
1.218     albertel 9182: 	    my %parmhash=();
                   9183: 	    my $thisparm='';
                   9184: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9185: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9186: 		    &GDBM_READER(),0640)) {
1.218     albertel 9187: 		$thisparm=$parmhash{$symbparm};
                   9188: 		untie(%parmhash);
                   9189: 	    }
1.927     albertel 9190: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9191: 	}
1.594     albertel 9192: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9193: 
1.218     albertel 9194: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9195: 	my $filename;
                   9196: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9197: 	if ($symbparm) {
1.409     www      9198: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9199: 	} else {
1.620     albertel 9200: 	    $filename=$env{'request.filename'};
1.282     albertel 9201: 	}
                   9202: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9203: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9204: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9205: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9206: 
1.927     albertel 9207: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9208: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9209: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9210: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9211: 				     $env{'course.'.$courseid.'.domain'},
                   9212: 				     'course',
1.927     albertel 9213: 				     ([$courselevelm,'map'   ],
                   9214: 				      [$courselevel, 'course']));
                   9215: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9216: 	}
1.145     www      9217: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9218: 	unless ($space eq '0') {
1.336     albertel 9219: 	    my @parts=split(/_/,$space);
                   9220: 	    my $id=pop(@parts);
                   9221: 	    my $part=join('_',@parts);
                   9222: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9223: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9224: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9225: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9226: 	}
1.395     albertel 9227: 	if ($recurse) { return undef; }
                   9228: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9229: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9230: # ---------------------------------------------------- Any other user namespace
                   9231:     } elsif ($realm eq 'environment') {
                   9232: # ----------------------------------------------------------------- environment
1.620     albertel 9233: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9234: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9235: 	} else {
1.770     albertel 9236: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9237: 		return '';
                   9238: 	    }
1.219     albertel 9239: 	    my %returnhash=&userenvironment($udom,$uname,
                   9240: 					    $spacequalifierrest);
                   9241: 	    return $returnhash{$spacequalifierrest};
                   9242: 	}
1.28      www      9243:     } elsif ($realm eq 'system') {
1.48      www      9244: # ----------------------------------------------------------------- system.time
                   9245: 	if ($space eq 'time') {
                   9246: 	    return time;
                   9247:         }
1.696     albertel 9248:     } elsif ($realm eq 'server') {
                   9249: # ----------------------------------------------------------------- system.time
                   9250: 	if ($space eq 'name') {
                   9251: 	    return $ENV{'SERVER_NAME'};
                   9252:         }
1.28      www      9253:     }
1.48      www      9254:     return '';
1.61      www      9255: }
                   9256: 
1.927     albertel 9257: sub get_reply {
                   9258:     my ($reply_value) = @_;
1.940     raeburn  9259:     if (ref($reply_value) eq 'ARRAY') {
                   9260:         if (wantarray) {
                   9261: 	    return @$reply_value;
                   9262:         }
                   9263:         return $reply_value->[0];
                   9264:     } else {
                   9265:         return $reply_value;
1.927     albertel 9266:     }
                   9267: }
                   9268: 
1.691     raeburn  9269: sub check_group_parms {
                   9270:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9271:     my @groupitems = ();
                   9272:     my $resultitem;
1.927     albertel 9273:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9274:     foreach my $group (@{$groups}) {
                   9275:         foreach my $level (@levels) {
1.927     albertel 9276:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9277:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9278:         }
                   9279:     }
                   9280:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9281:                             $env{'course.'.$courseid.'.domain'},
                   9282:                                      'course',@groupitems);
                   9283:     return $coursereply;
                   9284: }
                   9285: 
                   9286: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9287:     my ($courseid,@groups) = @_;
                   9288:     @groups = sort(@groups);
1.691     raeburn  9289:     return @groups;
                   9290: }
                   9291: 
1.395     albertel 9292: sub packages_tab_default {
                   9293:     my ($uri,$varname)=@_;
                   9294:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9295: 
                   9296:     my (@extension,@specifics,$do_default);
                   9297:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9298: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9299: 	if ($pack_type eq 'default') {
                   9300: 	    $do_default=1;
                   9301: 	} elsif ($pack_type eq 'extension') {
                   9302: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9303: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9304: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9305: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9306: 	}
                   9307:     }
                   9308:     # first look for a package that matches the requested part id
                   9309:     foreach my $package (@specifics) {
                   9310: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9311: 	next if ($pack_part ne $part);
                   9312: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9313: 	    return $packagetab{"$pack_type&$name&default"};
                   9314: 	}
                   9315:     }
                   9316:     # look for any possible matching non extension_ package
                   9317:     foreach my $package (@specifics) {
                   9318: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9319: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9320: 	    return $packagetab{"$pack_type&$name&default"};
                   9321: 	}
1.585     albertel 9322: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9323: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9324: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9325: 	}
                   9326:     }
1.738     albertel 9327:     # look for any posible extension_ match
                   9328:     foreach my $package (@extension) {
                   9329: 	my ($package,$pack_type)=@{$package};
                   9330: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9331: 	    return $packagetab{"$pack_type&$name&default"};
                   9332: 	}
                   9333: 	if (defined($packagetab{$package."&$name&default"})) {
                   9334: 	    return $packagetab{$package."&$name&default"};
                   9335: 	}
                   9336:     }
                   9337:     # look for a global default setting
                   9338:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9339: 	return $packagetab{"default&$name&default"};
                   9340:     }
1.395     albertel 9341:     return undef;
                   9342: }
                   9343: 
1.334     albertel 9344: sub add_prefix_and_part {
                   9345:     my ($prefix,$part)=@_;
                   9346:     my $keyroot;
                   9347:     if (defined($prefix) && $prefix !~ /^__/) {
                   9348: 	# prefix that has a part already
                   9349: 	$keyroot=$prefix;
                   9350:     } elsif (defined($prefix)) {
                   9351: 	# prefix that is missing a part
                   9352: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9353:     } else {
                   9354: 	# no prefix at all
                   9355: 	if (defined($part)) { $keyroot='_'.$part; }
                   9356:     }
                   9357:     return $keyroot;
                   9358: }
                   9359: 
1.71      www      9360: # ---------------------------------------------------------------- Get metadata
                   9361: 
1.599     albertel 9362: my %metaentry;
1.1070    www      9363: my %importedpartids;
1.71      www      9364: sub metadata {
1.176     www      9365:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9366:     $uri=&declutter($uri);
1.288     albertel 9367:     # if it is a non metadata possible uri return quickly
1.529     albertel 9368:     if (($uri eq '') || 
                   9369: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9370: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9371:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9372: 	return undef;
                   9373:     }
1.1140    www      9374:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9375: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9376: 	return undef;
1.288     albertel 9377:     }
1.73      www      9378:     my $filename=$uri;
                   9379:     $uri=~s/\.meta$//;
1.172     www      9380: #
                   9381: # Is the metadata already cached?
1.177     www      9382: # Look at timestamp of caching
1.172     www      9383: # Everything is cached by the main uri, libraries are never directly cached
                   9384: #
1.428     albertel 9385:     if (!defined($liburi)) {
1.599     albertel 9386: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9387: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9388:     }
                   9389:     {
1.1069    www      9390: # Imported parts would go here
1.1070    www      9391:         my %importedids=();
                   9392:         my @origfileimportpartids=();
1.1069    www      9393:         my $importedparts=0;
1.172     www      9394: #
                   9395: # Is this a recursive call for a library?
                   9396: #
1.599     albertel 9397: #	if (! exists($metacache{$uri})) {
                   9398: #	    $metacache{$uri}={};
                   9399: #	}
1.924     albertel 9400: 	my $cachetime = 60*60;
1.171     www      9401:         if ($liburi) {
                   9402: 	    $liburi=&declutter($liburi);
                   9403:             $filename=$liburi;
1.401     bowersj2 9404:         } else {
1.599     albertel 9405: 	    &devalidate_cache_new('meta',$uri);
                   9406: 	    undef(%metaentry);
1.401     bowersj2 9407: 	}
1.140     www      9408:         my %metathesekeys=();
1.73      www      9409:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9410: 	my $metastring;
1.1140    www      9411: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9412: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9413: 	    $metastring = 
1.929     albertel 9414: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9415: 					  ('grade_target' => 'meta'));
                   9416: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9417: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9418:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9419: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9420: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9421: 	    $metastring=&getfile($file);
1.489     albertel 9422: 	}
1.208     albertel 9423:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9424:         my $token;
1.140     www      9425:         undef %metathesekeys;
1.71      www      9426:         while ($token=$parser->get_token) {
1.339     albertel 9427: 	    if ($token->[0] eq 'S') {
                   9428: 		if (defined($token->[2]->{'package'})) {
1.172     www      9429: #
                   9430: # This is a package - get package info
                   9431: #
1.339     albertel 9432: 		    my $package=$token->[2]->{'package'};
                   9433: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9434: 		    if (defined($token->[2]->{'id'})) { 
                   9435: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9436: 		    }
1.599     albertel 9437: 		    if ($metaentry{':packages'}) {
                   9438: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9439: 		    } else {
1.599     albertel 9440: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9441: 		    }
1.736     albertel 9442: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9443: 			my $part=$keyroot;
                   9444: 			$part=~s/^\_//;
1.736     albertel 9445: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9446: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9447: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9448: 			    # ignore package.tab specified default values
                   9449:                             # here &package_tab_default() will fetch those
                   9450: 			    if ($subp eq 'default') { next; }
1.736     albertel 9451: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9452: 			    my $unikey;
                   9453: 			    if ($pack =~ /_0$/) {
                   9454: 				$unikey='parameter_0_'.$name;
                   9455: 				$part=0;
                   9456: 			    } else {
                   9457: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9458: 			    }
1.339     albertel 9459: 			    if ($subp eq 'display') {
                   9460: 				$value.=' [Part: '.$part.']';
                   9461: 			    }
1.599     albertel 9462: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9463: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9464: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9465: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9466: 			    }
1.599     albertel 9467: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9468: 				$metaentry{':'.$unikey}=
                   9469: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9470: 			    }
1.339     albertel 9471: 			}
                   9472: 		    }
                   9473: 		} else {
1.172     www      9474: #
                   9475: # This is not a package - some other kind of start tag
1.339     albertel 9476: #
                   9477: 		    my $entry=$token->[1];
1.1068    www      9478: 		    my $unikey='';
1.175     www      9479: 
1.339     albertel 9480: 		    if ($entry eq 'import') {
1.175     www      9481: #
                   9482: # Importing a library here
1.339     albertel 9483: #
1.1067    www      9484:                         my $location=$parser->get_text('/import');
                   9485:                         my $dir=$filename;
                   9486:                         $dir=~s|[^/]*$||;
                   9487:                         $location=&filelocation($dir,$location);
1.1069    www      9488:                        
1.1068    www      9489:                         my $importmode=$token->[2]->{'importmode'};
                   9490:                         if ($importmode eq 'problem') {
1.1069    www      9491: # Import as problem/response
1.1068    www      9492:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9493:                         } elsif ($importmode eq 'part') {
                   9494: # Import as part(s)
1.1069    www      9495:                            $importedparts=1;
                   9496: # We need to get the original file and the imported file to get the part order correct
                   9497: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9498: # Load and inspect original file
1.1070    www      9499:                            if ($#origfileimportpartids<0) {
                   9500:                               undef(%importedpartids);
                   9501:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9502:                               my $origfile=&getfile($origfilelocation);
                   9503:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9504:                            }
                   9505: 
1.1069    www      9506: # Load and inspect imported file
                   9507:                            my $impfile=&getfile($location);
                   9508:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9509:                            if ($#impfilepartids>=0) {
                   9510: # This problem had parts
1.1070    www      9511:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9512:                            } else {
                   9513: # Importing by turning a single problem into a problem part
                   9514: # It gets the import-tags ID as part-ID
                   9515:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9516:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9517:                            }
1.1068    www      9518:                         } else {
                   9519: # Normal import
                   9520:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9521:                            if (defined($token->[2]->{'id'})) {
                   9522:                               $unikey.='_'.$token->[2]->{'id'};
                   9523:                            }
1.1067    www      9524:                         }
                   9525: 
1.339     albertel 9526: 			if ($depthcount<20) {
1.736     albertel 9527: 			    my $metadata = 
                   9528: 				&metadata($uri,'keys', $location,$unikey,
                   9529: 					  $depthcount+1);
                   9530: 			    foreach my $meta (split(',',$metadata)) {
                   9531: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9532: 				$metathesekeys{$meta}=1;
1.339     albertel 9533: 			    }
1.1068    www      9534: 			
                   9535:                         }
1.1067    www      9536: 		    } else {
                   9537: #
                   9538: # Not importing, some other kind of non-package, non-library start tag
                   9539: # 
                   9540:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9541:                         if (defined($token->[2]->{'id'})) {
                   9542:                             $unikey.='_'.$token->[2]->{'id'};
                   9543:                         }
1.339     albertel 9544: 			if (defined($token->[2]->{'name'})) { 
                   9545: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9546: 			}
                   9547: 			$metathesekeys{$unikey}=1;
1.736     albertel 9548: 			foreach my $param (@{$token->[3]}) {
                   9549: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9550: 				$token->[2]->{$param};
1.339     albertel 9551: 			}
                   9552: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9553: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9554: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9555: 		 # only ws inside the tag, and not in default, so use default
                   9556: 		 # as value
1.599     albertel 9557: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9558: 			} elsif ( $internaltext =~ /\S/ ) {
                   9559: 		  # something interesting inside the tag
                   9560: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9561: 			} else {
1.908     albertel 9562: 		  # no interesting values, don't set a default
1.339     albertel 9563: 			}
1.172     www      9564: # end of not-a-package not-a-library import
1.339     albertel 9565: 		    }
1.172     www      9566: # end of not-a-package start tag
1.339     albertel 9567: 		}
1.172     www      9568: # the next is the end of "start tag"
1.339     albertel 9569: 	    }
                   9570: 	}
1.483     albertel 9571: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9572: 	$extension = lc($extension);
                   9573: 	if ($extension eq 'htm') { $extension='html'; }
                   9574: 
1.737     albertel 9575: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9576: 	    #no specific packages #how's our extension
                   9577: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9578: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9579: 					 \%metathesekeys);
                   9580: 	}
1.883     albertel 9581: 
                   9582: 	if (!exists($metaentry{':packages'})
                   9583: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9584: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9585: 		#no specific packages well let's get default then
                   9586: 		if ($key!~/^default&/) { next; }
1.488     albertel 9587: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9588: 					     \%metathesekeys);
                   9589: 	    }
                   9590: 	}
1.338     www      9591: # are there custom rights to evaluate
1.599     albertel 9592: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9593: 
1.338     www      9594:     #
                   9595:     # Importing a rights file here
1.339     albertel 9596:     #
                   9597: 	    unless ($depthcount) {
1.599     albertel 9598: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9599: 		my $dir=$filename;
                   9600: 		$dir=~s|[^/]*$||;
                   9601: 		$location=&filelocation($dir,$location);
1.736     albertel 9602: 		my $rights_metadata =
                   9603: 		    &metadata($uri,'keys',$location,'_rights',
                   9604: 			      $depthcount+1);
                   9605: 		foreach my $rights (split(',',$rights_metadata)) {
                   9606: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9607: 		    $metathesekeys{$rights}=1;
1.339     albertel 9608: 		}
                   9609: 	    }
                   9610: 	}
1.737     albertel 9611: 	# uniqifiy package listing
                   9612: 	my %seen;
                   9613: 	my @uniq_packages =
                   9614: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9615: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9616: 
1.1070    www      9617:         if ($importedparts) {
                   9618: # We had imported parts and need to rebuild partorder
                   9619:            $metaentry{':partorder'}='';
                   9620:            $metathesekeys{'partorder'}=1;
                   9621:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9622:                if ($origfileimportpartids[$index] eq 'part') {
                   9623: # original part, part of the problem
                   9624:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9625:                } else {
                   9626: # we have imported parts at this position
                   9627:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9628:                }
                   9629:            }
                   9630:            $metaentry{':partorder'}=~s/^\,//;
                   9631:         }
                   9632: 
1.737     albertel 9633: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9634: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9635: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9636: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9637: # this is the end of "was not already recently cached
1.71      www      9638:     }
1.599     albertel 9639:     return $metaentry{':'.$what};
1.261     albertel 9640: }
                   9641: 
1.488     albertel 9642: sub metadata_create_package_def {
1.483     albertel 9643:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9644:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9645:     if ($subp eq 'default') { next; }
                   9646:     
1.599     albertel 9647:     if (defined($metaentry{':packages'})) {
                   9648: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9649:     } else {
1.599     albertel 9650: 	$metaentry{':packages'}=$package;
1.483     albertel 9651:     }
                   9652:     my $value=$packagetab{$key};
                   9653:     my $unikey;
                   9654:     $unikey='parameter_0_'.$name;
1.599     albertel 9655:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9656:     $$metathesekeys{$unikey}=1;
1.599     albertel 9657:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9658: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9659:     }
1.599     albertel 9660:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9661: 	$metaentry{':'.$unikey}=
                   9662: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9663:     }
                   9664: }
                   9665: 
1.261     albertel 9666: sub metadata_generate_part0 {
                   9667:     my ($metadata,$metacache,$uri) = @_;
                   9668:     my %allnames;
1.737     albertel 9669:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9670: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9671: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9672: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9673: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9674: 	    $allnames{$name}=$part;
                   9675: 	  }
                   9676: 	}
                   9677:     }
                   9678:     foreach my $name (keys(%allnames)) {
                   9679:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9680:       my $key=":parameter_0_$name";
1.261     albertel 9681:       $$metacache{"$key.part"}='0';
                   9682:       $$metacache{"$key.name"}=$name;
1.428     albertel 9683:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9684: 					   $allnames{$name}.'_'.$name.
                   9685: 					   '.type'};
1.428     albertel 9686:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9687: 			     '.display'};
1.644     www      9688:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9689:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9690:       $$metacache{"$key.display"}=$olddis;
                   9691:     }
1.71      www      9692: }
                   9693: 
1.764     albertel 9694: # ------------------------------------------------------ Devalidate title cache
                   9695: 
                   9696: sub devalidate_title_cache {
                   9697:     my ($url)=@_;
                   9698:     if (!$env{'request.course.id'}) { return; }
                   9699:     my $symb=&symbread($url);
                   9700:     if (!$symb) { return; }
                   9701:     my $key=$env{'request.course.id'}."\0".$symb;
                   9702:     &devalidate_cache_new('title',$key);
                   9703: }
                   9704: 
1.1014    droeschl 9705: # ------------------------------------------------- Get the title of a course
                   9706: 
                   9707: sub current_course_title {
                   9708:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9709: }
1.301     www      9710: # ------------------------------------------------- Get the title of a resource
                   9711: 
                   9712: sub gettitle {
                   9713:     my $urlsymb=shift;
                   9714:     my $symb=&symbread($urlsymb);
1.534     albertel 9715:     if ($symb) {
1.620     albertel 9716: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9717: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9718: 	if (defined($cached)) { 
                   9719: 	    return $result;
                   9720: 	}
1.534     albertel 9721: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9722: 	my $title='';
1.907     albertel 9723: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9724: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9725: 	} else {
                   9726: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9727: 		    &GDBM_READER(),0640)) {
                   9728: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9729: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9730: 		untie(%bighash);
                   9731: 	    }
1.534     albertel 9732: 	}
                   9733: 	$title=~s/\&colon\;/\:/gs;
                   9734: 	if ($title) {
1.1159    www      9735: # Remember both $symb and $title for dynamic metadata
                   9736:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9737:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9738: # Cache this title and then return it
1.599     albertel 9739: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9740: 	}
                   9741: 	$urlsymb=$url;
                   9742:     }
                   9743:     my $title=&metadata($urlsymb,'title');
                   9744:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9745:     return $title;
1.301     www      9746: }
1.613     albertel 9747: 
1.614     albertel 9748: sub get_slot {
                   9749:     my ($which,$cnum,$cdom)=@_;
                   9750:     if (!$cnum || !$cdom) {
1.790     albertel 9751: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9752: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9753: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9754:     }
1.703     albertel 9755:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9756:     my %slotinfo;
                   9757:     if (exists($remembered{$key})) {
                   9758: 	$slotinfo{$which} = $remembered{$key};
                   9759:     } else {
                   9760: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9761: 	&Apache::lonhomework::showhash(%slotinfo);
                   9762: 	my ($tmp)=keys(%slotinfo);
                   9763: 	if ($tmp=~/^error:/) { return (); }
                   9764: 	$remembered{$key} = $slotinfo{$which};
                   9765:     }
1.616     albertel 9766:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9767: 	return %{$slotinfo{$which}};
                   9768:     }
                   9769:     return $slotinfo{$which};
1.614     albertel 9770: }
1.1150    raeburn  9771: 
                   9772: sub get_reservable_slots {
                   9773:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9774:     my $now = time;
                   9775:     my $reservable_info;
                   9776:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9777:     if (exists($remembered{$key})) {
                   9778:         $reservable_info = $remembered{$key};
                   9779:     } else {
                   9780:         my %resv;
                   9781:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9782:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9783:         $reservable_info = \%resv;
                   9784:         $remembered{$key} = $reservable_info;
                   9785:     }
                   9786:     return $reservable_info;
                   9787: }
                   9788: 
                   9789: sub get_course_slots {
                   9790:     my ($cnum,$cdom) = @_;
                   9791:     my $hashid=$cnum.':'.$cdom;
                   9792:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9793:     if (defined($cached)) {
                   9794:         if (ref($result) eq 'HASH') {
                   9795:             return %{$result};
                   9796:         }
                   9797:     } else {
                   9798:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9799:         my ($tmp) = keys(%slots);
                   9800:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9801:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9802:             return %slots;
                   9803:         }
                   9804:     }
                   9805:     return;
                   9806: }
                   9807: 
                   9808: sub devalidate_slots_cache {
                   9809:     my ($cnum,$cdom)=@_;
                   9810:     my $hashid=$cnum.':'.$cdom;
                   9811:     &devalidate_cache_new('allslots',$hashid);
                   9812: }
                   9813: 
1.31      www      9814: # ------------------------------------------------- Update symbolic store links
                   9815: 
                   9816: sub symblist {
                   9817:     my ($mapname,%newhash)=@_;
1.438     www      9818:     $mapname=&deversion(&declutter($mapname));
1.31      www      9819:     my %hash;
1.620     albertel 9820:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9821:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9822:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9823: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9824: 		next if ($url eq 'last_known'
                   9825: 			 && $env{'form.no_update_last_known'});
                   9826: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9827: 						    $newhash{$url}->[1],
                   9828: 						    $newhash{$url}->[0]);
1.191     harris41 9829:             }
1.31      www      9830:             if (untie(%hash)) {
                   9831: 		return 'ok';
                   9832:             }
                   9833:         }
                   9834:     }
                   9835:     return 'error';
1.212     www      9836: }
                   9837: 
                   9838: # --------------------------------------------------------------- Verify a symb
                   9839: 
                   9840: sub symbverify {
1.510     www      9841:     my ($symb,$thisurl)=@_;
                   9842:     my $thisfn=$thisurl;
1.439     www      9843:     $thisfn=&declutter($thisfn);
1.215     www      9844: # direct jump to resource in page or to a sequence - will construct own symbs
                   9845:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9846: # check URL part
1.409     www      9847:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9848: 
1.431     www      9849:     unless ($url eq $thisfn) { return 0; }
1.213     www      9850: 
1.216     www      9851:     $symb=&symbclean($symb);
1.510     www      9852:     $thisurl=&deversion($thisurl);
1.439     www      9853:     $thisfn=&deversion($thisfn);
1.213     www      9854: 
                   9855:     my %bighash;
                   9856:     my $okay=0;
1.431     www      9857: 
1.620     albertel 9858:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9859:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9860:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9861:             $thisurl =~ s/\?.+$//;
                   9862:         }
1.510     www      9863:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9864:         unless ($ids) {
                   9865:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9866:             $ids=$bighash{$idkey};
1.216     www      9867:         }
                   9868:         if ($ids) {
                   9869: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9870: 	    foreach my $id (split(/\,/,$ids)) {
                   9871: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9872:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9873:                    $symb =~ s/\?.+$//;
                   9874:                }
1.216     www      9875:                if (
                   9876:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9877:    eq $symb) { 
1.620     albertel 9878: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9879: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9880:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9881: 		       $okay=1; 
                   9882: 		   }
                   9883: 	       }
1.216     www      9884: 	   }
                   9885:         }
1.213     www      9886: 	untie(%bighash);
                   9887:     }
                   9888:     return $okay;
1.31      www      9889: }
                   9890: 
1.210     www      9891: # --------------------------------------------------------------- Clean-up symb
                   9892: 
                   9893: sub symbclean {
                   9894:     my $symb=shift;
1.568     albertel 9895:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9896: # remove version from map
                   9897:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9898: 
1.210     www      9899: # remove version from URL
                   9900:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9901: 
1.507     www      9902: # remove wrapper
                   9903: 
1.510     www      9904:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9905:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9906:     return $symb;
1.409     www      9907: }
                   9908: 
                   9909: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9910: 
                   9911: sub encode_symb {
                   9912:     my ($map,$resid,$url)=@_;
                   9913:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9914: }
1.409     www      9915: 
                   9916: sub decode_symb {
1.568     albertel 9917:     my $symb=shift;
                   9918:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9919:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9920:     return (&fixversion($map),$resid,&fixversion($url));
                   9921: }
                   9922: 
                   9923: sub fixversion {
                   9924:     my $fn=shift;
1.609     banghart 9925:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9926:     my %bighash;
                   9927:     my $uri=&clutter($fn);
1.620     albertel 9928:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9929: # is this cached?
1.599     albertel 9930:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9931:     if (defined($cached)) { return $result; }
                   9932: # unfortunately not cached, or expired
1.620     albertel 9933:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9934: 	    &GDBM_READER(),0640)) {
                   9935:  	if ($bighash{'version_'.$uri}) {
                   9936:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9937:  	    unless (($version eq 'mostrecent') || 
                   9938: 		    ($version==&getversion($uri))) {
1.440     www      9939:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9940:  	    }
                   9941:  	}
                   9942:  	untie %bighash;
1.413     www      9943:     }
1.599     albertel 9944:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9945: }
                   9946: 
                   9947: sub deversion {
                   9948:     my $url=shift;
                   9949:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9950:     return $url;
1.210     www      9951: }
                   9952: 
1.31      www      9953: # ------------------------------------------------------ Return symb list entry
                   9954: 
                   9955: sub symbread {
1.249     www      9956:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9957:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9958:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9959: # no filename provided? try from environment
1.44      www      9960:     unless ($thisfn) {
1.620     albertel 9961:         if ($env{'request.symb'}) {
                   9962: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9963: 	}
1.620     albertel 9964: 	$thisfn=$env{'request.filename'};
1.44      www      9965:     }
1.569     albertel 9966:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9967: # is that filename actually a symb? Verify, clean, and return
                   9968:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9969: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9970: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9971: 	}
1.242     www      9972:     }
1.44      www      9973:     $thisfn=declutter($thisfn);
1.31      www      9974:     my %hash;
1.37      www      9975:     my %bighash;
                   9976:     my $syval='';
1.620     albertel 9977:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9978:         my $targetfn = $thisfn;
1.609     banghart 9979:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9980:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9981:         }
1.687     albertel 9982: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9983: 	    $targetfn=$1;
                   9984: 	}
1.620     albertel 9985:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9986:                       &GDBM_READER(),0640)) {
1.481     raeburn  9987: 	    $syval=$hash{$targetfn};
1.37      www      9988:             untie(%hash);
                   9989:         }
                   9990: # ---------------------------------------------------------- There was an entry
                   9991:         if ($syval) {
1.601     albertel 9992: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9993: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9994: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9995: 		    #return $env{$cache_str}='';
1.601     albertel 9996: 		#}    
                   9997: 		#$syval.=$1;
                   9998: 	    #}
1.37      www      9999:         } else {
                   10000: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10001:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10002:                             &GDBM_READER(),0640)) {
1.37      www      10003: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10004:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10005:               unless ($ids) { 
                   10006:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10007:               }
                   10008:               unless ($ids) {
                   10009: # alias?
                   10010: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10011:               }
1.37      www      10012:               if ($ids) {
                   10013: # ------------------------------------------------------------------- Has ID(s)
                   10014:                  my @possibilities=split(/\,/,$ids);
1.39      www      10015:                  if ($#possibilities==0) {
                   10016: # ----------------------------------------------- There is only one possibility
1.37      www      10017: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10018: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10019: 						    $resid,$thisfn);
1.249     www      10020:                  } elsif (!$donotrecurse) {
1.39      www      10021: # ------------------------------------------ There is more than one possibility
                   10022:                      my $realpossible=0;
1.800     albertel 10023:                      foreach my $id (@possibilities) {
                   10024: 			 my $file=$bighash{'src_'.$id};
1.39      www      10025:                          if (&allowed('bre',$file)) {
1.800     albertel 10026:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10027:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10028: 				$realpossible++;
1.626     albertel 10029:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10030: 						    $resid,$thisfn);
1.39      www      10031:                             }
                   10032: 			 }
1.191     harris41 10033:                      }
1.39      www      10034: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10035:                  } else {
                   10036:                      $syval='';
1.37      www      10037:                  }
                   10038: 	      }
                   10039:               untie(%bighash)
1.481     raeburn  10040:            }
1.31      www      10041:         }
1.62      www      10042:         if ($syval) {
1.620     albertel 10043: 	    return $env{$cache_str}=$syval;
1.62      www      10044:         }
1.31      www      10045:     }
1.949     raeburn  10046:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10047:     return $env{$cache_str}='';
1.31      www      10048: }
                   10049: 
                   10050: # ---------------------------------------------------------- Return random seed
                   10051: 
1.32      www      10052: sub numval {
                   10053:     my $txt=shift;
                   10054:     $txt=~tr/A-J/0-9/;
                   10055:     $txt=~tr/a-j/0-9/;
                   10056:     $txt=~tr/K-T/0-9/;
                   10057:     $txt=~tr/k-t/0-9/;
                   10058:     $txt=~tr/U-Z/0-5/;
                   10059:     $txt=~tr/u-z/0-5/;
                   10060:     $txt=~s/\D//g;
1.564     albertel 10061:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10062:     return int($txt);
1.368     albertel 10063: }
                   10064: 
1.484     albertel 10065: sub numval2 {
                   10066:     my $txt=shift;
                   10067:     $txt=~tr/A-J/0-9/;
                   10068:     $txt=~tr/a-j/0-9/;
                   10069:     $txt=~tr/K-T/0-9/;
                   10070:     $txt=~tr/k-t/0-9/;
                   10071:     $txt=~tr/U-Z/0-5/;
                   10072:     $txt=~tr/u-z/0-5/;
                   10073:     $txt=~s/\D//g;
                   10074:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10075:     my $total;
                   10076:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10077:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10078:     return int($total);
                   10079: }
                   10080: 
1.575     albertel 10081: sub numval3 {
                   10082:     use integer;
                   10083:     my $txt=shift;
                   10084:     $txt=~tr/A-J/0-9/;
                   10085:     $txt=~tr/a-j/0-9/;
                   10086:     $txt=~tr/K-T/0-9/;
                   10087:     $txt=~tr/k-t/0-9/;
                   10088:     $txt=~tr/U-Z/0-5/;
                   10089:     $txt=~tr/u-z/0-5/;
                   10090:     $txt=~s/\D//g;
                   10091:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10092:     my $total;
                   10093:     foreach my $val (@txts) { $total+=$val; }
                   10094:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10095:     return $total;
                   10096: }
                   10097: 
1.675     albertel 10098: sub digest {
                   10099:     my ($data)=@_;
                   10100:     my $digest=&Digest::MD5::md5($data);
                   10101:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10102:     my ($e,$f);
                   10103:     {
                   10104:         use integer;
                   10105:         $e=($a+$b);
                   10106:         $f=($c+$d);
                   10107:         if ($_64bit) {
                   10108:             $e=(($e<<32)>>32);
                   10109:             $f=(($f<<32)>>32);
                   10110:         }
                   10111:     }
                   10112:     if (wantarray) {
                   10113: 	return ($e,$f);
                   10114:     } else {
                   10115: 	my $g;
                   10116: 	{
                   10117: 	    use integer;
                   10118: 	    $g=($e+$f);
                   10119: 	    if ($_64bit) {
                   10120: 		$g=(($g<<32)>>32);
                   10121: 	    }
                   10122: 	}
                   10123: 	return $g;
                   10124:     }
                   10125: }
                   10126: 
1.368     albertel 10127: sub latest_rnd_algorithm_id {
1.675     albertel 10128:     return '64bit5';
1.366     albertel 10129: }
1.32      www      10130: 
1.503     albertel 10131: sub get_rand_alg {
                   10132:     my ($courseid)=@_;
1.790     albertel 10133:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10134:     if ($courseid) {
1.620     albertel 10135: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10136:     }
                   10137:     return &latest_rnd_algorithm_id();
                   10138: }
                   10139: 
1.562     albertel 10140: sub validCODE {
                   10141:     my ($CODE)=@_;
                   10142:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10143:     return 0;
                   10144: }
                   10145: 
1.491     albertel 10146: sub getCODE {
1.620     albertel 10147:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10148:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10149: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10150: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10151: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10152:     }
                   10153:     return undef;
                   10154: }
1.1133    foxr     10155: #
                   10156: #  Determines the random seed for a specific context:
                   10157: #
                   10158: # parameters:
                   10159: #   symb      - in course context the symb for the seed.
                   10160: #   course_id - The course id of the form domain_coursenum.
                   10161: #   domain    - Domain for the user.
                   10162: #   course    - Course for the user.
                   10163: #   cenv      - environment of the course.
                   10164: #
                   10165: # NOTE:
                   10166: #   All parameters are picked out of the environment if missing
                   10167: #   or not defined.
                   10168: #   If a symb cannot be determined the current time is used instead.
                   10169: #
                   10170: #  For a given well defined symb, courside, domain, username,
                   10171: #  and course environment, the seed is reproducible.
                   10172: #
1.31      www      10173: sub rndseed {
1.1133    foxr     10174:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10175:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10176:     if (!defined($symb)) {
1.366     albertel 10177: 	unless ($symb=$wsymb) { return time; }
                   10178:     }
1.1146    foxr     10179:     if (!defined $courseid) { 
                   10180: 	$courseid=$wcourseid; 
                   10181:     }
                   10182:     if (!defined $domain) { $domain=$wdomain; }
                   10183:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10184: 
                   10185:     my $which;
                   10186:     if (defined($cenv->{'rndseed'})) {
                   10187: 	$which = $cenv->{'rndseed'};
                   10188:     } else {
                   10189: 	$which =&get_rand_alg($courseid);
                   10190:     }
1.491     albertel 10191:     if (defined(&getCODE())) {
1.1133    foxr     10192: 
1.675     albertel 10193: 	if ($which eq '64bit5') {
                   10194: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10195: 	} elsif ($which eq '64bit4') {
1.575     albertel 10196: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10197: 	} else {
                   10198: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10199: 	}
1.675     albertel 10200:     } elsif ($which eq '64bit5') {
                   10201: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10202:     } elsif ($which eq '64bit4') {
                   10203: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10204:     } elsif ($which eq '64bit3') {
                   10205: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10206:     } elsif ($which eq '64bit2') {
                   10207: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10208:     } elsif ($which eq '64bit') {
                   10209: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10210:     }
                   10211:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10212: }
                   10213: 
                   10214: sub rndseed_32bit {
                   10215:     my ($symb,$courseid,$domain,$username)=@_;
                   10216:     {
                   10217: 	use integer;
                   10218: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10219: 	my $symbseed=numval($symb) << 22;
                   10220: 	my $namechck=unpack("%32C*",$username) << 17;
                   10221: 	my $nameseed=numval($username) << 12;
                   10222: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10223: 	my $courseseed=unpack("%32C*",$courseid);
                   10224: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10225: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10226: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10227: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10228: 	return $num;
                   10229:     }
                   10230: }
                   10231: 
                   10232: sub rndseed_64bit {
                   10233:     my ($symb,$courseid,$domain,$username)=@_;
                   10234:     {
                   10235: 	use integer;
                   10236: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10237: 	my $symbseed=numval($symb) << 10;
                   10238: 	my $namechck=unpack("%32S*",$username);
                   10239: 	
                   10240: 	my $nameseed=numval($username) << 21;
                   10241: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10242: 	my $courseseed=unpack("%32S*",$courseid);
                   10243: 	
                   10244: 	my $num1=$symbchck+$symbseed+$namechck;
                   10245: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10246: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10247: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10248: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10249: 	return "$num1,$num2";
1.155     albertel 10250:     }
1.366     albertel 10251: }
                   10252: 
1.443     albertel 10253: sub rndseed_64bit2 {
                   10254:     my ($symb,$courseid,$domain,$username)=@_;
                   10255:     {
                   10256: 	use integer;
                   10257: 	# strings need to be an even # of cahracters long, it it is odd the
                   10258:         # last characters gets thrown away
                   10259: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10260: 	my $symbseed=numval($symb) << 10;
                   10261: 	my $namechck=unpack("%32S*",$username.' ');
                   10262: 	
                   10263: 	my $nameseed=numval($username) << 21;
1.501     albertel 10264: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10265: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10266: 	
                   10267: 	my $num1=$symbchck+$symbseed+$namechck;
                   10268: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10269: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10270: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10271: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10272: 	return "$num1,$num2";
                   10273:     }
                   10274: }
                   10275: 
                   10276: sub rndseed_64bit3 {
                   10277:     my ($symb,$courseid,$domain,$username)=@_;
                   10278:     {
                   10279: 	use integer;
                   10280: 	# strings need to be an even # of cahracters long, it it is odd the
                   10281:         # last characters gets thrown away
                   10282: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10283: 	my $symbseed=numval2($symb) << 10;
                   10284: 	my $namechck=unpack("%32S*",$username.' ');
                   10285: 	
                   10286: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10287: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10288: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10289: 	
                   10290: 	my $num1=$symbchck+$symbseed+$namechck;
                   10291: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10292: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10293: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10294: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10295: 	
1.503     albertel 10296: 	return "$num1:$num2";
1.443     albertel 10297:     }
                   10298: }
                   10299: 
1.575     albertel 10300: sub rndseed_64bit4 {
                   10301:     my ($symb,$courseid,$domain,$username)=@_;
                   10302:     {
                   10303: 	use integer;
                   10304: 	# strings need to be an even # of cahracters long, it it is odd the
                   10305:         # last characters gets thrown away
                   10306: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10307: 	my $symbseed=numval3($symb) << 10;
                   10308: 	my $namechck=unpack("%32S*",$username.' ');
                   10309: 	
                   10310: 	my $nameseed=numval3($username) << 21;
                   10311: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10312: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10313: 	
                   10314: 	my $num1=$symbchck+$symbseed+$namechck;
                   10315: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10316: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10317: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10318: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10319: 	
1.575     albertel 10320: 	return "$num1:$num2";
                   10321:     }
                   10322: }
                   10323: 
1.675     albertel 10324: sub rndseed_64bit5 {
                   10325:     my ($symb,$courseid,$domain,$username)=@_;
                   10326:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10327:     return "$num1:$num2";
                   10328: }
                   10329: 
1.366     albertel 10330: sub rndseed_CODE_64bit {
                   10331:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10332:     {
1.366     albertel 10333: 	use integer;
1.443     albertel 10334: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10335: 	my $symbseed=numval2($symb);
1.491     albertel 10336: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10337: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10338: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10339: 	my $num1=$symbseed+$CODEchck;
                   10340: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10341: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10342: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10343: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10344: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10345: 	return "$num1:$num2";
1.366     albertel 10346:     }
                   10347: }
                   10348: 
1.575     albertel 10349: sub rndseed_CODE_64bit4 {
                   10350:     my ($symb,$courseid,$domain,$username)=@_;
                   10351:     {
                   10352: 	use integer;
                   10353: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10354: 	my $symbseed=numval3($symb);
                   10355: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10356: 	my $CODEseed=numval3(&getCODE());
                   10357: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10358: 	my $num1=$symbseed+$CODEchck;
                   10359: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10360: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10361: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10362: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10363: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10364: 	return "$num1:$num2";
                   10365:     }
                   10366: }
                   10367: 
1.675     albertel 10368: sub rndseed_CODE_64bit5 {
                   10369:     my ($symb,$courseid,$domain,$username)=@_;
                   10370:     my $code = &getCODE();
                   10371:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10372:     return "$num1:$num2";
                   10373: }
                   10374: 
1.366     albertel 10375: sub setup_random_from_rndseed {
                   10376:     my ($rndseed)=@_;
1.503     albertel 10377:     if ($rndseed =~/([,:])/) {
                   10378: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10379: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10380:     } else {
                   10381: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10382:     }
1.36      albertel 10383: }
                   10384: 
1.474     albertel 10385: sub latest_receipt_algorithm_id {
1.835     albertel 10386:     return 'receipt3';
1.474     albertel 10387: }
                   10388: 
1.480     www      10389: sub recunique {
                   10390:     my $fucourseid=shift;
                   10391:     my $unique;
1.835     albertel 10392:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10393: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10394: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10395:     } else {
                   10396: 	$unique=$perlvar{'lonReceipt'};
                   10397:     }
                   10398:     return unpack("%32C*",$unique);
                   10399: }
                   10400: 
                   10401: sub recprefix {
                   10402:     my $fucourseid=shift;
                   10403:     my $prefix;
1.835     albertel 10404:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10405: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10406: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10407:     } else {
                   10408: 	$prefix=$perlvar{'lonHostID'};
                   10409:     }
                   10410:     return unpack("%32C*",$prefix);
                   10411: }
                   10412: 
1.76      www      10413: sub ireceipt {
1.474     albertel 10414:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10415: 
                   10416:     my $return =&recprefix($fucourseid).'-';
                   10417: 
                   10418:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10419: 	$env{'request.state'} eq 'construct') {
                   10420: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10421: 	return $return;
                   10422:     }
                   10423: 
1.76      www      10424:     my $cuname=unpack("%32C*",$funame);
                   10425:     my $cudom=unpack("%32C*",$fudom);
                   10426:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10427:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10428:     my $cunique=&recunique($fucourseid);
1.474     albertel 10429:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10430:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10431: 
1.790     albertel 10432: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10433: 			       
                   10434: 	$return.= ($cunique%$cuname+
                   10435: 		   $cunique%$cudom+
                   10436: 		   $cusymb%$cuname+
                   10437: 		   $cusymb%$cudom+
                   10438: 		   $cucourseid%$cuname+
                   10439: 		   $cucourseid%$cudom+
                   10440: 		   $cpart%$cuname+
                   10441: 		   $cpart%$cudom);
                   10442:     } else {
                   10443: 	$return.= ($cunique%$cuname+
                   10444: 		   $cunique%$cudom+
                   10445: 		   $cusymb%$cuname+
                   10446: 		   $cusymb%$cudom+
                   10447: 		   $cucourseid%$cuname+
                   10448: 		   $cucourseid%$cudom);
                   10449:     }
                   10450:     return $return;
1.76      www      10451: }
                   10452: 
                   10453: sub receipt {
1.474     albertel 10454:     my ($part)=@_;
1.790     albertel 10455:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10456:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10457: }
1.260     ng       10458: 
1.790     albertel 10459: sub whichuser {
                   10460:     my ($passedsymb)=@_;
                   10461:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10462:     if (defined($env{'form.grade_symb'})) {
                   10463: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10464: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10465: 	if (!$allowed &&
                   10466: 	    exists($env{'request.course.sec'}) &&
                   10467: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10468: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10469: 			      '/'.$env{'request.course.sec'});
                   10470: 	}
                   10471: 	if ($allowed) {
                   10472: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10473: 	    $courseid=$tmp_courseid;
                   10474: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10475: 	    ($name)=&get_env_multiple('form.grade_username');
                   10476: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10477: 	}
                   10478:     }
                   10479:     if (!$passedsymb) {
                   10480: 	$symb=&symbread();
                   10481:     } else {
                   10482: 	$symb=$passedsymb;
                   10483:     }
                   10484:     $courseid=$env{'request.course.id'};
                   10485:     $domain=$env{'user.domain'};
                   10486:     $name=$env{'user.name'};
                   10487:     if ($name eq 'public' && $domain eq 'public') {
                   10488: 	if (!defined($env{'form.username'})) {
                   10489: 	    $env{'form.username'}.=time.rand(10000000);
                   10490: 	}
                   10491: 	$name.=$env{'form.username'};
                   10492:     }
                   10493:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10494: 
                   10495: }
                   10496: 
1.36      albertel 10497: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10498: # returns either the contents of the file or 
                   10499: # -1 if the file doesn't exist
1.481     raeburn  10500: #
                   10501: # if the target is a file that was uploaded via DOCS, 
                   10502: # a check will be made to see if a current copy exists on the local server,
                   10503: # if it does this will be served, otherwise a copy will be retrieved from
                   10504: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10505: # the local server.   
1.472     albertel 10506: 
1.36      albertel 10507: sub getfile {
1.538     albertel 10508:     my ($file) = @_;
1.609     banghart 10509:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10510:     &repcopy($file);
                   10511:     return &readfile($file);
                   10512: }
                   10513: 
                   10514: sub repcopy_userfile {
                   10515:     my ($file)=@_;
1.1142    raeburn  10516:     my $londocroot = $perlvar{'lonDocRoot'};
                   10517:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164  ! raeburn  10518:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10519:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10520: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10521:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10522:     if (-e "$file") {
1.828     www      10523: # we already have a local copy, check it out
1.538     albertel 10524: 	my @fileinfo = stat($file);
1.828     www      10525: 	my $rtncode;
                   10526: 	my $info;
1.538     albertel 10527: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10528: 	if ($lwpresp ne 'ok') {
1.828     www      10529: # there is no such file anymore, even though we had a local copy
1.482     albertel 10530: 	    if ($rtncode eq '404') {
1.538     albertel 10531: 		unlink($file);
1.482     albertel 10532: 	    }
                   10533: 	    return -1;
                   10534: 	}
                   10535: 	if ($info < $fileinfo[9]) {
1.828     www      10536: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10537: 	    return 'ok';
1.828     www      10538: 	} else {
                   10539: # the file is outdated, get rid of it
                   10540: 	    unlink($file);
1.482     albertel 10541: 	}
1.828     www      10542:     }
                   10543: # one way or the other, at this point, we don't have the file
                   10544: # construct the correct path for the file
                   10545:     my @parts = ($cdom,$cnum); 
                   10546:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10547: 	push @parts, split(/\//,$1);
                   10548:     }
                   10549:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10550:     foreach my $part (@parts) {
                   10551: 	$path .= '/'.$part;
                   10552: 	if (!-e $path) {
                   10553: 	    mkdir($path,0770);
1.482     albertel 10554: 	}
                   10555:     }
1.828     www      10556: # now the path exists for sure
                   10557: # get a user agent
                   10558:     my $ua=new LWP::UserAgent;
                   10559:     my $transferfile=$file.'.in.transfer';
                   10560: # FIXME: this should flock
                   10561:     if (-e $transferfile) { return 'ok'; }
                   10562:     my $request;
                   10563:     $uri=~s/^\///;
1.980     raeburn  10564:     my $homeserver = &homeserver($cnum,$cdom);
                   10565:     my $protocol = $protocol{$homeserver};
                   10566:     $protocol = 'http' if ($protocol ne 'https');
                   10567:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10568:     my $response=$ua->request($request,$transferfile);
                   10569: # did it work?
                   10570:     if ($response->is_error()) {
                   10571: 	unlink($transferfile);
                   10572: 	&logthis("Userfile repcopy failed for $uri");
                   10573: 	return -1;
                   10574:     }
                   10575: # worked, rename the transfer file
                   10576:     rename($transferfile,$file);
1.607     raeburn  10577:     return 'ok';
1.481     raeburn  10578: }
                   10579: 
1.517     albertel 10580: sub tokenwrapper {
                   10581:     my $uri=shift;
1.980     raeburn  10582:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10583:     $uri=~s|^/||;
1.620     albertel 10584:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10585:     my $token=$1;
1.552     albertel 10586:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10587:     if ($udom && $uname && $file) {
                   10588: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10589:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10590:         my $homeserver = &homeserver($uname,$udom);
                   10591:         my $protocol = $protocol{$homeserver};
                   10592:         $protocol = 'http' if ($protocol ne 'https');
                   10593:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10594:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10595:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10596:     } else {
                   10597:         return '/adm/notfound.html';
                   10598:     }
                   10599: }
                   10600: 
1.828     www      10601: # call with reqtype HEAD: get last modification time
                   10602: # call with reqtype GET: get the file contents
                   10603: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10604: #
1.481     raeburn  10605: sub getuploaded {
                   10606:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10607:     $uri=~s/^\///;
1.980     raeburn  10608:     my $homeserver = &homeserver($cnum,$cdom);
                   10609:     my $protocol = $protocol{$homeserver};
                   10610:     $protocol = 'http' if ($protocol ne 'https');
                   10611:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10612:     my $ua=new LWP::UserAgent;
                   10613:     my $request=new HTTP::Request($reqtype,$uri);
                   10614:     my $response=$ua->request($request);
                   10615:     $$rtncode = $response->code;
1.482     albertel 10616:     if (! $response->is_success()) {
                   10617: 	return 'failed';
                   10618:     }      
                   10619:     if ($reqtype eq 'HEAD') {
1.486     www      10620: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10621:     } elsif ($reqtype eq 'GET') {
                   10622: 	$$info = $response->content;
1.472     albertel 10623:     }
1.482     albertel 10624:     return 'ok';
1.36      albertel 10625: }
                   10626: 
1.481     raeburn  10627: sub readfile {
                   10628:     my $file = shift;
                   10629:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10630:     my $fh;
                   10631:     open($fh,"<$file");
                   10632:     my $a='';
1.800     albertel 10633:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10634:     return $a;
                   10635: }
                   10636: 
1.36      albertel 10637: sub filelocation {
1.590     banghart 10638:     my ($dir,$file) = @_;
                   10639:     my $location;
                   10640:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10641: 
                   10642:     if ($file =~ m-^/adm/-) {
                   10643: 	$file=~s-^/adm/wrapper/-/-;
                   10644: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10645:     }
1.882     albertel 10646: 
1.1139    www      10647:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10648:         $location = $file;
1.609     banghart 10649:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10650:         my ($udom,$uname,$filename)=
1.811     albertel 10651:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10652:         my $home=&homeserver($uname,$udom);
                   10653:         my $is_me=0;
                   10654:         my @ids=&current_machine_ids();
                   10655:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10656:         if ($is_me) {
1.1117    foxr     10657:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10658:         } else {
                   10659:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10660:   	      $udom.'/'.$uname.'/'.$filename;
                   10661:         }
1.882     albertel 10662:     } elsif ($file =~ m-^/adm/-) {
                   10663: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10664:     } else {
                   10665:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10666:         $file=~s:^/(res|priv)/:/:;
                   10667:         my $space=$1;
1.590     banghart 10668:         if ( !( $file =~ m:^/:) ) {
                   10669:             $location = $dir. '/'.$file;
                   10670:         } else {
1.1142    raeburn  10671:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10672:         }
1.59      albertel 10673:     }
1.590     banghart 10674:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10675:     while ($location=~m{/\.\./}) {
                   10676: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10677: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10678: 	} else {
                   10679: 	    $location=~ s{/\.\./}{/}g;
                   10680: 	}
                   10681:     } #remove dir/..
1.590     banghart 10682:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10683:     return $location;
1.46      www      10684: }
1.36      albertel 10685: 
1.46      www      10686: sub hreflocation {
                   10687:     my ($dir,$file)=@_;
1.980     raeburn  10688:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10689: 	$file=filelocation($dir,$file);
1.700     albertel 10690:     } elsif ($file=~m-^/adm/-) {
                   10691: 	$file=~s-^/adm/wrapper/-/-;
                   10692: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10693:     }
                   10694:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10695: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10696:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10697: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10698: 	        {/uploaded/$1/$2/}x;
1.46      www      10699:     }
1.913     albertel 10700:     if ($file=~ m{^/userfiles/}) {
                   10701: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10702:     }
1.462     albertel 10703:     return $file;
1.465     albertel 10704: }
                   10705: 
1.1139    www      10706: 
                   10707: 
                   10708: 
                   10709: 
1.465     albertel 10710: sub current_machine_domains {
1.853     albertel 10711:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10712: }
                   10713: 
                   10714: sub machine_domains {
                   10715:     my ($hostname) = @_;
1.465     albertel 10716:     my @domains;
1.838     albertel 10717:     my %hostname = &all_hostnames();
1.465     albertel 10718:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10719: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10720: 	if ($hostname eq $name) {
1.844     albertel 10721: 	    push(@domains,&host_domain($id));
1.465     albertel 10722: 	}
                   10723:     }
                   10724:     return @domains;
                   10725: }
                   10726: 
                   10727: sub current_machine_ids {
1.853     albertel 10728:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10729: }
                   10730: 
                   10731: sub machine_ids {
                   10732:     my ($hostname) = @_;
                   10733:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10734:     my @ids;
1.888     albertel 10735:     my %name_to_host = &all_names();
1.889     albertel 10736:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10737: 	return @{ $name_to_host{$hostname} };
                   10738:     }
                   10739:     return;
1.31      www      10740: }
                   10741: 
1.824     raeburn  10742: sub additional_machine_domains {
                   10743:     my @domains;
                   10744:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10745:     while( my $line = <$fh>) {
                   10746:         $line =~ s/\s//g;
                   10747:         push(@domains,$line);
                   10748:     }
                   10749:     return @domains;
                   10750: }
                   10751: 
                   10752: sub default_login_domain {
                   10753:     my $domain = $perlvar{'lonDefDomain'};
                   10754:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10755:     foreach my $posdom (&current_machine_domains(),
                   10756:                         &additional_machine_domains()) {
                   10757:         if (lc($posdom) eq lc($testdomain)) {
                   10758:             $domain=$posdom;
                   10759:             last;
                   10760:         }
                   10761:     }
                   10762:     return $domain;
                   10763: }
                   10764: 
1.31      www      10765: # ------------------------------------------------------------- Declutters URLs
                   10766: 
                   10767: sub declutter {
                   10768:     my $thisfn=shift;
1.569     albertel 10769:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10770:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10771:     $thisfn=~s/^\///;
1.697     albertel 10772:     $thisfn=~s|^adm/wrapper/||;
                   10773:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10774:     $thisfn=~s/^res\///;
1.1032    raeburn  10775:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10776:         $thisfn=~s/\?.+$//;
                   10777:     }
1.268     www      10778:     return $thisfn;
                   10779: }
                   10780: 
                   10781: # ------------------------------------------------------------- Clutter up URLs
                   10782: 
                   10783: sub clutter {
                   10784:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10785:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10786: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10787:        $thisfn='/res'.$thisfn; 
                   10788:     }
1.1031    raeburn  10789:     if ($thisfn !~m|^/adm|) {
                   10790: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10791: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10792: 	} else {
                   10793: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10794: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10795: 	    if ($embstyle eq 'ssi'
                   10796: 		|| ($embstyle eq 'hdn')
                   10797: 		|| ($embstyle eq 'rat')
                   10798: 		|| ($embstyle eq 'prv')
                   10799: 		|| ($embstyle eq 'ign')) {
                   10800: 		#do nothing with these
                   10801: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10802: 		|| ($embstyle eq 'emb')
                   10803: 		|| ($embstyle eq 'wrp')) {
                   10804: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10805: 	    } elsif ($embstyle eq 'unk'
                   10806: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10807: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10808: 	    } else {
1.718     www      10809: #		&logthis("Got a blank emb style");
1.695     albertel 10810: 	    }
1.694     albertel 10811: 	}
                   10812:     }
1.31      www      10813:     return $thisfn;
1.12      www      10814: }
                   10815: 
1.787     albertel 10816: sub clutter_with_no_wrapper {
                   10817:     my $uri = &clutter(shift);
                   10818:     if ($uri =~ m-^/adm/-) {
                   10819: 	$uri =~ s-^/adm/wrapper/-/-;
                   10820: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10821:     }
                   10822:     return $uri;
                   10823: }
                   10824: 
1.557     albertel 10825: sub freeze_escape {
                   10826:     my ($value)=@_;
                   10827:     if (ref($value)) {
                   10828: 	$value=&nfreeze($value);
                   10829: 	return '__FROZEN__'.&escape($value);
                   10830:     }
                   10831:     return &escape($value);
                   10832: }
                   10833: 
1.11      www      10834: 
1.557     albertel 10835: sub thaw_unescape {
                   10836:     my ($value)=@_;
                   10837:     if ($value =~ /^__FROZEN__/) {
                   10838: 	substr($value,0,10,undef);
                   10839: 	$value=&unescape($value);
                   10840: 	return &thaw($value);
                   10841:     }
                   10842:     return &unescape($value);
                   10843: }
                   10844: 
1.436     albertel 10845: sub correct_line_ends {
                   10846:     my ($result)=@_;
                   10847:     $$result =~s/\r\n/\n/mg;
                   10848:     $$result =~s/\r/\n/mg;
1.415     albertel 10849: }
1.1       albertel 10850: # ================================================================ Main Program
                   10851: 
1.184     www      10852: sub goodbye {
1.204     albertel 10853:    &logthis("Starting Shut down");
1.443     albertel 10854: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10855:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10856: #converted
1.599     albertel 10857: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10858:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10859: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10860: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10861: #1.1 only
1.870     albertel 10862: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10863: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10864: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10865: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10866:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10867:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10868:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10869:    &flushcourselogs();
                   10870:    &logthis("Shutting down");
                   10871: }
                   10872: 
1.852     albertel 10873: sub get_dns {
1.869     albertel 10874:     my ($url,$func,$ignore_cache) = @_;
                   10875:     if (!$ignore_cache) {
                   10876: 	my ($content,$cached)=
                   10877: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10878: 	if ($cached) {
                   10879: 	    &$func($content);
                   10880: 	    return;
                   10881: 	}
                   10882:     }
                   10883: 
                   10884:     my %alldns;
1.852     albertel 10885:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10886:     foreach my $dns (<$config>) {
                   10887: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10888:         my $line = $1;
                   10889:         my ($host,$protocol) = split(/:/,$line);
                   10890:         if ($protocol ne 'https') {
                   10891:             $protocol = 'http';
                   10892:         }
                   10893: 	$alldns{$host} = $protocol;
1.869     albertel 10894:     }
                   10895:     while (%alldns) {
                   10896: 	my ($dns) = keys(%alldns);
1.852     albertel 10897: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10898:         $ua->timeout(30);
1.979     raeburn  10899: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10900: 	my $response=$ua->request($request);
1.979     raeburn  10901:         delete($alldns{$dns});
1.852     albertel 10902: 	next if ($response->is_error());
                   10903: 	my @content = split("\n",$response->content);
1.869     albertel 10904: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10905: 	&$func(\@content);
1.869     albertel 10906: 	return;
1.852     albertel 10907:     }
                   10908:     close($config);
1.871     albertel 10909:     my $which = (split('/',$url))[3];
                   10910:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10911:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10912:     my @content = <$config>;
                   10913:     &$func(\@content);
                   10914:     return;
1.852     albertel 10915: }
1.327     albertel 10916: # ------------------------------------------------------------ Read domain file
                   10917: {
1.852     albertel 10918:     my $loaded;
1.846     albertel 10919:     my %domain;
                   10920: 
1.852     albertel 10921:     sub parse_domain_tab {
                   10922: 	my ($lines) = @_;
                   10923: 	foreach my $line (@$lines) {
                   10924: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10925: 
1.846     albertel 10926: 	    chomp($line);
1.852     albertel 10927: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10928: 	    my %this_domain;
                   10929: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10930: 			       'lang_def', 'city', 'longi', 'lati',
                   10931: 			       'primary') {
                   10932: 		$this_domain{$field} = shift(@elements);
                   10933: 	    }
                   10934: 	    $domain{$name} = \%this_domain;
1.852     albertel 10935: 	}
                   10936:     }
1.864     albertel 10937: 
                   10938:     sub reset_domain_info {
                   10939: 	undef($loaded);
                   10940: 	undef(%domain);
                   10941:     }
                   10942: 
1.852     albertel 10943:     sub load_domain_tab {
1.869     albertel 10944: 	my ($ignore_cache) = @_;
                   10945: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10946: 	my $fh;
                   10947: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10948: 	    my @lines = <$fh>;
                   10949: 	    &parse_domain_tab(\@lines);
1.448     albertel 10950: 	}
1.852     albertel 10951: 	close($fh);
                   10952: 	$loaded = 1;
1.327     albertel 10953:     }
1.846     albertel 10954: 
                   10955:     sub domain {
1.852     albertel 10956: 	&load_domain_tab() if (!$loaded);
                   10957: 
1.846     albertel 10958: 	my ($name,$what) = @_;
                   10959: 	return if ( !exists($domain{$name}) );
                   10960: 
                   10961: 	if (!$what) {
                   10962: 	    return $domain{$name}{'description'};
                   10963: 	}
                   10964: 	return $domain{$name}{$what};
                   10965:     }
1.974     raeburn  10966: 
                   10967:     sub domain_info {
                   10968:         &load_domain_tab() if (!$loaded);
                   10969:         return %domain;
                   10970:     }
                   10971: 
1.327     albertel 10972: }
                   10973: 
                   10974: 
1.1       albertel 10975: # ------------------------------------------------------------- Read hosts file
                   10976: {
1.838     albertel 10977:     my %hostname;
1.844     albertel 10978:     my %hostdom;
1.845     albertel 10979:     my %libserv;
1.852     albertel 10980:     my $loaded;
1.888     albertel 10981:     my %name_to_host;
1.1074    raeburn  10982:     my %internetdom;
1.1107    raeburn  10983:     my %LC_dns_serv;
1.852     albertel 10984: 
                   10985:     sub parse_hosts_tab {
                   10986: 	my ($file) = @_;
                   10987: 	foreach my $configline (@$file) {
                   10988: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10989:             chomp($configline);
                   10990: 	    if ($configline =~ /^\^/) {
                   10991:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10992:                     $LC_dns_serv{$1} = 1;
                   10993:                 }
                   10994:                 next;
                   10995:             }
1.1074    raeburn  10996: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10997: 	    $name=~s/\s//g;
                   10998: 	    if ($id && $domain && $role && $name) {
                   10999: 		$hostname{$id}=$name;
1.888     albertel 11000: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11001: 		$hostdom{$id}=$domain;
                   11002: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11003:                 if (defined($protocol)) {
                   11004:                     if ($protocol eq 'https') {
                   11005:                         $protocol{$id} = $protocol;
                   11006:                     } else {
                   11007:                         $protocol{$id} = 'http'; 
                   11008:                     }
1.968     raeburn  11009:                 } else {
1.969     raeburn  11010:                     $protocol{$id} = 'http';
1.968     raeburn  11011:                 }
1.1074    raeburn  11012:                 if (defined($intdom)) {
                   11013:                     $internetdom{$id} = $intdom;
                   11014:                 }
1.852     albertel 11015: 	    }
                   11016: 	}
                   11017:     }
1.864     albertel 11018:     
                   11019:     sub reset_hosts_info {
1.897     albertel 11020: 	&purge_remembered();
1.864     albertel 11021: 	&reset_domain_info();
                   11022: 	&reset_hosts_ip_info();
1.892     albertel 11023: 	undef(%name_to_host);
1.864     albertel 11024: 	undef(%hostname);
                   11025: 	undef(%hostdom);
                   11026: 	undef(%libserv);
                   11027: 	undef($loaded);
                   11028:     }
1.1       albertel 11029: 
1.852     albertel 11030:     sub load_hosts_tab {
1.869     albertel 11031: 	my ($ignore_cache) = @_;
                   11032: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11033: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11034: 	my @config = <$config>;
                   11035: 	&parse_hosts_tab(\@config);
                   11036: 	close($config);
                   11037: 	$loaded=1;
1.1       albertel 11038:     }
1.852     albertel 11039: 
1.838     albertel 11040:     sub hostname {
1.852     albertel 11041: 	&load_hosts_tab() if (!$loaded);
                   11042: 
1.838     albertel 11043: 	my ($lonid) = @_;
                   11044: 	return $hostname{$lonid};
                   11045:     }
1.845     albertel 11046: 
1.838     albertel 11047:     sub all_hostnames {
1.852     albertel 11048: 	&load_hosts_tab() if (!$loaded);
                   11049: 
1.838     albertel 11050: 	return %hostname;
                   11051:     }
1.845     albertel 11052: 
1.888     albertel 11053:     sub all_names {
                   11054: 	&load_hosts_tab() if (!$loaded);
                   11055: 
                   11056: 	return %name_to_host;
                   11057:     }
                   11058: 
1.974     raeburn  11059:     sub all_host_domain {
                   11060:         &load_hosts_tab() if (!$loaded);
                   11061:         return %hostdom;
                   11062:     }
                   11063: 
1.845     albertel 11064:     sub is_library {
1.852     albertel 11065: 	&load_hosts_tab() if (!$loaded);
                   11066: 
1.845     albertel 11067: 	return exists($libserv{$_[0]});
                   11068:     }
                   11069: 
                   11070:     sub all_library {
1.852     albertel 11071: 	&load_hosts_tab() if (!$loaded);
                   11072: 
1.845     albertel 11073: 	return %libserv;
                   11074:     }
                   11075: 
1.1062    droeschl 11076:     sub unique_library {
                   11077: 	#2x reverse removes all hostnames that appear more than once
                   11078:         my %unique = reverse &all_library();
                   11079:         return reverse %unique;
                   11080:     }
                   11081: 
1.841     albertel 11082:     sub get_servers {
1.852     albertel 11083: 	&load_hosts_tab() if (!$loaded);
                   11084: 
1.841     albertel 11085: 	my ($domain,$type) = @_;
                   11086: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11087: 	                                          : %hostname;
                   11088: 	my %result;
1.842     albertel 11089: 	if (ref($domain) eq 'ARRAY') {
                   11090: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11091: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11092: 		    $result{$host} = $hostname;
                   11093: 		}
                   11094: 	    }
                   11095: 	} else {
                   11096: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11097: 		if ($hostdom{$host} eq $domain) {
                   11098: 		    $result{$host} = $hostname;
                   11099: 		}
1.841     albertel 11100: 	    }
                   11101: 	}
                   11102: 	return %result;
                   11103:     }
1.845     albertel 11104: 
1.1062    droeschl 11105:     sub get_unique_servers {
                   11106:         my %unique = reverse &get_servers(@_);
                   11107: 	return reverse %unique;
                   11108:     }
                   11109: 
1.844     albertel 11110:     sub host_domain {
1.852     albertel 11111: 	&load_hosts_tab() if (!$loaded);
                   11112: 
1.844     albertel 11113: 	my ($lonid) = @_;
                   11114: 	return $hostdom{$lonid};
                   11115:     }
                   11116: 
1.841     albertel 11117:     sub all_domains {
1.852     albertel 11118: 	&load_hosts_tab() if (!$loaded);
                   11119: 
1.841     albertel 11120: 	my %seen;
                   11121: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11122: 	return @uniq;
                   11123:     }
1.1074    raeburn  11124: 
                   11125:     sub internet_dom {
                   11126:         &load_hosts_tab() if (!$loaded);
                   11127: 
                   11128:         my ($lonid) = @_;
                   11129:         return $internetdom{$lonid};
                   11130:     }
1.1107    raeburn  11131: 
                   11132:     sub is_LC_dns {
                   11133:         &load_hosts_tab() if (!$loaded);
                   11134: 
                   11135:         my ($hostname) = @_;
                   11136:         return exists($LC_dns_serv{$hostname});
                   11137:     }
                   11138: 
1.1       albertel 11139: }
                   11140: 
1.847     albertel 11141: { 
                   11142:     my %iphost;
1.856     albertel 11143:     my %name_to_ip;
                   11144:     my %lonid_to_ip;
1.869     albertel 11145: 
1.847     albertel 11146:     sub get_hosts_from_ip {
                   11147: 	my ($ip) = @_;
                   11148: 	my %iphosts = &get_iphost();
                   11149: 	if (ref($iphosts{$ip})) {
                   11150: 	    return @{$iphosts{$ip}};
                   11151: 	}
                   11152: 	return;
1.839     albertel 11153:     }
1.864     albertel 11154:     
                   11155:     sub reset_hosts_ip_info {
                   11156: 	undef(%iphost);
                   11157: 	undef(%name_to_ip);
                   11158: 	undef(%lonid_to_ip);
                   11159:     }
1.856     albertel 11160: 
                   11161:     sub get_host_ip {
                   11162: 	my ($lonid) = @_;
                   11163: 	if (exists($lonid_to_ip{$lonid})) {
                   11164: 	    return $lonid_to_ip{$lonid};
                   11165: 	}
                   11166: 	my $name=&hostname($lonid);
                   11167:    	my $ip = gethostbyname($name);
                   11168: 	return if (!$ip || length($ip) ne 4);
                   11169: 	$ip=inet_ntoa($ip);
                   11170: 	$name_to_ip{$name}   = $ip;
                   11171: 	$lonid_to_ip{$lonid} = $ip;
                   11172: 	return $ip;
                   11173:     }
1.847     albertel 11174:     
                   11175:     sub get_iphost {
1.869     albertel 11176: 	my ($ignore_cache) = @_;
1.894     albertel 11177: 
1.869     albertel 11178: 	if (!$ignore_cache) {
                   11179: 	    if (%iphost) {
                   11180: 		return %iphost;
                   11181: 	    }
                   11182: 	    my ($ip_info,$cached)=
                   11183: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11184: 	    if ($cached) {
                   11185: 		%iphost      = %{$ip_info->[0]};
                   11186: 		%name_to_ip  = %{$ip_info->[1]};
                   11187: 		%lonid_to_ip = %{$ip_info->[2]};
                   11188: 		return %iphost;
                   11189: 	    }
                   11190: 	}
1.894     albertel 11191: 
                   11192: 	# get yesterday's info for fallback
                   11193: 	my %old_name_to_ip;
                   11194: 	my ($ip_info,$cached)=
                   11195: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11196: 	if ($cached) {
                   11197: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11198: 	}
                   11199: 
1.888     albertel 11200: 	my %name_to_host = &all_names();
                   11201: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11202: 	    my $ip;
                   11203: 	    if (!exists($name_to_ip{$name})) {
                   11204: 		$ip = gethostbyname($name);
                   11205: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11206: 		    if (defined($old_name_to_ip{$name})) {
                   11207: 			$ip = $old_name_to_ip{$name};
                   11208: 			&logthis("Can't find $name defaulting to old $ip");
                   11209: 		    } else {
                   11210: 			&logthis("Name $name no IP found");
                   11211: 			next;
                   11212: 		    }
                   11213: 		} else {
                   11214: 		    $ip=inet_ntoa($ip);
1.847     albertel 11215: 		}
                   11216: 		$name_to_ip{$name} = $ip;
                   11217: 	    } else {
                   11218: 		$ip = $name_to_ip{$name};
1.653     albertel 11219: 	    }
1.888     albertel 11220: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11221: 		$lonid_to_ip{$id} = $ip;
                   11222: 	    }
                   11223: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11224: 	}
1.869     albertel 11225: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11226: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11227: 				      48*60*60);
1.869     albertel 11228: 
1.847     albertel 11229: 	return %iphost;
1.598     albertel 11230:     }
                   11231: 
1.992     raeburn  11232:     #
                   11233:     #  Given a DNS returns the loncapa host name for that DNS 
                   11234:     # 
                   11235:     sub host_from_dns {
                   11236:         my ($dns) = @_;
                   11237:         my @hosts;
                   11238:         my $ip;
                   11239: 
1.993     raeburn  11240:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11241:             $ip = $name_to_ip{$dns};
                   11242:         }
                   11243:         if (!$ip) {
                   11244:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11245:             if (length($ip) == 4) { 
                   11246: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11247:             }
                   11248:         }
                   11249:         if ($ip) {
                   11250: 	    @hosts = get_hosts_from_ip($ip);
                   11251: 	    return $hosts[0];
                   11252:         }
                   11253:         return undef;
1.986     foxr     11254:     }
1.992     raeburn  11255: 
1.1074    raeburn  11256:     sub get_internet_names {
                   11257:         my ($lonid) = @_;
                   11258:         return if ($lonid eq '');
                   11259:         my ($idnref,$cached)=
                   11260:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11261:         if ($cached) {
                   11262:             return $idnref;
                   11263:         }
                   11264:         my $ip = &get_host_ip($lonid);
                   11265:         my @hosts = &get_hosts_from_ip($ip);
                   11266:         my %iphost = &get_iphost();
                   11267:         my (@idns,%seen);
                   11268:         foreach my $id (@hosts) {
                   11269:             my $dom = &host_domain($id);
                   11270:             my $prim_id = &domain($dom,'primary');
                   11271:             my $prim_ip = &get_host_ip($prim_id);
                   11272:             next if ($seen{$prim_ip});
                   11273:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11274:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11275:                     my $intdom = &internet_dom($id);
                   11276:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11277:                         push(@idns,$intdom);
                   11278:                     }
                   11279:                 }
                   11280:             }
                   11281:             $seen{$prim_ip} = 1;
                   11282:         }
                   11283:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11284:     }
                   11285: 
1.986     foxr     11286: }
                   11287: 
1.1079    raeburn  11288: sub all_loncaparevs {
                   11289:     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);
                   11290: }
                   11291: 
1.862     albertel 11292: BEGIN {
                   11293: 
                   11294: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11295:     unless ($readit) {
                   11296: {
                   11297:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11298:     %perlvar = (%perlvar,%{$configvars});
                   11299: }
                   11300: 
                   11301: 
1.1       albertel 11302: # ------------------------------------------------------ Read spare server file
                   11303: {
1.448     albertel 11304:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11305: 
                   11306:     while (my $configline=<$config>) {
                   11307:        chomp($configline);
1.284     matthew  11308:        if ($configline) {
1.784     albertel 11309: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11310: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11311: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11312:        }
                   11313:     }
1.448     albertel 11314:     close($config);
1.1       albertel 11315: }
1.11      www      11316: # ------------------------------------------------------------ Read permissions
                   11317: {
1.448     albertel 11318:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11319: 
                   11320:     while (my $configline=<$config>) {
1.448     albertel 11321: 	chomp($configline);
                   11322: 	if ($configline) {
                   11323: 	    my ($role,$perm)=split(/ /,$configline);
                   11324: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11325: 	}
1.11      www      11326:     }
1.448     albertel 11327:     close($config);
1.11      www      11328: }
                   11329: 
                   11330: # -------------------------------------------- Read plain texts for permissions
                   11331: {
1.448     albertel 11332:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11333: 
                   11334:     while (my $configline=<$config>) {
1.448     albertel 11335: 	chomp($configline);
                   11336: 	if ($configline) {
1.742     raeburn  11337: 	    my ($short,@plain)=split(/:/,$configline);
                   11338:             %{$prp{$short}} = ();
                   11339: 	    if (@plain > 0) {
                   11340:                 $prp{$short}{'std'} = $plain[0];
                   11341:                 for (my $i=1; $i<@plain; $i++) {
                   11342:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11343:                 }
                   11344:             }
1.448     albertel 11345: 	}
1.135     www      11346:     }
1.448     albertel 11347:     close($config);
1.135     www      11348: }
                   11349: 
                   11350: # ---------------------------------------------------------- Read package table
                   11351: {
1.448     albertel 11352:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11353: 
                   11354:     while (my $configline=<$config>) {
1.483     albertel 11355: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11356: 	chomp($configline);
                   11357: 	my ($short,$plain)=split(/:/,$configline);
                   11358: 	my ($pack,$name)=split(/\&/,$short);
                   11359: 	if ($plain ne '') {
                   11360: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11361: 	    $packagetab{$short}=$plain; 
                   11362: 	}
1.11      www      11363:     }
1.448     albertel 11364:     close($config);
1.329     matthew  11365: }
                   11366: 
1.1073    raeburn  11367: # ---------------------------------------------------------- Read loncaparev table
                   11368: {
                   11369:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11370:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11371:             while (my $configline=<$config>) {
                   11372:                 chomp($configline);
                   11373:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11374:                 $loncaparevs{$hostid}=$loncaparev;
                   11375:             }
                   11376:             close($config);
                   11377:         }
                   11378:     }
                   11379: }
                   11380: 
1.1074    raeburn  11381: # ---------------------------------------------------------- Read serverhostID table
                   11382: {
                   11383:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11384:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11385:             while (my $configline=<$config>) {
                   11386:                 chomp($configline);
                   11387:                 my ($name,$id)=split(/:/,$configline);
                   11388:                 $serverhomeIDs{$name}=$id;
                   11389:             }
                   11390:             close($config);
                   11391:         }
                   11392:     }
                   11393: }
                   11394: 
1.1079    raeburn  11395: {
                   11396:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11397:     if (-e $file) {
                   11398:         my $parser = HTML::LCParser->new($file);
                   11399:         while (my $token = $parser->get_token()) {
                   11400:             if ($token->[0] eq 'S') {
                   11401:                 my $item = $token->[1];
                   11402:                 my $name = $token->[2]{'name'};
                   11403:                 my $value = $token->[2]{'value'};
                   11404:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11405:                     my $release = $parser->get_text();
                   11406:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11407:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11408:                 }
                   11409:             }
                   11410:         }
                   11411:     }
1.1073    raeburn  11412: }
                   11413: 
1.1138    raeburn  11414: # ---------------------------------------------------------- Read managers table
                   11415: {
                   11416:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11417:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11418:             while (my $configline=<$config>) {
                   11419:                 chomp($configline);
                   11420:                 next if ($configline =~ /^\#/);
                   11421:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11422:                     $managerstab{$configline} = 1;
                   11423:                 }
                   11424:             }
                   11425:             close($config);
                   11426:         }
                   11427:     }
                   11428: }
                   11429: 
1.329     matthew  11430: # ------------- set up temporary directory
                   11431: {
1.1117    foxr     11432:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11433: 
1.11      www      11434: }
                   11435: 
1.794     albertel 11436: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11437: 				'compress_threshold'=> 20_000,
                   11438:  			        });
1.185     www      11439: 
1.281     www      11440: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11441: $dumpcount=0;
1.958     www      11442: $locknum=0;
1.22      www      11443: 
1.163     harris41 11444: &logtouch();
1.672     albertel 11445: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11446: $readit=1;
1.564     albertel 11447:     {
                   11448: 	use integer;
                   11449: 	my $test=(2**32)+1;
1.568     albertel 11450: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11451: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11452:     }
1.195     www      11453: }
1.1       albertel 11454: }
1.179     www      11455: 
1.1       albertel 11456: 1;
1.191     harris41 11457: __END__
                   11458: 
1.243     albertel 11459: =pod
                   11460: 
1.191     harris41 11461: =head1 NAME
                   11462: 
1.243     albertel 11463: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11464: 
                   11465: =head1 SYNOPSIS
                   11466: 
1.243     albertel 11467: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11468: 
                   11469:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11470: 
1.243     albertel 11471: Common parameters:
                   11472: 
                   11473: =over 4
                   11474: 
                   11475: =item *
                   11476: 
                   11477: $uname : an internal username (if $cname expecting a course Id specifically)
                   11478: 
                   11479: =item *
                   11480: 
                   11481: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11482: 
                   11483: =item *
                   11484: 
                   11485: $symb : a resource instance identifier
                   11486: 
                   11487: =item *
                   11488: 
                   11489: $namespace : the name of a .db file that contains the data needed or
                   11490: being set.
                   11491: 
                   11492: =back
                   11493: 
1.394     bowersj2 11494: =head1 OVERVIEW
1.191     harris41 11495: 
1.394     bowersj2 11496: lonnet provides subroutines which interact with the
                   11497: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11498: about classes, users, and resources.
1.243     albertel 11499: 
                   11500: For many of these objects you can also use this to store data about
                   11501: them or modify them in various ways.
1.191     harris41 11502: 
1.394     bowersj2 11503: =head2 Symbs
1.191     harris41 11504: 
1.394     bowersj2 11505: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11506: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11507: map, the resource number of the resource in the map, and the URL of
                   11508: the resource itself. The latter is somewhat redundant, but might help
                   11509: if maps change.
                   11510: 
                   11511: An example is
                   11512: 
                   11513:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11514: 
                   11515: The respective map entry is
                   11516: 
                   11517:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11518:   title="Problem 2">
                   11519:  </resource>
                   11520: 
                   11521: Symbs are used by the random number generator, as well as to store and
                   11522: restore data specific to a certain instance of for example a problem.
                   11523: 
                   11524: =head2 Storing And Retrieving Data
                   11525: 
                   11526: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11527: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11528: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11529: is is the non-critical message twin of cstore. These functions are for
                   11530: handlers to store a perl hash to a user's permanent data space in an
                   11531: easy manner, and to retrieve it again on another call. It is expected
                   11532: that a handler would use this once at the beginning to retrieve data,
                   11533: and then again once at the end to send only the new data back.
                   11534: 
                   11535: The data is stored in the user's data directory on the user's
                   11536: homeserver under the ID of the course.
                   11537: 
                   11538: The hash that is returned by restore will have all of the previous
                   11539: value for all of the elements of the hash.
                   11540: 
                   11541: Example:
                   11542: 
                   11543:  #creating a hash
                   11544:  my %hash;
                   11545:  $hash{'foo'}='bar';
                   11546: 
                   11547:  #storing it
                   11548:  &Apache::lonnet::cstore(\%hash);
                   11549: 
                   11550:  #changing a value
                   11551:  $hash{'foo'}='notbar';
                   11552: 
                   11553:  #adding a new value
                   11554:  $hash{'bar'}='foo';
                   11555:  &Apache::lonnet::cstore(\%hash);
                   11556: 
                   11557:  #retrieving the hash
                   11558:  my %history=&Apache::lonnet::restore();
                   11559: 
                   11560:  #print the hash
                   11561:  foreach my $key (sort(keys(%history))) {
                   11562:    print("\%history{$key} = $history{$key}");
                   11563:  }
                   11564: 
                   11565: Will print out:
1.191     harris41 11566: 
1.394     bowersj2 11567:  %history{1:foo} = bar
                   11568:  %history{1:keys} = foo:timestamp
                   11569:  %history{1:timestamp} = 990455579
                   11570:  %history{2:bar} = foo
                   11571:  %history{2:foo} = notbar
                   11572:  %history{2:keys} = foo:bar:timestamp
                   11573:  %history{2:timestamp} = 990455580
                   11574:  %history{bar} = foo
                   11575:  %history{foo} = notbar
                   11576:  %history{timestamp} = 990455580
                   11577:  %history{version} = 2
                   11578: 
                   11579: Note that the special hash entries C<keys>, C<version> and
                   11580: C<timestamp> were added to the hash. C<version> will be equal to the
                   11581: total number of versions of the data that have been stored. The
                   11582: C<timestamp> attribute will be the UNIX time the hash was
                   11583: stored. C<keys> is available in every historical section to list which
                   11584: keys were added or changed at a specific historical revision of a
                   11585: hash.
                   11586: 
                   11587: B<Warning>: do not store the hash that restore returns directly. This
                   11588: will cause a mess since it will restore the historical keys as if the
                   11589: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11590: 
1.394     bowersj2 11591: Calling convention:
1.191     harris41 11592: 
1.394     bowersj2 11593:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11594:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11595: 
1.394     bowersj2 11596: For more detailed information, see lonnet specific documentation.
1.191     harris41 11597: 
1.394     bowersj2 11598: =head1 RETURN MESSAGES
1.191     harris41 11599: 
1.394     bowersj2 11600: =over 4
1.191     harris41 11601: 
1.394     bowersj2 11602: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11603: 
1.394     bowersj2 11604: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11605: when the connection is brought back up
1.191     harris41 11606: 
1.394     bowersj2 11607: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11608: for later delivery
1.191     harris41 11609: 
1.967     bisitz   11610: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11611: 
1.394     bowersj2 11612: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11613: that was requested
1.191     harris41 11614: 
1.243     albertel 11615: =back
1.191     harris41 11616: 
1.243     albertel 11617: =head1 PUBLIC SUBROUTINES
1.191     harris41 11618: 
1.243     albertel 11619: =head2 Session Environment Functions
1.191     harris41 11620: 
1.243     albertel 11621: =over 4
1.191     harris41 11622: 
1.394     bowersj2 11623: =item * 
                   11624: X<appenv()>
1.949     raeburn  11625: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11626: the user envirnoment file, and will be restored for each access this
1.620     albertel 11627: user makes during this session, also modifies the %env for the current
1.949     raeburn  11628: process. Optional rolesarrayref - if defined contains a reference to an array
                   11629: of roles which are exempt from the restriction on modifying user.role entries 
                   11630: in the user's environment.db and in %env.    
1.191     harris41 11631: 
                   11632: =item *
1.394     bowersj2 11633: X<delenv()>
1.987     raeburn  11634: B<delenv($delthis,$regexp)>: removes all items from the session
                   11635: environment file that begin with $delthis. If the 
                   11636: optional second arg - $regexp - is true, $delthis is treated as a 
                   11637: regular expression, otherwise \Q$delthis\E is used. 
                   11638: The values are also deleted from the current processes %env.
1.191     harris41 11639: 
1.795     albertel 11640: =item * get_env_multiple($name) 
                   11641: 
                   11642: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11643: values may be defined and end up as an array ref.
                   11644: 
                   11645: returns an array of values
                   11646: 
1.243     albertel 11647: =back
                   11648: 
                   11649: =head2 User Information
1.191     harris41 11650: 
1.243     albertel 11651: =over 4
1.191     harris41 11652: 
                   11653: =item *
1.394     bowersj2 11654: X<queryauthenticate()>
                   11655: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11656: authentication scheme
                   11657: 
                   11658: =item *
1.394     bowersj2 11659: X<authenticate()>
1.1073    raeburn  11660: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11661: authenticate user from domain's lib servers (first use the current
                   11662: one). C<$upass> should be the users password.
1.1073    raeburn  11663: $checkdefauth is optional (value is 1 if a check should be made to
                   11664:    authenticate user using default authentication method, and allow
                   11665:    account creation if username does not have account in the domain).
                   11666: $clientcancheckhost is optional (value is 1 if checking whether the
                   11667:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11668: 
                   11669: =item *
1.394     bowersj2 11670: X<homeserver()>
                   11671: B<homeserver($uname,$udom)>: find the server which has
                   11672: the user's directory and files (there must be only one), this caches
                   11673: the answer, and also caches if there is a borken connection.
1.191     harris41 11674: 
                   11675: =item *
1.394     bowersj2 11676: X<idget()>
                   11677: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11678: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11679: username, and only 1 username per ID in a specific domain) (returns
                   11680: hash: id=>name,id=>name)
1.191     harris41 11681: 
                   11682: =item *
1.394     bowersj2 11683: X<idrget()>
                   11684: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11685: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11686: 
                   11687: =item *
1.394     bowersj2 11688: X<idput()>
                   11689: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11690: 
                   11691: =item *
1.394     bowersj2 11692: X<rolesinit()>
                   11693: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 11694: 
                   11695: =item *
1.551     albertel 11696: X<getsection()>
                   11697: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11698: course $cname, return section name/number or '' for "not in course"
                   11699: and '-1' for "no section"
                   11700: 
                   11701: =item *
1.394     bowersj2 11702: X<userenvironment()>
                   11703: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11704: passed in @what from the requested user's environment, returns a hash
                   11705: 
1.858     raeburn  11706: =item * 
                   11707: X<userlog_query()>
1.859     albertel 11708: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11709: activity.log file. %filters defines filters applied when parsing the
                   11710: log file. These can be start or end timestamps, or the type of action
                   11711: - log to look for Login or Logout events, check for Checkin or
                   11712: Checkout, role for role selection. The response is in the form
                   11713: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11714: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11715: 
1.243     albertel 11716: =back
                   11717: 
                   11718: =head2 User Roles
                   11719: 
                   11720: =over 4
                   11721: 
                   11722: =item *
                   11723: 
1.810     raeburn  11724: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11725:  F: full access
                   11726:  U,I,K: authentication modes (cxx only)
                   11727:  '': forbidden
                   11728:  1: user needs to choose course
                   11729:  2: browse allowed
1.766     albertel 11730:  A: passphrase authentication needed
1.243     albertel 11731: 
                   11732: =item *
                   11733: 
                   11734: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11735: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11736: and course level
                   11737: 
                   11738: =item *
                   11739: 
1.988     raeburn  11740: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11741: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11742: $type is Course (default) or Community.
1.988     raeburn  11743: If $forcedefault evaluates to true, text returned will be default 
                   11744: text for $type. Otherwise, if this is a course, the text returned 
                   11745: will be a custom name for the role (if defined in the course's 
                   11746: environment).  If no custom name is defined the default is returned.
                   11747:    
1.832     raeburn  11748: =item *
                   11749: 
1.935     raeburn  11750: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11751: All arguments are optional. Returns a hash of a roles, either for
                   11752: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11753: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11754: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11755: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11756: For each key, value is set to colon-separated start and end times for
                   11757: the role.  If no username and domain are specified, will default to
1.934     raeburn  11758: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11759: of role statuses (active, future or previous), roles 
                   11760: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11761: to restrict the list of roles reported. If no array ref is 
                   11762: provided for types, will default to return only active roles.
1.834     albertel 11763: 
1.243     albertel 11764: =back
                   11765: 
                   11766: =head2 User Modification
                   11767: 
                   11768: =over 4
                   11769: 
                   11770: =item *
                   11771: 
1.957     raeburn  11772: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11773: user for the level given by URL.  Optional start and end dates (leave empty
                   11774: string or zero for "no date")
1.191     harris41 11775: 
                   11776: =item *
                   11777: 
1.243     albertel 11778: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11779: change a users, password, possible return values are: ok,
                   11780: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11781: refused
1.191     harris41 11782: 
                   11783: =item *
                   11784: 
1.243     albertel 11785: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11786: 
                   11787: =item *
                   11788: 
1.1058    raeburn  11789: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11790:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11791: 
                   11792: will update user information (firstname,middlename,lastname,generation,
                   11793: permanentemail), and if forceid is true, student/employee ID also.
                   11794: A user's institutional affiliation(s) can also be updated.
                   11795: User information fields will not be overwritten with empty entries 
                   11796: unless the field is included in the $candelete array reference.
                   11797: This array is included when a single user is modified via "Manage Users",
                   11798: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11799: 
                   11800: =item *
                   11801: 
1.286     matthew  11802: modifystudent
                   11803: 
1.957     raeburn  11804: modify a student's enrollment and identification information.
1.286     matthew  11805: The course id is resolved based on the current users environment.  
                   11806: This means the envoking user must be a course coordinator or otherwise
                   11807: associated with a course.
                   11808: 
1.297     matthew  11809: This call is essentially a wrapper for lonnet::modifyuser and
                   11810: lonnet::modify_student_enrollment
1.286     matthew  11811: 
                   11812: Inputs: 
                   11813: 
                   11814: =over 4
                   11815: 
1.957     raeburn  11816: =item B<$udom> Student's loncapa domain
1.286     matthew  11817: 
1.957     raeburn  11818: =item B<$uname> Student's loncapa login name
1.286     matthew  11819: 
1.964     bisitz   11820: =item B<$uid> Student/Employee ID
1.286     matthew  11821: 
1.957     raeburn  11822: =item B<$umode> Student's authentication mode
1.286     matthew  11823: 
1.957     raeburn  11824: =item B<$upass> Student's password
1.286     matthew  11825: 
1.957     raeburn  11826: =item B<$first> Student's first name
1.286     matthew  11827: 
1.957     raeburn  11828: =item B<$middle> Student's middle name
1.286     matthew  11829: 
1.957     raeburn  11830: =item B<$last> Student's last name
1.286     matthew  11831: 
1.957     raeburn  11832: =item B<$gene> Student's generation
1.286     matthew  11833: 
1.957     raeburn  11834: =item B<$usec> Student's section in course
1.286     matthew  11835: 
                   11836: =item B<$end> Unix time of the roles expiration
                   11837: 
                   11838: =item B<$start> Unix time of the roles start date
                   11839: 
                   11840: =item B<$forceid> If defined, allow $uid to be changed
                   11841: 
                   11842: =item B<$desiredhome> server to use as home server for student
                   11843: 
1.957     raeburn  11844: =item B<$email> Student's permanent e-mail address
                   11845: 
                   11846: =item B<$type> Type of enrollment (auto or manual)
                   11847: 
1.963     raeburn  11848: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11849: 
                   11850: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11851: 
1.963     raeburn  11852: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11853: 
1.963     raeburn  11854: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11855: 
1.963     raeburn  11856: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11857: 
1.286     matthew  11858: =back
1.297     matthew  11859: 
                   11860: =item *
                   11861: 
                   11862: modify_student_enrollment
                   11863: 
                   11864: Change a students enrollment status in a class.  The environment variable
                   11865: 'role.request.course' must be defined for this function to proceed.
                   11866: 
                   11867: Inputs:
                   11868: 
                   11869: =over 4
                   11870: 
                   11871: =item $udom, students domain
                   11872: 
                   11873: =item $uname, students name
                   11874: 
                   11875: =item $uid, students user id
                   11876: 
                   11877: =item $first, students first name
                   11878: 
                   11879: =item $middle
                   11880: 
                   11881: =item $last
                   11882: 
                   11883: =item $gene
                   11884: 
                   11885: =item $usec
                   11886: 
                   11887: =item $end
                   11888: 
                   11889: =item $start
                   11890: 
1.957     raeburn  11891: =item $type
                   11892: 
                   11893: =item $locktype
                   11894: 
                   11895: =item $cid
                   11896: 
                   11897: =item $selfenroll
                   11898: 
                   11899: =item $context
                   11900: 
1.297     matthew  11901: =back
                   11902: 
1.191     harris41 11903: 
                   11904: =item *
                   11905: 
1.243     albertel 11906: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11907: custom role; give a custom role to a user for the level given by URL.  Specify
                   11908: name and domain of role author, and role name
1.191     harris41 11909: 
                   11910: =item *
                   11911: 
1.243     albertel 11912: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11913: 
                   11914: =item *
                   11915: 
1.243     albertel 11916: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11917: 
                   11918: =back
                   11919: 
                   11920: =head2 Course Infomation
                   11921: 
                   11922: =over 4
1.191     harris41 11923: 
                   11924: =item *
                   11925: 
1.1118    foxr     11926: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11927: specified course id, including all environment settings for the
                   11928: course, the description of the course will be in the hash under the
                   11929: key 'description'
1.191     harris41 11930: 
1.1118    foxr     11931: $options is an optional parameter that if supplied is a hash reference that controls
                   11932: what how this function works.  It has the following key/values:
                   11933: 
                   11934: =over 4
                   11935: 
                   11936: =item freshen_cache
                   11937: 
                   11938: If defined, and the environment cache for the course is valid, it is 
                   11939: returned in the returned hash.
                   11940: 
                   11941: =item one_time
                   11942: 
                   11943: If defined, the last cache time is set to _now_
                   11944: 
                   11945: =item user
                   11946: 
                   11947: If defined, the supplied username is used instead of the current user.
                   11948: 
                   11949: 
                   11950: =back
                   11951: 
1.191     harris41 11952: =item *
                   11953: 
1.624     albertel 11954: resdata($name,$domain,$type,@which) : request for current parameter
                   11955: setting for a specific $type, where $type is either 'course' or 'user',
                   11956: @what should be a list of parameters to ask about. This routine caches
                   11957: answers for 5 minutes.
1.243     albertel 11958: 
1.877     foxr     11959: =item *
                   11960: 
                   11961: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11962: data base, returning a hash that is keyed by the resource name and has
                   11963: values that are the resource value.  I believe that the timestamps and
                   11964: versions are also returned.
                   11965: 
                   11966: 
1.243     albertel 11967: =back
                   11968: 
                   11969: =head2 Course Modification
                   11970: 
                   11971: =over 4
1.191     harris41 11972: 
                   11973: =item *
                   11974: 
1.243     albertel 11975: writecoursepref($courseid,%prefs) : write preferences (environment
                   11976: database) for a course
1.191     harris41 11977: 
                   11978: =item *
                   11979: 
1.1011    raeburn  11980: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11981: 
                   11982: =item *
                   11983: 
1.1038    raeburn  11984: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11985: 
                   11986: =back
                   11987: 
                   11988: =head2 Resource Subroutines
                   11989: 
                   11990: =over 4
1.191     harris41 11991: 
                   11992: =item *
                   11993: 
1.243     albertel 11994: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11995: 
                   11996: =item *
                   11997: 
1.243     albertel 11998: repcopy($filename) : subscribes to the requested file, and attempts to
                   11999: replicate from the owning library server, Might return
1.607     raeburn  12000: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12001: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12002: resource. Expects the local filesystem pathname
                   12003: (/home/httpd/html/res/....)
                   12004: 
                   12005: =back
                   12006: 
                   12007: =head2 Resource Information
                   12008: 
                   12009: =over 4
1.191     harris41 12010: 
                   12011: =item *
                   12012: 
1.243     albertel 12013: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12014: a vairety of different possible values, $varname should be a request
                   12015: string, and the other parameters can be used to specify who and what
                   12016: one is asking about.
                   12017: 
                   12018: Possible values for $varname are environment.lastname (or other item
                   12019: from the envirnment hash), user.name (or someother aspect about the
                   12020: user), resource.0.maxtries (or some other part and parameter of a
                   12021: resource)
1.204     albertel 12022: 
                   12023: =item *
                   12024: 
1.243     albertel 12025: directcondval($number) : get current value of a condition; reads from a state
                   12026: string
1.204     albertel 12027: 
                   12028: =item *
                   12029: 
1.243     albertel 12030: condval($condidx) : value of condition index based on state
1.204     albertel 12031: 
                   12032: =item *
                   12033: 
1.243     albertel 12034: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12035: resource's metadata, $what should be either a specific key, or either
                   12036: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12037: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12038: 
                   12039: this function automatically caches all requests
1.191     harris41 12040: 
                   12041: =item *
                   12042: 
1.243     albertel 12043: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12044: network of library servers; returns file handle of where SQL and regex results
                   12045: will be stored for query
1.191     harris41 12046: 
                   12047: =item *
                   12048: 
1.243     albertel 12049: symbread($filename) : return symbolic list entry (filename argument optional);
                   12050: returns the data handle
1.191     harris41 12051: 
                   12052: =item *
                   12053: 
1.243     albertel 12054: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12055: a possible symb for the URL in $thisfn, and if is an encryypted
                   12056: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12057: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12058: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12059: 
1.191     harris41 12060: 
                   12061: =item *
                   12062: 
1.243     albertel 12063: symbclean($symb) : removes versions numbers from a symb, returns the
                   12064: cleaned symb
1.191     harris41 12065: 
                   12066: =item *
                   12067: 
1.243     albertel 12068: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12069: course map, user must be in a course for it to work.
1.191     harris41 12070: 
                   12071: =item *
                   12072: 
1.243     albertel 12073: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12074: 
                   12075: =item *
                   12076: 
1.243     albertel 12077: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12078: a random seed, all arguments are optional, if they aren't sent it uses the
                   12079: environment to derive them. Note: if symb isn't sent and it can't get one
                   12080: from &symbread it will use the current time as its return value
1.191     harris41 12081: 
                   12082: =item *
                   12083: 
1.243     albertel 12084: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12085: unfakeable, receipt
1.191     harris41 12086: 
                   12087: =item *
                   12088: 
1.620     albertel 12089: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12090: 
                   12091: =item *
                   12092: 
1.243     albertel 12093: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12094: 
                   12095: =item *
                   12096: 
1.243     albertel 12097: 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 12098: 
                   12099: =item *
                   12100: 
1.243     albertel 12101: 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 12102: 
                   12103: =item *
                   12104: 
1.243     albertel 12105: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12106: 
                   12107: =item *
                   12108: 
1.243     albertel 12109: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12110: forcing spreadsheet to reevaluate the resource scores next time.
                   12111: 
                   12112: =back
                   12113: 
                   12114: =head2 Storing/Retreiving Data
                   12115: 
                   12116: =over 4
1.191     harris41 12117: 
                   12118: =item *
                   12119: 
1.243     albertel 12120: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12121: for this url; hashref needs to be given and should be a \%hashname; the
                   12122: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12123: be derived from the env
1.191     harris41 12124: 
                   12125: =item *
                   12126: 
1.243     albertel 12127: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12128: uses critical subroutine
1.191     harris41 12129: 
                   12130: =item *
                   12131: 
1.243     albertel 12132: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12133: all args are optional
1.191     harris41 12134: 
                   12135: =item *
                   12136: 
1.717     albertel 12137: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12138: dumps the complete (or key matching regexp) namespace into a hash
                   12139: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12140: normally &store()ed into
                   12141: 
                   12142: $range should be either an integer '100' (give me the first 100
                   12143:                                            matching records)
                   12144:               or be  two integers sperated by a - with no spaces
                   12145:                  '30-50' (give me the 30th through the 50th matching
                   12146:                           records)
                   12147: 
                   12148: 
                   12149: =item *
                   12150: 
                   12151: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12152: replaces a &store() version of data with a replacement set of data
                   12153: for a particular resource in a namespace passed in the $storehash hash 
                   12154: reference
                   12155: 
                   12156: =item *
                   12157: 
1.243     albertel 12158: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12159: works very similar to store/cstore, but all data is stored in a
                   12160: temporary location and can be reset using tmpreset, $storehash should
                   12161: be a hash reference, returns nothing on success
1.191     harris41 12162: 
                   12163: =item *
                   12164: 
1.243     albertel 12165: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12166: similar to restore, but all data is stored in a temporary location and
                   12167: can be reset using tmpreset. Returns a hash of values on success,
                   12168: error string otherwise.
1.191     harris41 12169: 
                   12170: =item *
                   12171: 
1.243     albertel 12172: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12173: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12174: 
                   12175: =item *
                   12176: 
1.243     albertel 12177: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12178: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12179: 
                   12180: =item *
                   12181: 
1.243     albertel 12182: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12183: namesp ($udom and $uname are optional)
1.191     harris41 12184: 
                   12185: =item *
                   12186: 
1.702     albertel 12187: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12188: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12189: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12190: 
1.702     albertel 12191: $range should be either an integer '100' (give me the first 100
                   12192:                                            matching records)
                   12193:               or be  two integers sperated by a - with no spaces
                   12194:                  '30-50' (give me the 30th through the 50th matching
                   12195:                           records)
1.449     matthew  12196: =item *
                   12197: 
                   12198: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12199: $store can be a scalar, an array reference, or if the amount to be 
                   12200: incremented is > 1, a hash reference.
                   12201: 
                   12202: ($udom and $uname are optional)
1.191     harris41 12203: 
                   12204: =item *
                   12205: 
1.243     albertel 12206: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12207: ($udom and $uname are optional)
1.191     harris41 12208: 
                   12209: =item *
                   12210: 
1.243     albertel 12211: cput($namespace,$storehash,$udom,$uname) : critical put
                   12212: ($udom and $uname are optional)
1.191     harris41 12213: 
                   12214: =item *
                   12215: 
1.748     albertel 12216: newput($namespace,$storehash,$udom,$uname) :
                   12217: 
                   12218: Attempts to store the items in the $storehash, but only if they don't
                   12219: currently exist, if this succeeds you can be certain that you have 
                   12220: successfully created a new key value pair in the $namespace db.
                   12221: 
                   12222: 
                   12223: Args:
                   12224:  $namespace: name of database to store values to
                   12225:  $storehash: hashref to store to the db
                   12226:  $udom: (optional) domain of user containing the db
                   12227:  $uname: (optional) name of user caontaining the db
                   12228: 
                   12229: Returns:
                   12230:  'ok' -> succeeded in storing all keys of $storehash
                   12231:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12232:                         least <key> already existed in the db (other
                   12233:                         requested keys may also already exist)
1.967     bisitz   12234:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12235:  'con_lost' -> unable to contact request server
                   12236:  'refused' -> action was not allowed by remote machine
                   12237: 
                   12238: 
                   12239: =item *
                   12240: 
1.243     albertel 12241: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12242: reference filled in from namesp (encrypts the return communication)
                   12243: ($udom and $uname are optional)
1.191     harris41 12244: 
                   12245: =item *
                   12246: 
1.243     albertel 12247: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12248: critical subroutine
                   12249: 
1.806     raeburn  12250: =item *
                   12251: 
1.860     raeburn  12252: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12253: array reference filled in from namespace found in domain level on either
                   12254: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12255: 
                   12256: =item *
                   12257: 
1.860     raeburn  12258: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12259: domain level either on specified domain server ($uhome) or primary domain 
                   12260: server ($udom and $uhome are optional)
1.806     raeburn  12261: 
1.943     raeburn  12262: =item * 
                   12263: 
                   12264: get_domain_defaults($target_domain) : returns hash with defaults for
                   12265: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12266: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12267: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12268: Values are retrieved from cache (if current), or from domain's configuration.db
                   12269: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12270: or lonTabs/domain.tab. 
                   12271: 
                   12272: %domdefaults = &get_auth_defaults($target_domain);
                   12273: 
1.243     albertel 12274: =back
                   12275: 
                   12276: =head2 Network Status Functions
                   12277: 
                   12278: =over 4
1.191     harris41 12279: 
                   12280: =item *
                   12281: 
1.1137    raeburn  12282: dirlist() : return directory list based on URI (first arg).
                   12283: 
                   12284: Inputs: 1 required, 5 optional.
                   12285: 
                   12286: =over
                   12287: 
                   12288: =item 
                   12289: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12290: 
                   12291: =item
                   12292: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12293: 
                   12294: =item
                   12295: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12296: 
                   12297: =item
                   12298: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12299: 
                   12300: =item
                   12301: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12302: 
                   12303: =item 
                   12304: $alternateRoot - path to prepend in place of path from $uri.
                   12305: 
                   12306: =back
                   12307: 
                   12308: Returns: Array of up to two items.
                   12309: 
                   12310: =over
                   12311: 
                   12312: a reference to an array of files/subdirectories
                   12313: 
                   12314: =over
                   12315: 
                   12316: Each element in the array of files/subdirectories is a & separated list of
                   12317: item name and the result of running stat on the item.  If dirlist was requested
                   12318: for a file instead of a directory, the item name will be ''. For a directory 
                   12319: listing, if the item is a metadata file, the element will end &N&M 
                   12320: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12321: default copyright set (1).  
                   12322: 
                   12323: =back
                   12324: 
                   12325: a scalar containing error condition (if encountered).
                   12326: 
                   12327: =over
                   12328: 
                   12329: =item 
                   12330: no_host (no homeserver identified for $username:$domain).
                   12331: 
                   12332: =item 
                   12333: no_such_host (server contacted for listing not identified as valid host).
                   12334: 
                   12335: =item 
                   12336: con_lost (connection to remote server failed).
                   12337: 
                   12338: =item 
                   12339: refused (invalid $username:$domain received on lond side).
                   12340: 
                   12341: =item 
                   12342: no_such_dir (directory at specified path on lond side does not exist). 
                   12343: 
                   12344: =item 
                   12345: empty (directory at specified path on lond side is empty).
                   12346: 
                   12347: =over
                   12348: 
                   12349: This is currently not encountered because the &ls3, &ls2, 
                   12350: &ls (_handler) routines on the lond side do not filter out
                   12351: . and .. from a directory listing. 
                   12352: 
                   12353: =back
                   12354: 
                   12355: =back
                   12356: 
                   12357: =back
1.191     harris41 12358: 
                   12359: =item *
                   12360: 
1.243     albertel 12361: spareserver() : find server with least workload from spare.tab
                   12362: 
1.986     foxr     12363: 
                   12364: =item *
                   12365: 
                   12366: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12367: if there is no corresponding loncapa host.
                   12368: 
1.243     albertel 12369: =back
                   12370: 
1.986     foxr     12371: 
1.243     albertel 12372: =head2 Apache Request
                   12373: 
                   12374: =over 4
1.191     harris41 12375: 
                   12376: =item *
                   12377: 
1.243     albertel 12378: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12379: localhost, posts hash
                   12380: 
                   12381: =back
                   12382: 
                   12383: =head2 Data to String to Data
                   12384: 
                   12385: =over 4
1.191     harris41 12386: 
                   12387: =item *
                   12388: 
1.243     albertel 12389: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12390: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12391: 
                   12392: =item *
                   12393: 
1.243     albertel 12394: hashref2str($hashref) : convert a hashref into a string complete with
                   12395: escaping and '=' and '&' separators, supports elements that are
                   12396: arrayrefs and hashrefs
1.191     harris41 12397: 
                   12398: =item *
                   12399: 
1.243     albertel 12400: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12401: with escaping and '&' separators, supports elements that are arrayrefs
                   12402: and hashrefs
1.191     harris41 12403: 
                   12404: =item *
                   12405: 
1.243     albertel 12406: str2hash($string) : convert string to hash using unescaping and
                   12407: splitting on '=' and '&', supports elements that are arrayrefs and
                   12408: hashrefs
1.191     harris41 12409: 
                   12410: =item *
                   12411: 
1.243     albertel 12412: str2array($string) : convert string to hash using unescaping and
                   12413: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12414: 
                   12415: =back
                   12416: 
                   12417: =head2 Logging Routines
                   12418: 
                   12419: 
                   12420: These routines allow one to make log messages in the lonnet.log and
                   12421: lonnet.perm logfiles.
1.191     harris41 12422: 
1.1119    foxr     12423: =over 4
                   12424: 
1.191     harris41 12425: =item *
                   12426: 
1.243     albertel 12427: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12428: 
                   12429: =item *
                   12430: 
1.243     albertel 12431: logthis() : append message to the normal lonnet.log file, it gets
                   12432: preiodically rolled over and deleted.
1.191     harris41 12433: 
                   12434: =item *
                   12435: 
1.243     albertel 12436: logperm() : append a permanent message to lonnet.perm.log, this log
                   12437: file never gets deleted by any automated portion of the system, only
                   12438: messages of critical importance should go in here.
                   12439: 
1.1119    foxr     12440: 
1.243     albertel 12441: =back
                   12442: 
                   12443: =head2 General File Helper Routines
                   12444: 
                   12445: =over 4
1.191     harris41 12446: 
                   12447: =item *
                   12448: 
1.481     raeburn  12449: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12450: (a) files in /uploaded
                   12451:   (i) If a local copy of the file exists - 
                   12452:       compares modification date of local copy with last-modified date for 
                   12453:       definitive version stored on home server for course. If local copy is 
                   12454:       stale, requests a new version from the home server and stores it. 
                   12455:       If the original has been removed from the home server, then local copy 
                   12456:       is unlinked.
                   12457:   (ii) If local copy does not exist -
                   12458:       requests the file from the home server and stores it. 
                   12459:   
                   12460:   If $caller is 'uploadrep':  
                   12461:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12462:     for request for files originally uploaded via DOCS. 
                   12463:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12464:   
                   12465:   Otherwise:
                   12466:      This indicates a call from the content generation phase of the request.
                   12467:      -  returns the entire contents of the file or -1.
                   12468:      
                   12469: (b) files in /res
                   12470:    - returns the entire contents of a file or -1; 
                   12471:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12472: 
1.712     albertel 12473: 
                   12474: =item *
                   12475: 
                   12476: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12477:                   reference
                   12478: 
                   12479: returns either a stat() list of data about the file or an empty list
                   12480: if the file doesn't exist or couldn't find out about it (connection
                   12481: problems or user unknown)
                   12482: 
1.191     harris41 12483: =item *
                   12484: 
1.243     albertel 12485: filelocation($dir,$file) : returns file system location of a file
                   12486: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12487: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12488: and a file of ../bob will become /a/bob)
1.191     harris41 12489: 
                   12490: =item *
                   12491: 
                   12492: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12493: filelocation except for hrefs
                   12494: 
                   12495: =item *
                   12496: 
                   12497: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12498: 
1.243     albertel 12499: =back
                   12500: 
1.608     albertel 12501: =head2 Usererfile file routines (/uploaded*)
                   12502: 
                   12503: =over 4
                   12504: 
                   12505: =item *
                   12506: 
                   12507: userfileupload(): main rotine for putting a file in a user or course's
                   12508:                   filespace, arguments are,
                   12509: 
1.620     albertel 12510:  formname - required - this is the name of the element in $env where the
1.608     albertel 12511:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12512:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12513:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12514:  context - if coursedoc, store the file in the course of the active role
                   12515:              of the current user; 
                   12516:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12517:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12518:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12519:          if undefined, it will be placed in "unknown"
                   12520: 
                   12521:  (This routine calls clean_filename() to remove any dangerous
                   12522:  characters from the filename, and then calls finuserfileupload() to
                   12523:  complete the transaction)
                   12524: 
                   12525:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12526:  and /adm/notfound.html if unsuccessful
                   12527: 
                   12528: =item *
                   12529: 
                   12530: clean_filename(): routine for cleaing a filename up for storage in
                   12531:                  userfile space, argument is:
                   12532: 
                   12533:  filename - proposed filename
                   12534: 
                   12535: returns: the new clean filename
                   12536: 
                   12537: =item *
                   12538: 
1.1090    raeburn  12539: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12540: userspace, probably shouldn't be called directly
                   12541: 
                   12542:   docuname: username or courseid of destination for the file
                   12543:   docudom: domain of user/course of destination for the file
                   12544:   formname: same as for userfileupload()
1.1090    raeburn  12545:   fname: filename (including subdirectories) for the file
                   12546:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12547:   allfiles: reference to hash used to store objects found by parser
                   12548:   codebase: reference to hash used for codebases of java objects found by parser
                   12549:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12550:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12551:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12552:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12553:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12554:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12555:   mimetype: reference to scalar to accommodate mime type determined
                   12556:             from File::MMagic if $parser = parse.
1.608     albertel 12557: 
                   12558:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12559:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12560:  was 'overwrite').
                   12561:  
1.608     albertel 12562: 
                   12563: =item *
                   12564: 
                   12565: renameuserfile(): renames an existing userfile to a new name
                   12566: 
                   12567:   Args:
                   12568:    docuname: username or courseid of destination for the file
                   12569:    docudom: domain of user/course of destination for the file
                   12570:    old: current file name (including any subdirs under userfiles)
                   12571:    new: desired file name (including any subdirs under userfiles)
                   12572: 
                   12573: =item *
                   12574: 
                   12575: mkdiruserfile(): creates a directory is a userfiles dir
                   12576: 
                   12577:   Args:
                   12578:    docuname: username or courseid of destination for the file
                   12579:    docudom: domain of user/course of destination for the file
                   12580:    dir: dir to create (including any subdirs under userfiles)
                   12581: 
                   12582: =item *
                   12583: 
                   12584: removeuserfile(): removes a file that exists in userfiles
                   12585: 
                   12586:   Args:
                   12587:    docuname: username or courseid of destination for the file
                   12588:    docudom: domain of user/course of destination for the file
                   12589:    fname: filname to delete (including any subdirs under userfiles)
                   12590: 
                   12591: =item *
                   12592: 
                   12593: removeuploadedurl(): convience function for removeuserfile()
                   12594: 
                   12595:   Args:
                   12596:    url:  a full /uploaded/... url to delete
                   12597: 
1.747     albertel 12598: =item * 
                   12599: 
                   12600: get_portfile_permissions():
                   12601:   Args:
                   12602:     domain: domain of user or course contain the portfolio files
                   12603:     user: name of user or num of course contain the portfolio files
                   12604:   Returns:
                   12605:     hashref of a dump of the proper file_permissions.db
                   12606:    
                   12607: 
                   12608: =item * 
                   12609: 
                   12610: get_access_controls():
                   12611: 
                   12612: Args:
                   12613:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12614:   group: (optional) the group you want the files associated with
                   12615:   file: (optional) the file you want access info on
                   12616: 
                   12617: Returns:
1.749     raeburn  12618:     a hash (keys are file names) of hashes containing
                   12619:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12620:         values are XML containing access control settings (see below) 
1.747     albertel 12621: 
                   12622: Internal notes:
                   12623: 
1.749     raeburn  12624:  access controls are stored in file_permissions.db as key=value pairs.
                   12625:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12626:         where scope -> public,guest,course,group,domains or users.
                   12627:               end -> UNIX time for end of access (0 -> no end date)
                   12628:               start -> UNIX time for start of access
                   12629: 
                   12630:     value -> XML description of access control
                   12631:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12632:             <start></start>
                   12633:             <end></end>
                   12634: 
                   12635:             <password></password>  for scope type = guest
                   12636: 
                   12637:             <domain></domain>     for scope type = course or group
                   12638:             <number></number>
                   12639:             <roles id="">
                   12640:              <role></role>
                   12641:              <access></access>
                   12642:              <section></section>
                   12643:              <group></group>
                   12644:             </roles>
                   12645: 
                   12646:             <dom></dom>         for scope type = domains
                   12647: 
                   12648:             <users>             for scope type = users
                   12649:              <user>
                   12650:               <uname></uname>
                   12651:               <udom></udom>
                   12652:              </user>
                   12653:             </users>
                   12654:            </scope> 
                   12655:               
                   12656:  Access data is also aggregated for each file in an additional key=value pair:
                   12657:  key -> path to file/file_name\0accesscontrol 
                   12658:  value -> reference to hash
                   12659:           hash contains key = value pairs
                   12660:           where key = uniqueID:scope_end_start
                   12661:                 value = UNIX time record was last updated
                   12662: 
                   12663:           Used to improve speed of look-ups of access controls for each file.  
                   12664:  
                   12665:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12666: 
                   12667: modify_access_controls():
                   12668: 
                   12669: Modifies access controls for a portfolio file
                   12670: Args
                   12671: 1. file name
                   12672: 2. reference to hash of required changes,
                   12673: 3. domain
                   12674: 4. username
                   12675:   where domain,username are the domain of the portfolio owner 
                   12676:   (either a user or a course) 
                   12677: 
                   12678: Returns:
                   12679: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12680: 2. result of deletions ('ok' or 'error', with error message).
                   12681: 3. reference to hash of any new or updated access controls.
                   12682: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12683:    key = integer (inbound ID)
                   12684:    value = uniqueID  
1.747     albertel 12685: 
1.608     albertel 12686: =back
                   12687: 
1.243     albertel 12688: =head2 HTTP Helper Routines
                   12689: 
                   12690: =over 4
                   12691: 
1.191     harris41 12692: =item *
                   12693: 
                   12694: escape() : unpack non-word characters into CGI-compatible hex codes
                   12695: 
                   12696: =item *
                   12697: 
                   12698: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12699: 
1.243     albertel 12700: =back
                   12701: 
                   12702: =head1 PRIVATE SUBROUTINES
                   12703: 
                   12704: =head2 Underlying communication routines (Shouldn't call)
                   12705: 
                   12706: =over 4
                   12707: 
                   12708: =item *
                   12709: 
                   12710: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12711: 
                   12712: =item *
                   12713: 
                   12714: reply() : uses subreply to send a message to remote machine, logs all failures
                   12715: 
                   12716: =item *
                   12717: 
                   12718: critical() : passes a critical message to another server; if cannot
                   12719: get through then place message in connection buffer directory and
                   12720: returns con_delayed, if incapable of saving message, returns
                   12721: con_failed
                   12722: 
                   12723: =item *
                   12724: 
                   12725: reconlonc() : tries to reconnect lonc client processes.
                   12726: 
                   12727: =back
                   12728: 
                   12729: =head2 Resource Access Logging
                   12730: 
                   12731: =over 4
                   12732: 
                   12733: =item *
                   12734: 
                   12735: flushcourselogs() : flush (save) buffer logs and access logs
                   12736: 
                   12737: =item *
                   12738: 
                   12739: courselog($what) : save message for course in hash
                   12740: 
                   12741: =item *
                   12742: 
                   12743: courseacclog($what) : save message for course using &courselog().  Perform
                   12744: special processing for specific resource types (problems, exams, quizzes, etc).
                   12745: 
1.191     harris41 12746: =item *
                   12747: 
                   12748: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12749: as a PerlChildExitHandler
1.243     albertel 12750: 
                   12751: =back
                   12752: 
                   12753: =head2 Other
                   12754: 
                   12755: =over 4
                   12756: 
                   12757: =item *
                   12758: 
                   12759: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12760: 
                   12761: =back
                   12762: 
                   12763: =cut
1.877     foxr     12764: 

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