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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.4! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.3 2012/05/29 12:16:42 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'};
1.1172.2.4! raeburn  1239:     my @hosts = &current_machine_ids();
1.1129    raeburn  1240:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1241:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1242:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1243:     my $serverhomedom = &host_domain($lonhost);
                   1244: 
                   1245:     my $cachetime = 60*60*24;
                   1246: 
                   1247:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1248:         $dom_in_use = $udom;
                   1249:         $homeintdom = 1;
                   1250:     } else {
                   1251:         $dom_in_use = $serverhomedom;
                   1252:     }
                   1253:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1254:     unless (defined($cached)) {
                   1255:         my %domconfig =
                   1256:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1257:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1258:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1259:         }
                   1260:     }
                   1261:     if (ref($result) eq 'HASH') {
                   1262:         my $currbalancer = $result->{'lonhost'};
                   1263:         my $currtargets = $result->{'targets'};
                   1264:         my $currrules = $result->{'rules'};
                   1265:         if ($currbalancer ne '') {
                   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:     }
1.1172.2.4! raeburn  1381:     if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
        !          1382:         $is_balancer = 0;
        !          1383:     }
1.1129    raeburn  1384:     return ($is_balancer,$otherserver);
                   1385: }
                   1386: 
                   1387: sub get_loadbalancer_targets {
                   1388:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1389:     my $offloadto;
1.1172.2.4! raeburn  1390:     if ($rule_in_effect eq 'none') {
        !          1391:         return [$perlvar{'lonHostID'}];
        !          1392:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1393:         $offloadto = $currtargets;
                   1394:     } else {
                   1395:         if ($rule_in_effect eq 'homeserver') {
                   1396:             my $homeserver = &homeserver($uname,$udom);
                   1397:             if ($homeserver ne 'no_host') {
                   1398:                 $offloadto = [$homeserver];
                   1399:             }
                   1400:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1401:             my %domconfig =
                   1402:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1403:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1404:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1405:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1406:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1407:                     }
                   1408:                 }
                   1409:             } else {
                   1410:                 my %servers = &dom_servers($udom);
                   1411:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1412:                 if (&hostname($remotebalancer) ne '') {
                   1413:                     $offloadto = [$remotebalancer];
                   1414:                 }
                   1415:             }
                   1416:         } elsif (&hostname($rule_in_effect) ne '') {
                   1417:             $offloadto = [$rule_in_effect];
                   1418:         }
                   1419:     }
                   1420:     return $offloadto;
                   1421: }
                   1422: 
1.1127    raeburn  1423: sub internet_dom_servers {
                   1424:     my ($dom) = @_;
                   1425:     my (%uniqservers,%servers);
                   1426:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1427:     my @machinedoms = &machine_domains($primaryserver);
                   1428:     foreach my $mdom (@machinedoms) {
                   1429:         my %currservers = %servers;
                   1430:         my %server = &get_servers($mdom);
                   1431:         %servers = (%currservers,%server);
                   1432:     }
                   1433:     my %by_hostname;
                   1434:     foreach my $id (keys(%servers)) {
                   1435:         push(@{$by_hostname{$servers{$id}}},$id);
                   1436:     }
                   1437:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1438:         if (@{$by_hostname{$hostname}} > 1) {
                   1439:             my $match = 0;
                   1440:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1441:                 if (&host_domain($id) eq $dom) {
                   1442:                     $uniqservers{$id} = $hostname;
                   1443:                     $match = 1;
                   1444:                 }
                   1445:             }
                   1446:             unless ($match) {
                   1447:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1448:             }
                   1449:         } else {
                   1450:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1451:         }
                   1452:     }
                   1453:     return %uniqservers;
                   1454: }
                   1455: 
1.1       albertel 1456: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1457: 
1.599     albertel 1458: my %homecache;
1.1       albertel 1459: sub homeserver {
1.230     stredwic 1460:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1461:     my $index="$uname:$udom";
1.426     albertel 1462: 
1.599     albertel 1463:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1464: 
                   1465:     my %servers = &get_servers($udom,'library');
                   1466:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1467:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1468: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1469: 
                   1470: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1471: 	if ($answer eq 'found') {
                   1472: 	    delete($badServerCache{$tryserver}); 
                   1473: 	    return $homecache{$index}=$tryserver;
                   1474: 	} elsif ($answer eq 'no_host') {
                   1475: 	    $badServerCache{$tryserver}=1;
                   1476: 	}
1.1       albertel 1477:     }    
                   1478:     return 'no_host';
1.70      www      1479: }
                   1480: 
                   1481: # ------------------------------------- Find the usernames behind a list of IDs
                   1482: 
                   1483: sub idget {
                   1484:     my ($udom,@ids)=@_;
                   1485:     my %returnhash=();
                   1486:     
1.841     albertel 1487:     my %servers = &get_servers($udom,'library');
                   1488:     foreach my $tryserver (keys(%servers)) {
                   1489: 	my $idlist=join('&',@ids);
                   1490: 	$idlist=~tr/A-Z/a-z/; 
                   1491: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1492: 	my @answer=();
                   1493: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1494: 	    @answer=split(/\&/,$reply);
                   1495: 	}                    ;
                   1496: 	my $i;
                   1497: 	for ($i=0;$i<=$#ids;$i++) {
                   1498: 	    if ($answer[$i]) {
                   1499: 		$returnhash{$ids[$i]}=$answer[$i];
                   1500: 	    } 
                   1501: 	}
                   1502:     } 
1.70      www      1503:     return %returnhash;
                   1504: }
                   1505: 
                   1506: # ------------------------------------- Find the IDs behind a list of usernames
                   1507: 
                   1508: sub idrget {
                   1509:     my ($udom,@unames)=@_;
                   1510:     my %returnhash=();
1.800     albertel 1511:     foreach my $uname (@unames) {
                   1512:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1513:     }
1.70      www      1514:     return %returnhash;
                   1515: }
                   1516: 
                   1517: # ------------------------------- Store away a list of names and associated IDs
                   1518: 
                   1519: sub idput {
                   1520:     my ($udom,%ids)=@_;
                   1521:     my %servers=();
1.800     albertel 1522:     foreach my $uname (keys(%ids)) {
                   1523: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1524:         my $uhom=&homeserver($uname,$udom);
1.70      www      1525:         if ($uhom ne 'no_host') {
1.800     albertel 1526:             my $id=&escape($ids{$uname});
1.70      www      1527:             $id=~tr/A-Z/a-z/;
1.800     albertel 1528:             my $esc_unam=&escape($uname);
1.70      www      1529: 	    if ($servers{$uhom}) {
1.800     albertel 1530: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1531:             } else {
1.800     albertel 1532:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1533:             }
                   1534:         }
1.191     harris41 1535:     }
1.800     albertel 1536:     foreach my $server (keys(%servers)) {
                   1537:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1538:     }
1.344     www      1539: }
                   1540: 
1.1023    raeburn  1541: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1542: sub dump_dom {
1.1165    droeschl 1543:     my ($namespace, $udom, $regexp) = @_;
                   1544: 
                   1545:     $udom ||= $env{'user.domain'};
                   1546: 
                   1547:     return () unless $udom;
                   1548: 
                   1549:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1550: }
                   1551: 
1.1023    raeburn  1552: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1553: 
                   1554: sub get_dom {
1.860     raeburn  1555:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1556:     my $items='';
                   1557:     foreach my $item (@$storearr) {
                   1558:         $items.=&escape($item).'&';
                   1559:     }
                   1560:     $items=~s/\&$//;
1.860     raeburn  1561:     if (!$udom) {
                   1562:         $udom=$env{'user.domain'};
                   1563:         if (defined(&domain($udom,'primary'))) {
                   1564:             $uhome=&domain($udom,'primary');
                   1565:         } else {
1.874     albertel 1566:             undef($uhome);
1.860     raeburn  1567:         }
                   1568:     } else {
                   1569:         if (!$uhome) {
                   1570:             if (defined(&domain($udom,'primary'))) {
                   1571:                 $uhome=&domain($udom,'primary');
                   1572:             }
                   1573:         }
                   1574:     }
                   1575:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1576:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1577:         my %returnhash;
1.875     albertel 1578:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1579:             return %returnhash;
                   1580:         }
1.806     raeburn  1581:         my @pairs=split(/\&/,$rep);
                   1582:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1583:             return @pairs;
                   1584:         }
                   1585:         my $i=0;
                   1586:         foreach my $item (@$storearr) {
                   1587:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1588:             $i++;
                   1589:         }
                   1590:         return %returnhash;
                   1591:     } else {
1.880     banghart 1592:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1593:     }
                   1594: }
                   1595: 
                   1596: # -------------------------------------------- put items in domain db files 
                   1597: 
                   1598: sub put_dom {
1.860     raeburn  1599:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1600:     if (!$udom) {
                   1601:         $udom=$env{'user.domain'};
                   1602:         if (defined(&domain($udom,'primary'))) {
                   1603:             $uhome=&domain($udom,'primary');
                   1604:         } else {
1.874     albertel 1605:             undef($uhome);
1.860     raeburn  1606:         }
                   1607:     } else {
                   1608:         if (!$uhome) {
                   1609:             if (defined(&domain($udom,'primary'))) {
                   1610:                 $uhome=&domain($udom,'primary');
                   1611:             }
                   1612:         }
                   1613:     } 
                   1614:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1615:         my $items='';
                   1616:         foreach my $item (keys(%$storehash)) {
                   1617:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1618:         }
                   1619:         $items=~s/\&$//;
                   1620:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1621:     } else {
1.860     raeburn  1622:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1623:     }
                   1624: }
                   1625: 
1.1023    raeburn  1626: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1627: sub newput_dom {
1.1023    raeburn  1628:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1629:     my $result;
                   1630:     if (!$udom) {
                   1631:         $udom=$env{'user.domain'};
                   1632:     }
1.1023    raeburn  1633:     if ($udom) {
                   1634:         my $uname = &get_domainconfiguser($udom);
                   1635:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1636:     }
                   1637:     return $result;
                   1638: }
                   1639: 
1.1023    raeburn  1640: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1641: sub del_dom {
1.1023    raeburn  1642:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1643:     if (ref($storearr) eq 'ARRAY') {
                   1644:         if (!$udom) {
                   1645:             $udom=$env{'user.domain'};
                   1646:         }
1.1023    raeburn  1647:         if ($udom) {
                   1648:             my $uname = &get_domainconfiguser($udom); 
                   1649:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1650:         }
                   1651:     }
                   1652: }
                   1653: 
1.1023    raeburn  1654: # ----------------------------------construct domainconfig user for a domain 
                   1655: sub get_domainconfiguser {
                   1656:     my ($udom) = @_;
                   1657:     return $udom.'-domainconfig';
                   1658: }
                   1659: 
1.837     raeburn  1660: sub retrieve_inst_usertypes {
                   1661:     my ($udom) = @_;
                   1662:     my (%returnhash,@order);
1.989     raeburn  1663:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1664:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1665:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1666:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1667:         @order = @{$domdefs{'inststatusorder'}};
                   1668:     } else {
                   1669:         if (defined(&domain($udom,'primary'))) {
                   1670:             my $uhome=&domain($udom,'primary');
                   1671:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1672:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1673:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1674:                 return (\%returnhash,\@order);
                   1675:             }
                   1676:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1677:             my @pairs=split(/\&/,$hashitems);
                   1678:             foreach my $item (@pairs) {
                   1679:                 my ($key,$value)=split(/=/,$item,2);
                   1680:                 $key = &unescape($key);
                   1681:                 next if ($key =~ /^error: 2 /);
                   1682:                 $returnhash{$key}=&thaw_unescape($value);
                   1683:             }
                   1684:             my @esc_order = split(/\&/,$orderitems);
                   1685:             foreach my $item (@esc_order) {
                   1686:                 push(@order,&unescape($item));
                   1687:             }
                   1688:         } else {
                   1689:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1690:         }
                   1691:     }
                   1692:     return (\%returnhash,\@order);
                   1693: }
                   1694: 
1.868     raeburn  1695: sub is_domainimage {
                   1696:     my ($url) = @_;
                   1697:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1698:         if (&domain($1) ne '') {
                   1699:             return '1';
                   1700:         }
                   1701:     }
                   1702:     return;
                   1703: }
                   1704: 
1.899     raeburn  1705: sub inst_directory_query {
                   1706:     my ($srch) = @_;
                   1707:     my $udom = $srch->{'srchdomain'};
                   1708:     my %results;
                   1709:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1710:     my $outcome;
1.899     raeburn  1711:     if ($homeserver ne '') {
1.904     albertel 1712: 	my $queryid=&reply("querysend:instdirsearch:".
                   1713: 			   &escape($srch->{'srchby'}).':'.
                   1714: 			   &escape($srch->{'srchterm'}).':'.
                   1715: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1716: 	my $host=&hostname($homeserver);
                   1717: 	if ($queryid !~/^\Q$host\E\_/) {
                   1718: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1719: 	    return;
                   1720: 	}
                   1721: 	my $response = &get_query_reply($queryid);
                   1722: 	my $maxtries = 5;
                   1723: 	my $tries = 1;
                   1724: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1725: 	    $response = &get_query_reply($queryid);
                   1726: 	    $tries ++;
                   1727: 	}
                   1728: 
                   1729:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1730:             if ($response eq 'unavailable') {
                   1731:                 $outcome = $response;
                   1732:             } else {
                   1733:                 $outcome = 'ok';
                   1734:                 my @matches = split(/\n/,$response);
                   1735:                 foreach my $match (@matches) {
                   1736:                     my ($key,$value) = split(/=/,$match);
                   1737:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1738:                 }
1.899     raeburn  1739:             }
                   1740:         }
                   1741:     }
1.909     raeburn  1742:     return ($outcome,%results);
1.899     raeburn  1743: }
                   1744: 
                   1745: sub usersearch {
                   1746:     my ($srch) = @_;
                   1747:     my $dom = $srch->{'srchdomain'};
                   1748:     my %results;
                   1749:     my %libserv = &all_library();
                   1750:     my $query = 'usersearch';
                   1751:     foreach my $tryserver (keys(%libserv)) {
                   1752:         if (&host_domain($tryserver) eq $dom) {
                   1753:             my $host=&hostname($tryserver);
                   1754:             my $queryid=
1.911     raeburn  1755:                 &reply("querysend:".&escape($query).':'.
                   1756:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1757:                        &escape($srch->{'srchtype'}).':'.
                   1758:                        &escape($srch->{'srchterm'}),$tryserver);
                   1759:             if ($queryid !~/^\Q$host\E\_/) {
                   1760:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1761:                 next;
1.899     raeburn  1762:             }
                   1763:             my $reply = &get_query_reply($queryid);
                   1764:             my $maxtries = 1;
                   1765:             my $tries = 1;
                   1766:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1767:                 $reply = &get_query_reply($queryid);
                   1768:                 $tries ++;
                   1769:             }
                   1770:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1771:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1772:             } else {
1.911     raeburn  1773:                 my @matches;
                   1774:                 if ($reply =~ /\n/) {
                   1775:                     @matches = split(/\n/,$reply);
                   1776:                 } else {
                   1777:                     @matches = split(/\&/,$reply);
                   1778:                 }
1.899     raeburn  1779:                 foreach my $match (@matches) {
                   1780:                     my ($uname,$udom,%userhash);
1.911     raeburn  1781:                     foreach my $entry (split(/:/,$match)) {
                   1782:                         my ($key,$value) =
                   1783:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1784:                         $userhash{$key} = $value;
                   1785:                         if ($key eq 'username') {
                   1786:                             $uname = $value;
                   1787:                         } elsif ($key eq 'domain') {
                   1788:                             $udom = $value;
1.911     raeburn  1789:                         }
1.899     raeburn  1790:                     }
                   1791:                     $results{$uname.':'.$udom} = \%userhash;
                   1792:                 }
                   1793:             }
                   1794:         }
                   1795:     }
                   1796:     return %results;
                   1797: }
                   1798: 
1.912     raeburn  1799: sub get_instuser {
                   1800:     my ($udom,$uname,$id) = @_;
                   1801:     my $homeserver = &domain($udom,'primary');
                   1802:     my ($outcome,%results);
                   1803:     if ($homeserver ne '') {
                   1804:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1805:                            &escape($id).':'.&escape($udom),$homeserver);
                   1806:         my $host=&hostname($homeserver);
                   1807:         if ($queryid !~/^\Q$host\E\_/) {
                   1808:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1809:             return;
                   1810:         }
                   1811:         my $response = &get_query_reply($queryid);
                   1812:         my $maxtries = 5;
                   1813:         my $tries = 1;
                   1814:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1815:             $response = &get_query_reply($queryid);
                   1816:             $tries ++;
                   1817:         }
                   1818:         if (!&error($response) && $response ne 'refused') {
                   1819:             if ($response eq 'unavailable') {
                   1820:                 $outcome = $response;
                   1821:             } else {
                   1822:                 $outcome = 'ok';
                   1823:                 my @matches = split(/\n/,$response);
                   1824:                 foreach my $match (@matches) {
                   1825:                     my ($key,$value) = split(/=/,$match);
                   1826:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1827:                 }
                   1828:             }
                   1829:         }
                   1830:     }
                   1831:     my %userinfo;
                   1832:     if (ref($results{$uname}) eq 'HASH') {
                   1833:         %userinfo = %{$results{$uname}};
                   1834:     } 
                   1835:     return ($outcome,%userinfo);
                   1836: }
                   1837: 
                   1838: sub inst_rulecheck {
1.923     raeburn  1839:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1840:     my %returnhash;
                   1841:     if ($udom ne '') {
                   1842:         if (ref($rules) eq 'ARRAY') {
                   1843:             @{$rules} = map {&escape($_);} (@{$rules});
                   1844:             my $rulestr = join(':',@{$rules});
                   1845:             my $homeserver=&domain($udom,'primary');
                   1846:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1847:                 my $response;
                   1848:                 if ($item eq 'username') {                
                   1849:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1850:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1851:                                               $homeserver));
1.923     raeburn  1852:                 } elsif ($item eq 'id') {
                   1853:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1854:                                               ':'.&escape($id).':'.$rulestr,
                   1855:                                               $homeserver));
1.945     raeburn  1856:                 } elsif ($item eq 'selfcreate') {
                   1857:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1858:                                                &escape($udom).':'.&escape($uname).
                   1859:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1860:                 }
1.912     raeburn  1861:                 if ($response ne 'refused') {
                   1862:                     my @pairs=split(/\&/,$response);
                   1863:                     foreach my $item (@pairs) {
                   1864:                         my ($key,$value)=split(/=/,$item,2);
                   1865:                         $key = &unescape($key);
                   1866:                         next if ($key =~ /^error: 2 /);
                   1867:                         $returnhash{$key}=&thaw_unescape($value);
                   1868:                     }
                   1869:                 }
                   1870:             }
                   1871:         }
                   1872:     }
                   1873:     return %returnhash;
                   1874: }
                   1875: 
                   1876: sub inst_userrules {
1.923     raeburn  1877:     my ($udom,$check) = @_;
1.912     raeburn  1878:     my (%ruleshash,@ruleorder);
                   1879:     if ($udom ne '') {
                   1880:         my $homeserver=&domain($udom,'primary');
                   1881:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1882:             my $response;
                   1883:             if ($check eq 'id') {
                   1884:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1885:                                  $homeserver);
1.943     raeburn  1886:             } elsif ($check eq 'email') {
                   1887:                 $response=&reply('instemailrules:'.&escape($udom),
                   1888:                                  $homeserver);
1.923     raeburn  1889:             } else {
                   1890:                 $response=&reply('instuserrules:'.&escape($udom),
                   1891:                                  $homeserver);
                   1892:             }
1.912     raeburn  1893:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1894:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1895:                 ($response ne 'no_such_host')) {
                   1896:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1897:                 my @pairs=split(/\&/,$hashitems);
                   1898:                 foreach my $item (@pairs) {
                   1899:                     my ($key,$value)=split(/=/,$item,2);
                   1900:                     $key = &unescape($key);
                   1901:                     next if ($key =~ /^error: 2 /);
                   1902:                     $ruleshash{$key}=&thaw_unescape($value);
                   1903:                 }
                   1904:                 my @esc_order = split(/\&/,$orderitems);
                   1905:                 foreach my $item (@esc_order) {
                   1906:                     push(@ruleorder,&unescape($item));
                   1907:                 }
                   1908:             }
                   1909:         }
                   1910:     }
                   1911:     return (\%ruleshash,\@ruleorder);
                   1912: }
                   1913: 
1.976     raeburn  1914: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1915: 
                   1916: sub get_domain_defaults {
                   1917:     my ($domain) = @_;
                   1918:     my $cachetime = 60*60*24;
                   1919:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1920:     if (defined($cached)) {
                   1921:         if (ref($result) eq 'HASH') {
                   1922:             return %{$result};
                   1923:         }
                   1924:     }
                   1925:     my %domdefaults;
                   1926:     my %domconfig =
1.989     raeburn  1927:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1928:                                   'requestcourses','inststatus',
1.1073    raeburn  1929:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1930:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1931:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1932:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1933:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1934:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1935:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1936:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1937:     } else {
                   1938:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1939:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1940:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1941:     }
1.976     raeburn  1942:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1943:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1944:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1945:         } else {
                   1946:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1947:         } 
                   1948:         my @usertools = ('aboutme','blog','portfolio');
                   1949:         foreach my $item (@usertools) {
                   1950:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1951:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1952:             }
                   1953:         }
                   1954:     }
1.985     raeburn  1955:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1956:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1957:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1958:         }
                   1959:     }
1.989     raeburn  1960:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1961:         foreach my $item ('inststatustypes','inststatusorder') {
                   1962:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1963:         }
                   1964:     }
1.1047    raeburn  1965:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1966:         foreach my $item ('canuse_pdfforms') {
                   1967:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1968:         }
                   1969:     }
1.1073    raeburn  1970:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1971:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1972:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1973:         }
                   1974:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1975:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1976:         }
                   1977:     }
1.943     raeburn  1978:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1979:                                   $cachetime);
                   1980:     return %domdefaults;
                   1981: }
                   1982: 
1.344     www      1983: # --------------------------------------------------- Assign a key to a student
                   1984: 
                   1985: sub assign_access_key {
1.364     www      1986: #
                   1987: # a valid key looks like uname:udom#comments
                   1988: # comments are being appended
                   1989: #
1.498     www      1990:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1991:     $kdom=
1.620     albertel 1992:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1993:     $knum=
1.620     albertel 1994:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1995:     $cdom=
1.620     albertel 1996:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1997:     $cnum=
1.620     albertel 1998:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1999:     $udom=$env{'user.name'} unless (defined($udom));
                   2000:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2001:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2002:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2003:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2004:                                                   # assigned to this person
                   2005:                                                   # - this should not happen,
1.345     www      2006:                                                   # unless something went wrong
                   2007:                                                   # the first time around
                   2008: # ready to assign
1.364     www      2009:         $logentry=$1.'; '.$logentry;
1.496     www      2010:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2011:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2012: # key now belongs to user
1.346     www      2013: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2014:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2015:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2016:                 return 'ok';
                   2017:             } else {
                   2018:                 return 
                   2019:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2020: 	    }
                   2021:         } else {
                   2022:             return 'error: Could not assign key, try again later.';
                   2023:         }
1.364     www      2024:     } elsif (!$existing{$ckey}) {
1.345     www      2025: # the key does not exist
                   2026: 	return 'error: The key does not exist';
                   2027:     } else {
                   2028: # the key is somebody else's
                   2029: 	return 'error: The key is already in use';
                   2030:     }
1.344     www      2031: }
                   2032: 
1.364     www      2033: # ------------------------------------------ put an additional comment on a key
                   2034: 
                   2035: sub comment_access_key {
                   2036: #
                   2037: # a valid key looks like uname:udom#comments
                   2038: # comments are being appended
                   2039: #
                   2040:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2041:     $cdom=
1.620     albertel 2042:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2043:     $cnum=
1.620     albertel 2044:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2045:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2046:     if ($existing{$ckey}) {
                   2047:         $existing{$ckey}.='; '.$logentry;
                   2048: # ready to assign
1.367     www      2049:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2050:                                                  $cdom,$cnum) eq 'ok') {
                   2051: 	    return 'ok';
                   2052:         } else {
                   2053: 	    return 'error: Count not store comment.';
                   2054:         }
                   2055:     } else {
                   2056: # the key does not exist
                   2057: 	return 'error: The key does not exist';
                   2058:     }
                   2059: }
                   2060: 
1.344     www      2061: # ------------------------------------------------------ Generate a set of keys
                   2062: 
                   2063: sub generate_access_keys {
1.364     www      2064:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2065:     $cdom=
1.620     albertel 2066:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2067:     $cnum=
1.620     albertel 2068:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2069:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2070:     unless (($cdom) && ($cnum)) { return 0; }
                   2071:     if ($number>10000) { return 0; }
                   2072:     sleep(2); # make sure don't get same seed twice
                   2073:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2074:     my $total=0;
                   2075:     for (my $i=1;$i<=$number;$i++) {
                   2076:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2077:                   sprintf("%lx",int(100000*rand)).'-'.
                   2078:                   sprintf("%lx",int(100000*rand));
                   2079:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2080:        $newkey=~s/0/h/g; # and also 0 and O
                   2081:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2082:        if ($existing{$newkey}) {
                   2083:            $i--;
                   2084:        } else {
1.364     www      2085: 	  if (&put('accesskeys',
                   2086:               { $newkey => '# generated '.localtime().
1.620     albertel 2087:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2088:                            '; '.$logentry },
                   2089: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2090:               $total++;
                   2091: 	  }
                   2092:        }
                   2093:     }
1.620     albertel 2094:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2095:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2096:     return $total;
                   2097: }
                   2098: 
                   2099: # ------------------------------------------------------- Validate an accesskey
                   2100: 
                   2101: sub validate_access_key {
                   2102:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2103:     $cdom=
1.620     albertel 2104:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2105:     $cnum=
1.620     albertel 2106:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2107:     $udom=$env{'user.domain'} unless (defined($udom));
                   2108:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2109:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2110:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2111: }
                   2112: 
                   2113: # ------------------------------------- Find the section of student in a course
1.652     albertel 2114: sub devalidate_getsection_cache {
                   2115:     my ($udom,$unam,$courseid)=@_;
                   2116:     my $hashid="$udom:$unam:$courseid";
                   2117:     &devalidate_cache_new('getsection',$hashid);
                   2118: }
1.298     matthew  2119: 
1.815     albertel 2120: sub courseid_to_courseurl {
                   2121:     my ($courseid) = @_;
                   2122:     #already url style courseid
                   2123:     return $courseid if ($courseid =~ m{^/});
                   2124: 
                   2125:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2126: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2127: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2128: 	return "/$cdom/$cnum";
                   2129:     }
                   2130: 
                   2131:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2132:     if (exists($courseinfo{'num'})) {
                   2133: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2134:     }
                   2135: 
                   2136:     return undef;
                   2137: }
                   2138: 
1.298     matthew  2139: sub getsection {
                   2140:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2141:     my $cachetime=1800;
1.551     albertel 2142: 
                   2143:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2144:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2145:     if (defined($cached)) { return $result; }
                   2146: 
1.298     matthew  2147:     my %Pending; 
                   2148:     my %Expired;
                   2149:     #
                   2150:     # Each role can either have not started yet (pending), be active, 
                   2151:     #    or have expired.
                   2152:     #
                   2153:     # If there is an active role, we are done.
                   2154:     #
                   2155:     # If there is more than one role which has not started yet, 
                   2156:     #     choose the one which will start sooner
                   2157:     # If there is one role which has not started yet, return it.
                   2158:     #
                   2159:     # If there is more than one expired role, choose the one which ended last.
                   2160:     # If there is a role which has expired, return it.
                   2161:     #
1.815     albertel 2162:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2163:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2164:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2165:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2166:         my $section=$1;
                   2167:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2168:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2169:         my $now=time;
1.548     albertel 2170:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2171:             $Expired{$end}=$section;
                   2172:             next;
                   2173:         }
1.548     albertel 2174:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2175:             $Pending{$start}=$section;
                   2176:             next;
                   2177:         }
1.599     albertel 2178:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2179:     }
                   2180:     #
                   2181:     # Presumedly there will be few matching roles from the above
                   2182:     # loop and the sorting time will be negligible.
                   2183:     if (scalar(keys(%Pending))) {
                   2184:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2185:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2186:     } 
                   2187:     if (scalar(keys(%Expired))) {
                   2188:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2189:         my $time = pop(@sorted);
1.599     albertel 2190:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2191:     }
1.599     albertel 2192:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2193: }
1.70      www      2194: 
1.599     albertel 2195: sub save_cache {
                   2196:     &purge_remembered();
1.722     albertel 2197:     #&Apache::loncommon::validate_page();
1.620     albertel 2198:     undef(%env);
1.780     albertel 2199:     undef($env_loaded);
1.599     albertel 2200: }
1.452     albertel 2201: 
1.599     albertel 2202: my $to_remember=-1;
                   2203: my %remembered;
                   2204: my %accessed;
                   2205: my $kicks=0;
                   2206: my $hits=0;
1.849     albertel 2207: sub make_key {
                   2208:     my ($name,$id) = @_;
1.872     albertel 2209:     if (length($id) > 65 
                   2210: 	&& length(&escape($id)) > 200) {
                   2211: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2212:     }
1.849     albertel 2213:     return &escape($name.':'.$id);
                   2214: }
                   2215: 
1.599     albertel 2216: sub devalidate_cache_new {
                   2217:     my ($name,$id,$debug) = @_;
                   2218:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2219:     $id=&make_key($name,$id);
1.599     albertel 2220:     $memcache->delete($id);
                   2221:     delete($remembered{$id});
                   2222:     delete($accessed{$id});
                   2223: }
                   2224: 
                   2225: sub is_cached_new {
                   2226:     my ($name,$id,$debug) = @_;
1.849     albertel 2227:     $id=&make_key($name,$id);
1.599     albertel 2228:     if (exists($remembered{$id})) {
1.1133    foxr     2229: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2230: 	$accessed{$id}=[&gettimeofday()];
                   2231: 	$hits++;
                   2232: 	return ($remembered{$id},1);
                   2233:     }
                   2234:     my $value = $memcache->get($id);
                   2235:     if (!(defined($value))) {
                   2236: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2237: 	return (undef,undef);
1.416     albertel 2238:     }
1.599     albertel 2239:     if ($value eq '__undef__') {
                   2240: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2241: 	$value=undef;
                   2242:     }
                   2243:     &make_room($id,$value,$debug);
                   2244:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2245:     return ($value,1);
                   2246: }
                   2247: 
                   2248: sub do_cache_new {
                   2249:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2250:     $id=&make_key($name,$id);
1.599     albertel 2251:     my $setvalue=$value;
                   2252:     if (!defined($setvalue)) {
                   2253: 	$setvalue='__undef__';
                   2254:     }
1.623     albertel 2255:     if (!defined($time) ) {
                   2256: 	$time=600;
                   2257:     }
1.599     albertel 2258:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2259:     my $result = $memcache->set($id,$setvalue,$time);
                   2260:     if (! $result) {
1.872     albertel 2261: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2262: 	$memcache->disconnect_all();
1.872     albertel 2263:     }
1.600     albertel 2264:     # need to make a copy of $value
1.919     albertel 2265:     &make_room($id,$value,$debug);
1.599     albertel 2266:     return $value;
                   2267: }
                   2268: 
                   2269: sub make_room {
                   2270:     my ($id,$value,$debug)=@_;
1.919     albertel 2271: 
                   2272:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2273:                                     : $value;
1.599     albertel 2274:     if ($to_remember<0) { return; }
                   2275:     $accessed{$id}=[&gettimeofday()];
                   2276:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2277:     my $to_kick;
                   2278:     my $max_time=0;
                   2279:     foreach my $other (keys(%accessed)) {
                   2280: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2281: 	    $to_kick=$other;
                   2282: 	    $max_time=&tv_interval($accessed{$other});
                   2283: 	}
                   2284:     }
                   2285:     delete($remembered{$to_kick});
                   2286:     delete($accessed{$to_kick});
                   2287:     $kicks++;
                   2288:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2289:     return;
                   2290: }
                   2291: 
1.599     albertel 2292: sub purge_remembered {
1.604     albertel 2293:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2294:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2295:     undef(%remembered);
                   2296:     undef(%accessed);
1.428     albertel 2297: }
1.70      www      2298: # ------------------------------------- Read an entry from a user's environment
                   2299: 
                   2300: sub userenvironment {
                   2301:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2302:     my $items;
                   2303:     foreach my $item (@what) {
                   2304:         $items.=&escape($item).'&';
                   2305:     }
                   2306:     $items=~s/\&$//;
1.70      www      2307:     my %returnhash=();
1.1009    raeburn  2308:     my $uhome = &homeserver($unam,$udom);
                   2309:     unless ($uhome eq 'no_host') {
                   2310:         my @answer=split(/\&/, 
                   2311:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2312:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2313:             return %returnhash;
                   2314:         }
1.1009    raeburn  2315:         my $i;
                   2316:         for ($i=0;$i<=$#what;$i++) {
                   2317: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2318:         }
1.70      www      2319:     }
                   2320:     return %returnhash;
1.1       albertel 2321: }
                   2322: 
1.617     albertel 2323: # ---------------------------------------------------------- Get a studentphoto
                   2324: sub studentphoto {
                   2325:     my ($udom,$unam,$ext) = @_;
                   2326:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2327:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2328:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2329:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2330:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2331:             } else {
                   2332:                 my ($result,$perm_reqd)=
1.707     albertel 2333: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2334:                 if ($result eq 'ok') {
                   2335:                     if (!($perm_reqd eq 'yes')) {
                   2336:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2337:                     }
                   2338:                 }
                   2339:             }
                   2340:         }
                   2341:     } else {
                   2342:         my ($result,$perm_reqd) = 
1.707     albertel 2343: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2344:         if ($result eq 'ok') {
                   2345:             if (!($perm_reqd eq 'yes')) {
                   2346:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2347:             }
                   2348:         }
                   2349:     }
                   2350:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2351: }
                   2352: 
                   2353: sub retrievestudentphoto {
                   2354:     my ($udom,$unam,$ext,$type) = @_;
                   2355:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2356:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2357:     if ($ret eq 'ok') {
                   2358:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2359:         if ($type eq 'thumbnail') {
                   2360:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2361:         }
                   2362:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2363:         return $tokenurl;
                   2364:     } else {
                   2365:         if ($type eq 'thumbnail') {
                   2366:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2367:         } else { 
                   2368:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2369:         }
1.617     albertel 2370:     }
                   2371: }
                   2372: 
1.263     www      2373: # -------------------------------------------------------------------- New chat
                   2374: 
                   2375: sub chatsend {
1.724     raeburn  2376:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2377:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2378:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2379:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2380:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2381: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2382: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2383: }
                   2384: 
                   2385: # ------------------------------------------ Find current version of a resource
                   2386: 
                   2387: sub getversion {
                   2388:     my $fname=&clutter(shift);
                   2389:     unless ($fname=~/^\/res\//) { return -1; }
                   2390:     return &currentversion(&filelocation('',$fname));
                   2391: }
                   2392: 
                   2393: sub currentversion {
                   2394:     my $fname=shift;
                   2395:     my $author=$fname;
                   2396:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2397:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2398:     my $home=&homeserver($uname,$udom);
1.292     www      2399:     if ($home eq 'no_host') { 
                   2400:         return -1; 
                   2401:     }
1.1112    www      2402:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2403:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2404: 	return -1;
                   2405:     }
1.1112    www      2406:     return $answer;
1.263     www      2407: }
                   2408: 
1.1111    www      2409: #
                   2410: # Return special version number of resource if set by override, empty otherwise
                   2411: #
                   2412: sub usedversion {
                   2413:     my $fname=shift;
                   2414:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2415:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2416:     if ($urlversion) { return $urlversion; }
                   2417:     return '';
                   2418: }
                   2419: 
1.1       albertel 2420: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2421: 
1.1       albertel 2422: sub subscribe {
                   2423:     my $fname=shift;
1.761     raeburn  2424:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2425:     $fname=~s/[\n\r]//g;
1.1       albertel 2426:     my $author=$fname;
                   2427:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2428:     my ($udom,$uname)=split(/\//,$author);
                   2429:     my $home=homeserver($uname,$udom);
1.335     albertel 2430:     if ($home eq 'no_host') {
                   2431:         return 'not_found';
1.1       albertel 2432:     }
                   2433:     my $answer=reply("sub:$fname",$home);
1.64      www      2434:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2435: 	$answer.=' by '.$home;
                   2436:     }
1.1       albertel 2437:     return $answer;
                   2438: }
                   2439:     
1.8       www      2440: # -------------------------------------------------------------- Replicate file
                   2441: 
                   2442: sub repcopy {
                   2443:     my $filename=shift;
1.23      www      2444:     $filename=~s/\/+/\//g;
1.1142    raeburn  2445:     my $londocroot = $perlvar{'lonDocRoot'};
                   2446:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2447:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2448:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2449: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2450: 	return &repcopy_userfile($filename);
                   2451:     }
1.532     albertel 2452:     $filename=~s/[\n\r]//g;
1.8       www      2453:     my $transname="$filename.in.transfer";
1.828     www      2454: # FIXME: this should flock
1.607     raeburn  2455:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2456:     my $remoteurl=subscribe($filename);
1.64      www      2457:     if ($remoteurl =~ /^con_lost by/) {
                   2458: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2459:            return 'unavailable';
1.8       www      2460:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2461: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2462: 	   return 'not_found';
1.64      www      2463:     } elsif ($remoteurl =~ /^rejected by/) {
                   2464: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2465:            return 'forbidden';
1.20      www      2466:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2467:            return 'ok';
1.8       www      2468:     } else {
1.290     www      2469:         my $author=$filename;
                   2470:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2471:         my ($udom,$uname)=split(/\//,$author);
                   2472:         my $home=homeserver($uname,$udom);
                   2473:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2474:            my @parts=split(/\//,$filename);
                   2475:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2476:            if ($path ne "$londocroot/res") {
1.8       www      2477:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2478: 	       return 'bad_request';
1.8       www      2479:            }
                   2480:            my $count;
                   2481:            for ($count=5;$count<$#parts;$count++) {
                   2482:                $path.="/$parts[$count]";
                   2483:                if ((-e $path)!=1) {
                   2484: 		   mkdir($path,0777);
                   2485:                }
                   2486:            }
                   2487:            my $ua=new LWP::UserAgent;
                   2488:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2489:            my $response=$ua->request($request,$transname);
                   2490:            if ($response->is_error()) {
                   2491: 	       unlink($transname);
                   2492:                my $message=$response->status_line;
1.672     albertel 2493:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2494:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2495:                return 'unavailable';
1.8       www      2496:            } else {
1.16      www      2497: 	       if ($remoteurl!~/\.meta$/) {
                   2498:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2499:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2500:                   if ($mresponse->is_error()) {
                   2501: 		      unlink($filename.'.meta');
                   2502:                       &logthis(
1.672     albertel 2503:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2504:                   }
                   2505: 	       }
1.8       www      2506:                rename($transname,$filename);
1.607     raeburn  2507:                return 'ok';
1.8       www      2508:            }
1.290     www      2509:        }
1.8       www      2510:     }
1.330     www      2511: }
                   2512: 
                   2513: # ------------------------------------------------ Get server side include body
                   2514: sub ssi_body {
1.381     albertel 2515:     my ($filelink,%form)=@_;
1.606     matthew  2516:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2517:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2518:     }
1.953     www      2519:     my $output='';
                   2520:     my $response;
1.980     raeburn  2521:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2522:        ($output,$response)=&externalssi($filelink);
1.953     www      2523:     } else {
1.1004    droeschl 2524:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2525:        $filelink .= 'inhibitmenu=yes';
1.953     www      2526:        ($output,$response)=&ssi($filelink,%form);
                   2527:     }
1.778     albertel 2528:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2529:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2530:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2531:     if (wantarray) {
                   2532:         return ($output, $response);
                   2533:     } else {
                   2534:         return $output;
                   2535:     }
1.8       www      2536: }
                   2537: 
1.15      www      2538: # --------------------------------------------------------- Server Side Include
                   2539: 
1.782     albertel 2540: sub absolute_url {
                   2541:     my ($host_name) = @_;
                   2542:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2543:     if ($host_name eq '') {
                   2544: 	$host_name = $ENV{'SERVER_NAME'};
                   2545:     }
                   2546:     return $protocol.$host_name;
                   2547: }
                   2548: 
1.942     foxr     2549: #
                   2550: #   Server side include.
                   2551: # Parameters:
                   2552: #  fn     Possibly encrypted resource name/id.
                   2553: #  form   Hash that describes how the rendering should be done
                   2554: #         and other things.
1.944     foxr     2555: # Returns:
1.950     raeburn  2556: #   Scalar context: The content of the response.
                   2557: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2558: #     
1.15      www      2559: sub ssi {
                   2560: 
1.944     foxr     2561:     my ($fn,%form)=@_;
1.15      www      2562:     my $ua=new LWP::UserAgent;
1.23      www      2563:     my $request;
1.711     albertel 2564: 
                   2565:     $form{'no_update_last_known'}=1;
1.895     albertel 2566:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2567:     if (%form) {
1.782     albertel 2568:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2569:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2570:     } else {
1.782     albertel 2571:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2572:     }
                   2573: 
1.15      www      2574:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2575:     my $response= $ua->request($request);
1.944     foxr     2576:     if (wantarray) {
1.1172.2.3  raeburn  2577: 	return ($response->content, $response);
1.944     foxr     2578:     } else {
1.1172.2.3  raeburn  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.1169    droeschl 3496:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3497:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3498:        $userrolehash
                   3499:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3500:                     =$tend.':'.$tstart;
1.662     raeburn  3501:     }
1.1169    droeschl 3502:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3503:        $userrolehash
                   3504:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3505:                     =$tend.':'.$tstart;
                   3506:     }
1.1169    droeschl 3507:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3508:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3509:        $domainrolehash
                   3510:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3511:                     = $tend.':'.$tstart;
                   3512:     }
1.351     www      3513: }
                   3514: 
1.957     raeburn  3515: sub courserolelog {
                   3516:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3517:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3518:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3519:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3520:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3521:         ($trole eq 'co')) {
1.957     raeburn  3522:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3523:             my $cdom = $1;
                   3524:             my $cnum = $2;
                   3525:             my $sec = $3;
                   3526:             my $namespace = 'rolelog';
                   3527:             my %storehash = (
                   3528:                                role    => $trole,
                   3529:                                start   => $tstart,
                   3530:                                end     => $tend,
                   3531:                                selfenroll => $selfenroll,
                   3532:                                context    => $context,
                   3533:                             );
                   3534:             if ($trole eq 'gr') {
                   3535:                 $namespace = 'groupslog';
                   3536:                 $storehash{'group'} = $sec;
                   3537:             } else {
                   3538:                 $storehash{'section'} = $sec;
                   3539:             }
                   3540:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3541:             if (($trole ne 'st') || ($sec ne '')) {
                   3542:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3543:             }
1.957     raeburn  3544:         }
                   3545:     }
                   3546:     return;
                   3547: }
                   3548: 
1.351     www      3549: sub get_course_adv_roles {
1.948     raeburn  3550:     my ($cid,$codes) = @_;
1.620     albertel 3551:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3552:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3553:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3554:     my %nothide=();
1.800     albertel 3555:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3556:         if ($user !~ /:/) {
                   3557: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3558:         } else {
                   3559:             $nothide{$user}=1;
                   3560:         }
1.470     www      3561:     }
1.351     www      3562:     my %returnhash=();
                   3563:     my %dumphash=
                   3564:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3565:     my $now=time;
1.997     raeburn  3566:     my %privileged;
1.1000    raeburn  3567:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3568: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3569:         if (($tstart) && ($tstart<0)) { next; }
                   3570:         if (($tend) && ($tend<$now)) { next; }
                   3571:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3572:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3573: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3574:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3575:             my %dompersonnel =
1.998     raeburn  3576:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3577:             $privileged{$domain} = {};
                   3578:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3579:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3580:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3581:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3582:                         $privileged{$udom}{$uname} = 1;
                   3583:                     }
                   3584:                 }
                   3585:             }
                   3586:         }
                   3587:         if ((exists($privileged{$domain}{$username})) && 
                   3588:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3589: 	if ($role eq 'cr') { next; }
1.948     raeburn  3590:         if ($codes) {
                   3591:             if ($section) { $role .= ':'.$section; }
                   3592:             if ($returnhash{$role}) {
                   3593:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3594:             } else {
                   3595:                 $returnhash{$role}=$username.':'.$domain;
                   3596:             }
1.351     www      3597:         } else {
1.988     raeburn  3598:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3599:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3600:             if ($returnhash{$key}) {
                   3601: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3602:             } else {
                   3603:                 $returnhash{$key}=$username.':'.$domain;
                   3604:             }
1.351     www      3605:         }
1.948     raeburn  3606:     }
1.400     www      3607:     return %returnhash;
                   3608: }
                   3609: 
                   3610: sub get_my_roles {
1.937     raeburn  3611:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3612:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3613:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3614:     my (%dumphash,%nothide);
1.1086    raeburn  3615:     if ($context eq 'userroles') {
1.1166    raeburn  3616:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3617:     } else {
                   3618:         %dumphash=
1.400     www      3619:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3620:         if ($hidepriv) {
                   3621:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3622:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3623:                 if ($user !~ /:/) {
                   3624:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3625:                 } else {
                   3626:                     $nothide{$user} = 1;
                   3627:                 }
                   3628:             }
                   3629:         }
1.858     raeburn  3630:     }
1.400     www      3631:     my %returnhash=();
                   3632:     my $now=time;
1.999     raeburn  3633:     my %privileged;
1.800     albertel 3634:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3635:         my ($role,$tend,$tstart);
                   3636:         if ($context eq 'userroles') {
1.1149    raeburn  3637:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3638: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3639:         } else {
                   3640:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3641:         }
1.400     www      3642:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3643:         my $status = 'active';
1.939     raeburn  3644:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3645:             $status = 'previous';
                   3646:         } 
                   3647:         if (($tstart) && ($now<$tstart)) {
                   3648:             $status = 'future';
                   3649:         }
                   3650:         if (ref($types) eq 'ARRAY') {
                   3651:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3652:                 next;
                   3653:             } 
                   3654:         } else {
                   3655:             if ($status ne 'active') {
                   3656:                 next;
                   3657:             }
                   3658:         }
1.867     raeburn  3659:         my ($rolecode,$username,$domain,$section,$area);
                   3660:         if ($context eq 'userroles') {
                   3661:             ($area,$rolecode) = split(/_/,$entry);
                   3662:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3663:         } else {
                   3664:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3665:         }
1.832     raeburn  3666:         if (ref($roledoms) eq 'ARRAY') {
                   3667:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3668:                 next;
                   3669:             }
                   3670:         }
                   3671:         if (ref($roles) eq 'ARRAY') {
                   3672:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3673:                 if ($role =~ /^cr\//) {
                   3674:                     if (!grep(/^cr$/,@{$roles})) {
                   3675:                         next;
                   3676:                     }
1.1104    raeburn  3677:                 } elsif ($role =~ /^gr\//) {
                   3678:                     if (!grep(/^gr$/,@{$roles})) {
                   3679:                         next;
                   3680:                     }
1.922     raeburn  3681:                 } else {
                   3682:                     next;
                   3683:                 }
1.832     raeburn  3684:             }
1.867     raeburn  3685:         }
1.937     raeburn  3686:         if ($hidepriv) {
1.999     raeburn  3687:             if ($context eq 'userroles') {
                   3688:                 if ((&privileged($username,$domain)) &&
                   3689:                     (!$nothide{$username.':'.$domain})) {
                   3690:                     next;
                   3691:                 }
                   3692:             } else {
                   3693:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3694:                     my %dompersonnel =
                   3695:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3696:                     $privileged{$domain} = {};
                   3697:                     if (keys(%dompersonnel)) {
                   3698:                         foreach my $server (keys(%dompersonnel)) {
                   3699:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3700:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3701:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3702:                                     $privileged{$udom}{$uname} = $trole;
                   3703:                                 }
                   3704:                             }
                   3705:                         }
                   3706:                     }
                   3707:                 }
                   3708:                 if (exists($privileged{$domain}{$username})) {
                   3709:                     if (!$nothide{$username.':'.$domain}) {
                   3710:                         next;
                   3711:                     }
                   3712:                 }
1.937     raeburn  3713:             }
                   3714:         }
1.933     raeburn  3715:         if ($withsec) {
                   3716:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3717:                 $tstart.':'.$tend;
                   3718:         } else {
                   3719:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3720:         }
1.832     raeburn  3721:     }
1.373     www      3722:     return %returnhash;
1.399     www      3723: }
                   3724: 
                   3725: # ----------------------------------------------------- Frontpage Announcements
                   3726: #
                   3727: #
                   3728: 
                   3729: sub postannounce {
                   3730:     my ($server,$text)=@_;
1.844     albertel 3731:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3732:     unless ($text=~/\w/) { $text=''; }
                   3733:     return &reply('setannounce:'.&escape($text),$server);
                   3734: }
                   3735: 
                   3736: sub getannounce {
1.448     albertel 3737: 
                   3738:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3739: 	my $announcement='';
1.800     albertel 3740: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3741: 	close($fh);
1.399     www      3742: 	if ($announcement=~/\w/) { 
                   3743: 	    return 
                   3744:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3745:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3746: 	} else {
                   3747: 	    return '';
                   3748: 	}
                   3749:     } else {
                   3750: 	return '';
                   3751:     }
1.351     www      3752: }
1.353     www      3753: 
                   3754: # ---------------------------------------------------------- Course ID routines
                   3755: # Deal with domain's nohist_courseid.db files
                   3756: #
                   3757: 
                   3758: sub courseidput {
1.921     raeburn  3759:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3760:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3761:     my $outcome;
                   3762:     if ($caller eq 'timeonly') {
                   3763:         my $cids = '';
                   3764:         foreach my $item (keys(%$storehash)) {
                   3765:             $cids.=&escape($item).'&';
                   3766:         }
                   3767:         $cids=~s/\&$//;
                   3768:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3769:                           $coursehome);       
                   3770:     } else {
                   3771:         my $items = '';
                   3772:         foreach my $item (keys(%$storehash)) {
                   3773:             $items.= &escape($item).'='.
                   3774:                      &freeze_escape($$storehash{$item}).'&';
                   3775:         }
                   3776:         $items=~s/\&$//;
                   3777:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3778:                           $coursehome);
1.918     raeburn  3779:     }
                   3780:     if ($outcome eq 'unknown_cmd') {
                   3781:         my $what;
                   3782:         foreach my $cid (keys(%$storehash)) {
                   3783:             $what .= &escape($cid).'=';
1.921     raeburn  3784:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3785:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3786:             }
                   3787:             $what =~ s/\:$/&/;
                   3788:         }
                   3789:         $what =~ s/\&$//;  
                   3790:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3791:     } else {
                   3792:         return $outcome;
                   3793:     }
1.353     www      3794: }
                   3795: 
                   3796: sub courseiddump {
1.921     raeburn  3797:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3798:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3799:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3800:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3801:     my $as_hash = 1;
                   3802:     my %returnhash;
                   3803:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3804:     my %libserv = &all_library();
                   3805:     foreach my $tryserver (keys(%libserv)) {
                   3806:         if ( (  $hostidflag == 1 
                   3807: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3808: 	     || (!defined($hostidflag)) ) {
                   3809: 
1.918     raeburn  3810: 	    if (($domfilter eq '') ||
                   3811: 		(&host_domain($tryserver) eq $domfilter)) {
                   3812:                 my $rep = 
                   3813:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3814:                          $sincefilter.':'.&escape($descfilter).':'.
                   3815:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3816:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3817:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3818:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3819:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3820:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3821:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3822:                          &escape($creationcontext).':'.$domcloner,
                   3823:                          $tryserver);
1.918     raeburn  3824:                 my @pairs=split(/\&/,$rep);
                   3825:                 foreach my $item (@pairs) {
                   3826:                     my ($key,$value)=split(/\=/,$item,2);
                   3827:                     $key = &unescape($key);
                   3828:                     next if ($key =~ /^error: 2 /);
                   3829:                     my $result = &thaw_unescape($value);
                   3830:                     if (ref($result) eq 'HASH') {
                   3831:                         $returnhash{$key}=$result;
                   3832:                     } else {
1.921     raeburn  3833:                         my @responses = split(/:/,$value);
                   3834:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3835:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3836:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3837:                         }
1.1008    raeburn  3838:                     }
1.353     www      3839:                 }
                   3840:             }
                   3841:         }
                   3842:     }
                   3843:     return %returnhash;
                   3844: }
                   3845: 
1.1055    raeburn  3846: sub courselastaccess {
                   3847:     my ($cdom,$cnum,$hostidref) = @_;
                   3848:     my %returnhash;
                   3849:     if ($cdom && $cnum) {
                   3850:         my $chome = &homeserver($cnum,$cdom);
                   3851:         if ($chome ne 'no_host') {
                   3852:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3853:             &extract_lastaccess(\%returnhash,$rep);
                   3854:         }
                   3855:     } else {
                   3856:         if (!$cdom) { $cdom=''; }
                   3857:         my %libserv = &all_library();
                   3858:         foreach my $tryserver (keys(%libserv)) {
                   3859:             if (ref($hostidref) eq 'ARRAY') {
                   3860:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3861:             } 
                   3862:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3863:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3864:                 &extract_lastaccess(\%returnhash,$rep);
                   3865:             }
                   3866:         }
                   3867:     }
                   3868:     return %returnhash;
                   3869: }
                   3870: 
                   3871: sub extract_lastaccess {
                   3872:     my ($returnhash,$rep) = @_;
                   3873:     if (ref($returnhash) eq 'HASH') {
                   3874:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3875:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3876:                  $rep eq '') {
                   3877:             my @pairs=split(/\&/,$rep);
                   3878:             foreach my $item (@pairs) {
                   3879:                 my ($key,$value)=split(/\=/,$item,2);
                   3880:                 $key = &unescape($key);
                   3881:                 next if ($key =~ /^error: 2 /);
                   3882:                 $returnhash->{$key} = &thaw_unescape($value);
                   3883:             }
                   3884:         }
                   3885:     }
                   3886:     return;
                   3887: }
                   3888: 
1.658     raeburn  3889: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3890: 
                   3891: sub dcmailput {
1.685     raeburn  3892:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3893:     my $status = &Apache::lonnet::critical(
1.740     www      3894:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3895:        &escape($message),$server);
1.662     raeburn  3896:     return $status;
                   3897: }
                   3898: 
1.658     raeburn  3899: sub dcmaildump {
                   3900:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3901:     my %returnhash=();
1.846     albertel 3902: 
                   3903:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3904:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3905:                                                          &escape($enddate).':';
                   3906: 	my @esc_senders=map { &escape($_)} @$senders;
                   3907: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3908: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3909:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3910:             if (($key) && ($value)) {
                   3911:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3912:             }
                   3913:         }
                   3914:     }
                   3915:     return %returnhash;
                   3916: }
1.662     raeburn  3917: # ---------------------------------------------------------- Domain roles
                   3918: 
                   3919: sub get_domain_roles {
                   3920:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3921:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3922:         $startdate = '.';
                   3923:     }
1.1018    raeburn  3924:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3925:         $enddate = '.';
                   3926:     }
1.922     raeburn  3927:     my $rolelist;
                   3928:     if (ref($roles) eq 'ARRAY') {
                   3929:         $rolelist = join(':',@{$roles});
                   3930:     }
1.662     raeburn  3931:     my %personnel = ();
1.841     albertel 3932: 
                   3933:     my %servers = &get_servers($dom,'library');
                   3934:     foreach my $tryserver (keys(%servers)) {
                   3935: 	%{$personnel{$tryserver}}=();
                   3936: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3937: 					    &escape($startdate).':'.
                   3938: 					    &escape($enddate).':'.
                   3939: 					    &escape($rolelist), $tryserver))) {
                   3940: 	    my ($key,$value) = split(/\=/,$line,2);
                   3941: 	    if (($key) && ($value)) {
                   3942: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3943: 	    }
                   3944: 	}
1.662     raeburn  3945:     }
                   3946:     return %personnel;
                   3947: }
1.658     raeburn  3948: 
1.1057    www      3949: # ----------------------------------------------------------- Interval timing 
1.149     www      3950: 
1.1153    www      3951: {
                   3952: # Caches needed for speedup of navmaps
                   3953: # We don't want to cache this for very long at all (5 seconds at most)
                   3954: # 
                   3955: # The user for whom we cache
                   3956: my $cachedkey='';
                   3957: # The cached times for this user
                   3958: my %cachedtimes=();
                   3959: # When this was last done
                   3960: my $cachedtime=();
                   3961: 
                   3962: sub load_all_first_access {
1.1154    raeburn  3963:     my ($uname,$udom)=@_;
1.1156    www      3964:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  3965:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  3966:         return;
                   3967:     }
                   3968:     $cachedtime=time;
                   3969:     $cachedkey=$uname.':'.$udom;
                   3970:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3971: }
                   3972: 
1.504     albertel 3973: sub get_first_access {
1.1162    raeburn  3974:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 3975:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3976:     if ($argsymb) { $symb=$argsymb; }
                   3977:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  3978:     if ($argmap) { $map = $argmap; }
1.926     albertel 3979:     if ($type eq 'course') {
                   3980: 	$res='course';
                   3981:     } elsif ($type eq 'map') {
1.588     albertel 3982: 	$res=&symbread($map);
                   3983:     } else {
                   3984: 	$res=$symb;
                   3985:     }
1.1153    www      3986:     &load_all_first_access($uname,$udom);
                   3987:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3988: }
                   3989: 
                   3990: sub set_first_access {
1.1162    raeburn  3991:     my ($type,$interval)=@_;
1.790     albertel 3992:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3993:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3994:     if ($type eq 'course') {
                   3995: 	$res='course';
                   3996:     } elsif ($type eq 'map') {
1.588     albertel 3997: 	$res=&symbread($map);
                   3998:     } else {
                   3999: 	$res=$symb;
                   4000:     }
1.1153    www      4001:     $cachedkey='';
1.1162    raeburn  4002:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4003:     if (!$firstaccess) {
1.1162    raeburn  4004:         my $start = time;
                   4005: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4006:                           $udom,$uname);
                   4007:         if ($putres eq 'ok') {
                   4008:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4009:                  $udom,$uname); 
                   4010:             &appenv(
                   4011:                      {
                   4012:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4013:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4014:                      }
                   4015:                   );
                   4016:         }
                   4017:         return $putres;
1.505     albertel 4018:     }
                   4019:     return 'already_set';
1.504     albertel 4020: }
1.1153    www      4021: }
1.110     www      4022: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4023: 
                   4024: sub expirespread {
                   4025:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4026:     my $cid=$env{'request.course.id'}; 
1.110     www      4027:     if ($cid) {
                   4028:        my $now=time;
                   4029:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4030:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4031:                             $env{'course.'.$cid.'.num'}.
1.110     www      4032: 	        	    ':nohist_expirationdates:'.
                   4033:                             &escape($key).'='.$now,
1.620     albertel 4034:                             $env{'course.'.$cid.'.home'})
1.110     www      4035:     }
                   4036:     return 'ok';
1.14      www      4037: }
                   4038: 
1.109     www      4039: # ----------------------------------------------------- Devalidate Spreadsheets
                   4040: 
                   4041: sub devalidate {
1.325     www      4042:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4043:     my $cid=$env{'request.course.id'}; 
1.109     www      4044:     if ($cid) {
1.391     matthew  4045:         # delete the stored spreadsheets for
                   4046:         # - the student level sheet of this user in course's homespace
                   4047:         # - the assessment level sheet for this resource 
                   4048:         #   for this user in user's homespace
1.553     albertel 4049: 	# - current conditional state info
1.325     www      4050: 	my $key=$uname.':'.$udom.':';
1.109     www      4051:         my $status=
1.299     matthew  4052: 	    &del('nohist_calculatedsheets',
1.391     matthew  4053: 		 [$key.'studentcalc:'],
1.620     albertel 4054: 		 $env{'course.'.$cid.'.domain'},
                   4055: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4056: 		.' '.
                   4057: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4058: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4059:         unless ($status eq 'ok ok') {
                   4060:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4061:                     $uname.' at '.$udom.' for '.
1.109     www      4062: 		    $symb.': '.$status);
1.133     albertel 4063:         }
1.553     albertel 4064: 	&delenv('user.state.'.$cid);
1.109     www      4065:     }
                   4066: }
                   4067: 
1.265     albertel 4068: sub get_scalar {
                   4069:     my ($string,$end) = @_;
                   4070:     my $value;
                   4071:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4072: 	$value = $1;
                   4073:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4074: 	$value = $1;
                   4075:     }
                   4076:     return &unescape($value);
                   4077: }
                   4078: 
                   4079: sub array2str {
                   4080:   my (@array) = @_;
                   4081:   my $result=&arrayref2str(\@array);
                   4082:   $result=~s/^__ARRAY_REF__//;
                   4083:   $result=~s/__END_ARRAY_REF__$//;
                   4084:   return $result;
                   4085: }
                   4086: 
1.204     albertel 4087: sub arrayref2str {
                   4088:   my ($arrayref) = @_;
1.265     albertel 4089:   my $result='__ARRAY_REF__';
1.204     albertel 4090:   foreach my $elem (@$arrayref) {
1.265     albertel 4091:     if(ref($elem) eq 'ARRAY') {
                   4092:       $result.=&arrayref2str($elem).'&';
                   4093:     } elsif(ref($elem) eq 'HASH') {
                   4094:       $result.=&hashref2str($elem).'&';
                   4095:     } elsif(ref($elem)) {
                   4096:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4097:     } else {
                   4098:       $result.=&escape($elem).'&';
                   4099:     }
                   4100:   }
                   4101:   $result=~s/\&$//;
1.265     albertel 4102:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4103:   return $result;
                   4104: }
                   4105: 
1.168     albertel 4106: sub hash2str {
1.204     albertel 4107:   my (%hash) = @_;
                   4108:   my $result=&hashref2str(\%hash);
1.265     albertel 4109:   $result=~s/^__HASH_REF__//;
                   4110:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4111:   return $result;
                   4112: }
                   4113: 
                   4114: sub hashref2str {
                   4115:   my ($hashref)=@_;
1.265     albertel 4116:   my $result='__HASH_REF__';
1.800     albertel 4117:   foreach my $key (sort(keys(%$hashref))) {
                   4118:     if (ref($key) eq 'ARRAY') {
                   4119:       $result.=&arrayref2str($key).'=';
                   4120:     } elsif (ref($key) eq 'HASH') {
                   4121:       $result.=&hashref2str($key).'=';
                   4122:     } elsif (ref($key)) {
1.265     albertel 4123:       $result.='=';
1.800     albertel 4124:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4125:     } else {
1.1132    raeburn  4126: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4127:     }
                   4128: 
1.800     albertel 4129:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4130:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4131:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4132:       $result.=&hashref2str($hashref->{$key}).'&';
                   4133:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4134:        $result.='&';
1.800     albertel 4135:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4136:     } else {
1.800     albertel 4137:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4138:     }
                   4139:   }
1.168     albertel 4140:   $result=~s/\&$//;
1.265     albertel 4141:   $result .= '__END_HASH_REF__';
1.168     albertel 4142:   return $result;
                   4143: }
                   4144: 
                   4145: sub str2hash {
1.265     albertel 4146:     my ($string)=@_;
                   4147:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4148:     return %$hash;
                   4149: }
                   4150: 
                   4151: sub str2hashref {
1.168     albertel 4152:   my ($string) = @_;
1.265     albertel 4153: 
                   4154:   my %hash;
                   4155: 
                   4156:   if($string !~ /^__HASH_REF__/) {
                   4157:       if (! ($string eq '' || !defined($string))) {
                   4158: 	  $hash{'error'}='Not hash reference';
                   4159:       }
                   4160:       return (\%hash, $string);
                   4161:   }
                   4162: 
                   4163:   $string =~ s/^__HASH_REF__//;
                   4164: 
                   4165:   while($string !~ /^__END_HASH_REF__/) {
                   4166:       #key
                   4167:       my $key='';
                   4168:       if($string =~ /^__HASH_REF__/) {
                   4169:           ($key, $string)=&str2hashref($string);
                   4170:           if(defined($key->{'error'})) {
                   4171:               $hash{'error'}='Bad data';
                   4172:               return (\%hash, $string);
                   4173:           }
                   4174:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4175:           ($key, $string)=&str2arrayref($string);
                   4176:           if($key->[0] eq 'Array reference error') {
                   4177:               $hash{'error'}='Bad data';
                   4178:               return (\%hash, $string);
                   4179:           }
                   4180:       } else {
                   4181:           $string =~ s/^(.*?)=//;
1.267     albertel 4182: 	  $key=&unescape($1);
1.265     albertel 4183:       }
                   4184:       $string =~ s/^=//;
                   4185: 
                   4186:       #value
                   4187:       my $value='';
                   4188:       if($string =~ /^__HASH_REF__/) {
                   4189:           ($value, $string)=&str2hashref($string);
                   4190:           if(defined($value->{'error'})) {
                   4191:               $hash{'error'}='Bad data';
                   4192:               return (\%hash, $string);
                   4193:           }
                   4194:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4195:           ($value, $string)=&str2arrayref($string);
                   4196:           if($value->[0] eq 'Array reference error') {
                   4197:               $hash{'error'}='Bad data';
                   4198:               return (\%hash, $string);
                   4199:           }
                   4200:       } else {
                   4201: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4202:       }
                   4203:       $string =~ s/^&//;
                   4204: 
                   4205:       $hash{$key}=$value;
1.204     albertel 4206:   }
1.265     albertel 4207: 
                   4208:   $string =~ s/^__END_HASH_REF__//;
                   4209: 
                   4210:   return (\%hash, $string);
1.204     albertel 4211: }
                   4212: 
                   4213: sub str2array {
1.265     albertel 4214:     my ($string)=@_;
                   4215:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4216:     return @$array;
                   4217: }
                   4218: 
                   4219: sub str2arrayref {
1.204     albertel 4220:   my ($string) = @_;
1.265     albertel 4221:   my @array;
                   4222: 
                   4223:   if($string !~ /^__ARRAY_REF__/) {
                   4224:       if (! ($string eq '' || !defined($string))) {
                   4225: 	  $array[0]='Array reference error';
                   4226:       }
                   4227:       return (\@array, $string);
                   4228:   }
                   4229: 
                   4230:   $string =~ s/^__ARRAY_REF__//;
                   4231: 
                   4232:   while($string !~ /^__END_ARRAY_REF__/) {
                   4233:       my $value='';
                   4234:       if($string =~ /^__HASH_REF__/) {
                   4235:           ($value, $string)=&str2hashref($string);
                   4236:           if(defined($value->{'error'})) {
                   4237:               $array[0] ='Array reference error';
                   4238:               return (\@array, $string);
                   4239:           }
                   4240:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4241:           ($value, $string)=&str2arrayref($string);
                   4242:           if($value->[0] eq 'Array reference error') {
                   4243:               $array[0] ='Array reference error';
                   4244:               return (\@array, $string);
                   4245:           }
                   4246:       } else {
                   4247: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4248:       }
                   4249:       $string =~ s/^&//;
                   4250: 
                   4251:       push(@array, $value);
1.191     harris41 4252:   }
1.265     albertel 4253: 
                   4254:   $string =~ s/^__END_ARRAY_REF__//;
                   4255: 
                   4256:   return (\@array, $string);
1.168     albertel 4257: }
                   4258: 
1.167     albertel 4259: # -------------------------------------------------------------------Temp Store
                   4260: 
1.168     albertel 4261: sub tmpreset {
                   4262:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4263:   if (!$symb) {
                   4264:     $symb=&symbread();
1.620     albertel 4265:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4266:   }
                   4267:   $symb=escape($symb);
                   4268: 
1.620     albertel 4269:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4270:   $namespace=~s/\//\_/g;
                   4271:   $namespace=~s/\W//g;
                   4272: 
1.620     albertel 4273:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4274:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4275:   if ($domain eq 'public' && $stuname eq 'public') {
                   4276:       $stuname=$ENV{'REMOTE_ADDR'};
                   4277:   }
1.1117    foxr     4278:   my $path=LONCAPA::tempdir();
1.168     albertel 4279:   my %hash;
                   4280:   if (tie(%hash,'GDBM_File',
                   4281: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4282: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4283:     foreach my $key (keys(%hash)) {
1.180     albertel 4284:       if ($key=~ /:$symb/) {
1.168     albertel 4285: 	delete($hash{$key});
                   4286:       }
                   4287:     }
                   4288:   }
                   4289: }
                   4290: 
1.167     albertel 4291: sub tmpstore {
1.168     albertel 4292:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4293: 
                   4294:   if (!$symb) {
                   4295:     $symb=&symbread();
1.620     albertel 4296:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4297:   }
                   4298:   $symb=escape($symb);
                   4299: 
                   4300:   if (!$namespace) {
                   4301:     # I don't think we would ever want to store this for a course.
                   4302:     # it seems this will only be used if we don't have a course.
1.620     albertel 4303:     #$namespace=$env{'request.course.id'};
1.168     albertel 4304:     #if (!$namespace) {
1.620     albertel 4305:       $namespace=$env{'request.state'};
1.168     albertel 4306:     #}
                   4307:   }
                   4308:   $namespace=~s/\//\_/g;
                   4309:   $namespace=~s/\W//g;
1.620     albertel 4310:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4311:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4312:   if ($domain eq 'public' && $stuname eq 'public') {
                   4313:       $stuname=$ENV{'REMOTE_ADDR'};
                   4314:   }
1.168     albertel 4315:   my $now=time;
                   4316:   my %hash;
1.1117    foxr     4317:   my $path=LONCAPA::tempdir();
1.168     albertel 4318:   if (tie(%hash,'GDBM_File',
                   4319: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4320: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4321:     $hash{"version:$symb"}++;
                   4322:     my $version=$hash{"version:$symb"};
                   4323:     my $allkeys=''; 
                   4324:     foreach my $key (keys(%$storehash)) {
                   4325:       $allkeys.=$key.':';
1.591     albertel 4326:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4327:     }
                   4328:     $hash{"$version:$symb:timestamp"}=$now;
                   4329:     $allkeys.='timestamp';
                   4330:     $hash{"$version:keys:$symb"}=$allkeys;
                   4331:     if (untie(%hash)) {
                   4332:       return 'ok';
                   4333:     } else {
                   4334:       return "error:$!";
                   4335:     }
                   4336:   } else {
                   4337:     return "error:$!";
                   4338:   }
                   4339: }
1.167     albertel 4340: 
1.168     albertel 4341: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4342: 
1.168     albertel 4343: sub tmprestore {
                   4344:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4345: 
1.168     albertel 4346:   if (!$symb) {
                   4347:     $symb=&symbread();
1.620     albertel 4348:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4349:   }
                   4350:   $symb=escape($symb);
                   4351: 
1.620     albertel 4352:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4353: 
1.620     albertel 4354:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4355:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4356:   if ($domain eq 'public' && $stuname eq 'public') {
                   4357:       $stuname=$ENV{'REMOTE_ADDR'};
                   4358:   }
1.168     albertel 4359:   my %returnhash;
                   4360:   $namespace=~s/\//\_/g;
                   4361:   $namespace=~s/\W//g;
                   4362:   my %hash;
1.1117    foxr     4363:   my $path=LONCAPA::tempdir();
1.168     albertel 4364:   if (tie(%hash,'GDBM_File',
                   4365: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4366: 	  &GDBM_READER(),0640)) {
1.168     albertel 4367:     my $version=$hash{"version:$symb"};
                   4368:     $returnhash{'version'}=$version;
                   4369:     my $scope;
                   4370:     for ($scope=1;$scope<=$version;$scope++) {
                   4371:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4372:       my @keys=split(/:/,$vkeys);
                   4373:       my $key;
                   4374:       $returnhash{"$scope:keys"}=$vkeys;
                   4375:       foreach $key (@keys) {
1.591     albertel 4376: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4377: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4378:       }
                   4379:     }
1.168     albertel 4380:     if (!(untie(%hash))) {
                   4381:       return "error:$!";
                   4382:     }
                   4383:   } else {
                   4384:     return "error:$!";
                   4385:   }
                   4386:   return %returnhash;
1.167     albertel 4387: }
                   4388: 
1.9       www      4389: # ----------------------------------------------------------------------- Store
                   4390: 
                   4391: sub store {
1.124     www      4392:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4393:     my $home='';
                   4394: 
1.168     albertel 4395:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4396: 
1.213     www      4397:     $symb=&symbclean($symb);
1.122     albertel 4398:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4399: 
1.620     albertel 4400:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4401:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4402: 
                   4403:     &devalidate($symb,$stuname,$domain);
1.109     www      4404: 
                   4405:     $symb=escape($symb);
1.187     www      4406:     if (!$namespace) { 
1.620     albertel 4407:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4408:           return ''; 
                   4409:        } 
                   4410:     }
1.620     albertel 4411:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4412: 
                   4413:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4414:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4415: 
1.12      www      4416:     my $namevalue='';
1.800     albertel 4417:     foreach my $key (keys(%$storehash)) {
                   4418:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4419:     }
1.12      www      4420:     $namevalue=~s/\&$//;
1.187     www      4421:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4422:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4423: }
                   4424: 
1.47      www      4425: # -------------------------------------------------------------- Critical Store
                   4426: 
                   4427: sub cstore {
1.124     www      4428:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4429:     my $home='';
                   4430: 
1.168     albertel 4431:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4432: 
1.213     www      4433:     $symb=&symbclean($symb);
1.122     albertel 4434:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4435: 
1.620     albertel 4436:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4437:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4438: 
                   4439:     &devalidate($symb,$stuname,$domain);
1.109     www      4440: 
                   4441:     $symb=escape($symb);
1.187     www      4442:     if (!$namespace) { 
1.620     albertel 4443:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4444:           return ''; 
                   4445:        } 
                   4446:     }
1.620     albertel 4447:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4448: 
                   4449:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4450:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4451: 
1.47      www      4452:     my $namevalue='';
1.800     albertel 4453:     foreach my $key (keys(%$storehash)) {
                   4454:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4455:     }
1.47      www      4456:     $namevalue=~s/\&$//;
1.187     www      4457:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4458:     return critical
                   4459:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4460: }
                   4461: 
1.9       www      4462: # --------------------------------------------------------------------- Restore
                   4463: 
                   4464: sub restore {
1.124     www      4465:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4466:     my $home='';
                   4467: 
1.168     albertel 4468:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4469: 
1.122     albertel 4470:     if (!$symb) {
                   4471:       unless ($symb=escape(&symbread())) { return ''; }
                   4472:     } else {
1.213     www      4473:       $symb=&escape(&symbclean($symb));
1.122     albertel 4474:     }
1.188     www      4475:     if (!$namespace) { 
1.620     albertel 4476:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4477:           return ''; 
                   4478:        } 
                   4479:     }
1.620     albertel 4480:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4481:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4482:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4483:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4484: 
1.12      www      4485:     my %returnhash=();
1.800     albertel 4486:     foreach my $line (split(/\&/,$answer)) {
                   4487: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4488:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4489:     }
1.75      www      4490:     my $version;
                   4491:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4492:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4493:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4494:        }
1.75      www      4495:     }
1.13      www      4496:     return %returnhash;
1.34      www      4497: }
                   4498: 
                   4499: # ---------------------------------------------------------- Course Description
1.1118    foxr     4500: #
                   4501: #  
1.34      www      4502: 
                   4503: sub coursedescription {
1.731     albertel 4504:     my ($courseid,$args)=@_;
1.34      www      4505:     $courseid=~s/^\///;
1.49      www      4506:     $courseid=~s/\_/\//g;
1.34      www      4507:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4508:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4509:     my $normalid=$cdomain.'_'.$cnum;
                   4510:     # need to always cache even if we get errors otherwise we keep 
                   4511:     # trying and trying and trying to get the course description.
                   4512:     my %envhash=();
                   4513:     my %returnhash=();
1.731     albertel 4514:     
                   4515:     my $expiretime=600;
                   4516:     if ($env{'request.course.id'} eq $normalid) {
                   4517: 	$expiretime=120;
                   4518:     }
                   4519: 
                   4520:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4521:     if (!$args->{'freshen_cache'}
                   4522: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4523: 	foreach my $key (keys(%env)) {
                   4524: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4525: 	    my ($setting) = $1;
                   4526: 	    $returnhash{$setting} = $env{$key};
                   4527: 	}
                   4528: 	return %returnhash;
                   4529:     }
                   4530: 
1.1118    foxr     4531:     # get the data again
                   4532: 
1.731     albertel 4533:     if (!$args->{'one_time'}) {
                   4534: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4535:     }
1.811     albertel 4536: 
1.34      www      4537:     if ($chome ne 'no_host') {
1.302     albertel 4538:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4539:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4540: 	   my $username = $env{'user.name'}; # Defult username
                   4541: 	   if(defined $args->{'user'}) {
                   4542: 	       $username = $args->{'user'};
                   4543: 	   }
1.129     albertel 4544:            $returnhash{'home'}= $chome;
                   4545: 	   $returnhash{'domain'} = $cdomain;
                   4546: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4547:            if (!defined($returnhash{'type'})) {
                   4548:                $returnhash{'type'} = 'Course';
                   4549:            }
1.130     albertel 4550:            while (my ($name,$value) = each %returnhash) {
1.53      www      4551:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4552:            }
1.270     www      4553:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4554:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4555: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4556:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4557:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4558:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4559:        }
                   4560:     }
1.731     albertel 4561:     if (!$args->{'one_time'}) {
1.949     raeburn  4562: 	&appenv(\%envhash);
1.731     albertel 4563:     }
1.302     albertel 4564:     return %returnhash;
1.461     www      4565: }
                   4566: 
1.1080    raeburn  4567: sub update_released_required {
                   4568:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4569:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4570:         $cid = $env{'request.course.id'};
                   4571:         $cdom = $env{'course.'.$cid.'.domain'};
                   4572:         $cnum = $env{'course.'.$cid.'.num'};
                   4573:         $chome = $env{'course.'.$cid.'.home'};
                   4574:     }
                   4575:     if ($needsrelease) {
                   4576:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4577:         my $needsupdate;
                   4578:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4579:             $needsupdate = 1;
                   4580:         } else {
                   4581:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4582:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4583:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4584:                 $needsupdate = 1;
                   4585:             }
                   4586:         }
                   4587:         if ($needsupdate) {
                   4588:             my %needshash = (
                   4589:                              'internal.releaserequired' => $needsrelease,
                   4590:                             );
                   4591:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4592:             if ($putresult eq 'ok') {
                   4593:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4594:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4595:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4596:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4597:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4598:                 }
                   4599:             }
                   4600:         }
                   4601:     }
                   4602:     return;
                   4603: }
                   4604: 
1.461     www      4605: # -------------------------------------------------See if a user is privileged
                   4606: 
                   4607: sub privileged {
                   4608:     my ($username,$domain)=@_;
1.1170    droeschl 4609: 
                   4610:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4611:     my $now = time;
                   4612: 
                   4613:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4614:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4615:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4616:                 return 1 unless ($tend && $tend < $now) 
                   4617:                     or ($tstart && $tstart > $now);
                   4618:             }
1.461     www      4619: 	}
1.1170    droeschl 4620: 
1.461     www      4621:     return 0;
1.9       www      4622: }
1.1       albertel 4623: 
1.103     harris41 4624: # -------------------------------------------------------- Get user privileges
1.11      www      4625: 
                   4626: sub rolesinit {
1.1169    droeschl 4627:     my ($domain, $username) = @_;
                   4628:     my %userroles = ('user.login.time' => time);
                   4629:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4630: 
                   4631:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4632:     # also, blocking can be triggered by an activating timer
                   4633:     # it's saved in the user's %env.
                   4634:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4635:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4636:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4637:         %timerintchk, %timerintenv);
                   4638: 
1.1162    raeburn  4639:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4640:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4641:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4642:     }
1.1169    droeschl 4643: 
1.1162    raeburn  4644:     foreach my $key (keys(%timerinterval)) {
                   4645:         my ($cid,$rest) = split(/\0/,$key);
                   4646:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4647:     }
1.1169    droeschl 4648: 
1.11      www      4649:     my %allroles=();
1.1162    raeburn  4650:     my %allgroups=();
1.11      www      4651: 
1.1169    droeschl 4652:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4653:         my $role = $rolesdump{$area};
                   4654:         $area =~ s/\_\w\w$//;
                   4655: 
                   4656:         my ($trole, $tend, $tstart, $group_privs);
                   4657: 
                   4658:         if ($role =~ /^cr/) {
                   4659:         # Custom role, defined by a user 
                   4660:         # e.g., user.role.cr/msu/smith/mynewrole
                   4661:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4662:                 $trole = $1;
                   4663:                 ($tend, $tstart) = split('_', $2);
                   4664:             } else {
                   4665:                 $trole = $role;
                   4666:             }
                   4667:         } elsif ($role =~ m|^gr/|) {
                   4668:         # Role of member in a group, defined within a course/community
                   4669:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4670:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4671:             next if $tstart eq '-1';
                   4672:             ($trole, $group_privs) = split(/\//, $trole);
                   4673:             $group_privs = &unescape($group_privs);
                   4674:         } else {
                   4675:         # Just a normal role, defined in roles.tab
                   4676:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4677:         }
                   4678: 
                   4679:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4680:                  $username);
                   4681:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4682: 
                   4683:         # role expired or not available yet?
                   4684:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4685:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4686: 
                   4687:         next if $area eq '' or $trole eq '';
                   4688: 
                   4689:         my $spec = "$trole.$area";
                   4690:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4691: 
                   4692:         if ($trole =~ /^cr\//) {
                   4693:         # Custom role, defined by a user
                   4694:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4695:         } elsif ($trole eq 'gr') {
                   4696:         # Role of a member in a group, defined within a course/community
                   4697:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4698:             next;
                   4699:         } else {
                   4700:         # Normal role, defined in roles.tab
                   4701:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4702:         }
                   4703: 
                   4704:         my $cid = $tdomain.'_'.$trest;
                   4705:         unless ($firstaccchk{$cid}) {
                   4706:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4707:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4708:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4709:                         $coursetimerstarts{$cid}{$item}; 
                   4710:                 }
                   4711:             }
                   4712:             $firstaccchk{$cid} = 1;
                   4713:         }
                   4714:         unless ($timerintchk{$cid}) {
                   4715:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4716:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4717:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4718:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4719:                 }
1.12      www      4720:             }
1.1169    droeschl 4721:             $timerintchk{$cid} = 1;
1.191     harris41 4722:         }
1.11      www      4723:     }
1.1169    droeschl 4724: 
                   4725:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4726:         \%allroles, \%allgroups);
                   4727:     $env{'user.adv'} = $userroles{'user.adv'};
                   4728: 
1.1162    raeburn  4729:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4730: }
                   4731: 
1.567     raeburn  4732: sub set_arearole {
                   4733:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4734: # log the associated role with the area
                   4735:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4736:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4737: }
                   4738: 
                   4739: sub custom_roleprivs {
                   4740:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4741:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4742:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4743:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4744:         my ($rdummy,$roledef)=
                   4745:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4746:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4747:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4748:             if (defined($syspriv)) {
1.1043    raeburn  4749:                 if ($trest =~ /^$match_community$/) {
                   4750:                     $syspriv =~ s/bre\&S//; 
                   4751:                 }
1.567     raeburn  4752:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4753:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4754:             }
                   4755:             if ($tdomain ne '') {
                   4756:                 if (defined($dompriv)) {
                   4757:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4758:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4759:                 }
                   4760:                 if (($trest ne '') && (defined($coursepriv))) {
                   4761:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4762:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4763:                 }
                   4764:             }
                   4765:         }
                   4766:     }
                   4767: }
                   4768: 
1.678     raeburn  4769: sub group_roleprivs {
                   4770:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4771:     my $access = 1;
                   4772:     my $now = time;
                   4773:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4774:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4775:     if ($access) {
1.811     albertel 4776:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4777:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4778:     }
                   4779: }
1.567     raeburn  4780: 
                   4781: sub standard_roleprivs {
                   4782:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4783:     if (defined($pr{$trole.':s'})) {
                   4784:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4785:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4786:     }
                   4787:     if ($tdomain ne '') {
                   4788:         if (defined($pr{$trole.':d'})) {
                   4789:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4790:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4791:         }
                   4792:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4793:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4794:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4795:         }
                   4796:     }
                   4797: }
                   4798: 
                   4799: sub set_userprivs {
1.1064    raeburn  4800:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4801:     my $author=0;
                   4802:     my $adv=0;
1.678     raeburn  4803:     my %grouproles = ();
                   4804:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4805:         my @groupkeys; 
1.1000    raeburn  4806:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4807:             push(@groupkeys,$role);
                   4808:         }
                   4809:         if (ref($groups_roles) eq 'HASH') {
                   4810:             foreach my $key (keys(%{$groups_roles})) {
                   4811:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4812:                     push(@groupkeys,$key);
                   4813:                 }
                   4814:             }
                   4815:         }
                   4816:         if (@groupkeys > 0) {
                   4817:             foreach my $role (@groupkeys) {
                   4818:                 my ($trole,$area,$sec,$extendedarea);
                   4819:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4820:                     $trole = $1;
                   4821:                     $area = $2;
                   4822:                     $sec = $3;
                   4823:                     $extendedarea = $area.$sec;
                   4824:                     if (exists($$allgroups{$area})) {
                   4825:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4826:                             my $spec = $trole.'.'.$extendedarea;
                   4827:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4828:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4829:                         }
1.678     raeburn  4830:                     }
                   4831:                 }
                   4832:             }
                   4833:         }
                   4834:     }
1.800     albertel 4835:     foreach my $group (keys(%grouproles)) {
                   4836:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4837:     }
1.800     albertel 4838:     foreach my $role (keys(%{$allroles})) {
                   4839:         my %thesepriv;
1.941     raeburn  4840:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4841:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4842:             if ($item ne '') {
                   4843:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4844:                 if ($restrictions eq '') {
                   4845:                     $thesepriv{$privilege}='F';
                   4846:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4847:                     $thesepriv{$privilege}.=$restrictions;
                   4848:                 }
                   4849:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4850:             }
                   4851:         }
                   4852:         my $thesestr='';
1.1104    raeburn  4853:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4854: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4855: 	}
                   4856:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4857:     }
                   4858:     return ($author,$adv);
                   4859: }
                   4860: 
1.994     raeburn  4861: sub role_status {
1.1104    raeburn  4862:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4863:     my @pwhere = ();
                   4864:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4865:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4866:         unless (!defined($$role) || $$role eq '') {
                   4867:             $$where=join('.',@pwhere);
                   4868:             $$trolecode=$$role.'.'.$$where;
                   4869:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4870:             $$tstatus='is';
1.1104    raeburn  4871:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4872:                 $$tstatus='future';
1.1034    raeburn  4873:                 if ($$tstart<$now) {
                   4874:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4875:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4876:                             my (%allroles,%allgroups,$group_privs,
                   4877:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4878:                             my %userroles = (
                   4879:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4880:                             );
1.1064    raeburn  4881:                             @rolecodes = ('cm'); 
1.1002    raeburn  4882:                             my $spec=$$role.'.'.$$where;
                   4883:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4884:                             if ($$role =~ /^cr\//) {
                   4885:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4886:                                 push(@rolecodes,'cr');
1.1002    raeburn  4887:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4888:                                 push(@rolecodes,$$role);
1.1002    raeburn  4889:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4890:                                                     $env{'user.name'});
1.1064    raeburn  4891:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4892:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4893:                                 $group_privs = &unescape($group_privs);
                   4894:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4895:                                 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  4896:                                 &get_groups_roles($tdomain,$trest,
                   4897:                                                   \%course_roles,\@rolecodes,
                   4898:                                                   \%groups_roles);
1.1002    raeburn  4899:                             } else {
1.1064    raeburn  4900:                                 push(@rolecodes,$$role);
1.1002    raeburn  4901:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4902:                             }
1.1064    raeburn  4903:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4904:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4905:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4906:                         }
                   4907:                     }
1.1034    raeburn  4908:                     $$tstatus = 'is';
1.1002    raeburn  4909:                 }
1.994     raeburn  4910:             }
                   4911:             if ($$tend) {
1.1104    raeburn  4912:                 if ($$tend<$update) {
1.994     raeburn  4913:                     $$tstatus='expired';
                   4914:                 } elsif ($$tend<$now) {
                   4915:                     $$tstatus='will_not';
                   4916:                 }
                   4917:             }
                   4918:         }
                   4919:     }
                   4920: }
                   4921: 
1.1104    raeburn  4922: sub get_groups_roles {
                   4923:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4924:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4925:                   (ref($rolecodes) eq 'ARRAY') && 
                   4926:                   (ref($groups_roles) eq 'HASH')); 
                   4927:     if (keys(%{$cdom_courseroles}) > 0) {
                   4928:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4929:         if ($cdom ne '' && $cnum ne '') {
                   4930:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4931:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4932:                     my $crsrole = $1;
                   4933:                     my $crssec = $2;
                   4934:                     if ($crsrole =~ /^cr/) {
                   4935:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4936:                             push(@{$rolecodes},'cr');
                   4937:                         }
                   4938:                     } else {
                   4939:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4940:                             push(@{$rolecodes},$crsrole);
                   4941:                         }
                   4942:                     }
                   4943:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4944:                     if ($crssec ne '') {
                   4945:                         $rolekey .= "/$crssec";
                   4946:                     }
                   4947:                     $rolekey .= './';
                   4948:                     $groups_roles->{$rolekey} = $rolecodes;
                   4949:                 }
                   4950:             }
                   4951:         }
                   4952:     }
                   4953:     return;
                   4954: }
                   4955: 
                   4956: sub delete_env_groupprivs {
                   4957:     my ($where,$courseroles,$possroles) = @_;
                   4958:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4959:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4960:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4961:         %{$courseroles->{$udom}} =
                   4962:             &get_my_roles('','','userroles',['active'],
                   4963:                           $possroles,[$udom],1);
                   4964:     }
                   4965:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4966:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4967:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4968:             my $area = '/'.$cdom.'/'.$cnum;
                   4969:             my $privkey = "user.priv.$crsrole.$area";
                   4970:             if ($crssec ne '') {
                   4971:                 $privkey .= '/'.$crssec;
                   4972:             }
                   4973:             $privkey .= ".$area/$group";
                   4974:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4975:         }
                   4976:     }
                   4977:     return;
                   4978: }
                   4979: 
1.994     raeburn  4980: sub check_adhoc_privs {
1.1104    raeburn  4981:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4982:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4983:     if ($env{$cckey}) {
                   4984:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4985:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4986:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4987:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4988:         }
                   4989:     } else {
1.1088    raeburn  4990:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4991:     }
                   4992: }
                   4993: 
                   4994: sub set_adhoc_privileges {
                   4995: # role can be cc or ca
1.1088    raeburn  4996:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4997:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4998:     my $spec = $role.'.'.$area;
                   4999:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5000:                                   $env{'user.name'});
                   5001:     my %ccrole = ();
                   5002:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5003:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5004:     &appenv(\%userroles,[$role,'cm']);
                   5005:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5006:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5007:         &appenv( {'request.role'        => $spec,
                   5008:                   'request.role.domain' => $dcdom,
                   5009:                   'request.course.sec'  => ''
                   5010:                  }
                   5011:                );
                   5012:         my $tadv=0;
                   5013:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5014:         &appenv({'request.role.adv'    => $tadv});
                   5015:     }
1.994     raeburn  5016: }
                   5017: 
1.12      www      5018: # --------------------------------------------------------------- get interface
                   5019: 
                   5020: sub get {
1.131     albertel 5021:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5022:    my $items='';
1.800     albertel 5023:    foreach my $item (@$storearr) {
                   5024:        $items.=&escape($item).'&';
1.191     harris41 5025:    }
1.12      www      5026:    $items=~s/\&$//;
1.620     albertel 5027:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5028:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5029:    my $uhome=&homeserver($uname,$udomain);
                   5030: 
1.133     albertel 5031:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5032:    my @pairs=split(/\&/,$rep);
1.273     albertel 5033:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5034:      return @pairs;
                   5035:    }
1.15      www      5036:    my %returnhash=();
1.42      www      5037:    my $i=0;
1.800     albertel 5038:    foreach my $item (@$storearr) {
                   5039:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5040:       $i++;
1.191     harris41 5041:    }
1.15      www      5042:    return %returnhash;
1.27      www      5043: }
                   5044: 
                   5045: # --------------------------------------------------------------- del interface
                   5046: 
                   5047: sub del {
1.133     albertel 5048:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5049:    my $items='';
1.800     albertel 5050:    foreach my $item (@$storearr) {
                   5051:        $items.=&escape($item).'&';
1.191     harris41 5052:    }
1.984     neumanie 5053: 
1.27      www      5054:    $items=~s/\&$//;
1.620     albertel 5055:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5056:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5057:    my $uhome=&homeserver($uname,$udomain);
                   5058:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5059: }
                   5060: 
                   5061: # -------------------------------------------------------------- dump interface
                   5062: 
                   5063: sub dump {
1.1166    raeburn  5064:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5065:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5066:     if (!$uname) { $uname=$env{'user.name'}; }
                   5067:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5068: 
1.755     albertel 5069:     if ($regexp) {
                   5070: 	$regexp=&escape($regexp);
                   5071:     } else {
                   5072: 	$regexp='.';
                   5073:     }
1.1166    raeburn  5074:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5075:     my @pairs=split(/\&/,$rep);
                   5076:     my %returnhash=();
1.1098    foxr     5077:     if (!($rep =~ /^error/ )) {
                   5078: 	foreach my $item (@pairs) {
                   5079: 	    my ($key,$value)=split(/=/,$item,2);
                   5080: 	    $key = &unescape($key);
                   5081: 	    next if ($key =~ /^error: 2 /);
                   5082: 	    $returnhash{$key}=&thaw_unescape($value);
                   5083: 	}
1.755     albertel 5084:     }
                   5085:     return %returnhash;
1.407     www      5086: }
                   5087: 
1.1098    foxr     5088: 
1.717     albertel 5089: # --------------------------------------------------------- dumpstore interface
                   5090: 
                   5091: sub dumpstore {
                   5092:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5094:    if (!$uname) { $uname=$env{'user.name'}; }
                   5095:    my $uhome=&homeserver($uname,$udomain);
                   5096:    if ($regexp) {
                   5097:        $regexp=&escape($regexp);
                   5098:    } else {
                   5099:        $regexp='.';
                   5100:    }
                   5101:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5102:    my @pairs=split(/\&/,$rep);
                   5103:    my %returnhash=();
                   5104:    foreach my $item (@pairs) {
                   5105:        my ($key,$value)=split(/=/,$item,2);
                   5106:        next if ($key =~ /^error: 2 /);
                   5107:        $returnhash{$key}=&thaw_unescape($value);
                   5108:    }
                   5109:    return %returnhash;
1.717     albertel 5110: }
                   5111: 
1.407     www      5112: # -------------------------------------------------------------- keys interface
                   5113: 
                   5114: sub getkeys {
                   5115:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5117:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5118:    my $uhome=&homeserver($uname,$udomain);
                   5119:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5120:    my @keyarray=();
1.800     albertel 5121:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5122:       next if ($key =~ /^error: 2 /);
1.800     albertel 5123:       push(@keyarray,&unescape($key));
1.407     www      5124:    }
                   5125:    return @keyarray;
1.318     matthew  5126: }
                   5127: 
1.319     matthew  5128: # --------------------------------------------------------------- currentdump
                   5129: sub currentdump {
1.328     matthew  5130:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5131:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5132:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5133:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5134:    my $uhome = &homeserver($sname,$sdom);
                   5135:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5136:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5137:    #
1.318     matthew  5138:    my %returnhash=();
1.319     matthew  5139:    #
                   5140:    if ($rep eq "unknown_cmd") { 
                   5141:        # an old lond will not know currentdump
                   5142:        # Do a dump and make it look like a currentdump
1.822     albertel 5143:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5144:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5145:        my %hash = @tmp;
                   5146:        @tmp=();
1.424     matthew  5147:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5148:    } else {
                   5149:        my @pairs=split(/\&/,$rep);
1.800     albertel 5150:        foreach my $pair (@pairs) {
                   5151:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5152:            my ($symb,$param) = split(/:/,$key);
                   5153:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5154:                                                         &thaw_unescape($value);
1.319     matthew  5155:        }
1.191     harris41 5156:    }
1.12      www      5157:    return %returnhash;
1.424     matthew  5158: }
                   5159: 
                   5160: sub convert_dump_to_currentdump{
                   5161:     my %hash = %{shift()};
                   5162:     my %returnhash;
                   5163:     # Code ripped from lond, essentially.  The only difference
                   5164:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5165:     # we might run in to problems with parameter names =~ /^v\./
                   5166:     while (my ($key,$value) = each(%hash)) {
                   5167:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5168: 	$symb  = &unescape($symb);
                   5169: 	$param = &unescape($param);
1.424     matthew  5170:         next if ($v eq 'version' || $symb eq 'keys');
                   5171:         next if (exists($returnhash{$symb}) &&
                   5172:                  exists($returnhash{$symb}->{$param}) &&
                   5173:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5174:         $returnhash{$symb}->{$param}=$value;
                   5175:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5176:     }
                   5177:     #
                   5178:     # Remove all of the keys in the hashes which keep track of
                   5179:     # the version of the parameter.
                   5180:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5181:         # use a foreach because we are going to delete from the hash.
                   5182:         foreach my $key (keys(%$param_hash)) {
                   5183:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5184:         }
                   5185:     }
                   5186:     return \%returnhash;
1.12      www      5187: }
                   5188: 
1.627     albertel 5189: # ------------------------------------------------------ critical inc interface
                   5190: 
                   5191: sub cinc {
                   5192:     return &inc(@_,'critical');
                   5193: }
                   5194: 
1.449     matthew  5195: # --------------------------------------------------------------- inc interface
                   5196: 
                   5197: sub inc {
1.627     albertel 5198:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5199:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5200:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5201:     my $uhome=&homeserver($uname,$udomain);
                   5202:     my $items='';
                   5203:     if (! ref($store)) {
                   5204:         # got a single value, so use that instead
                   5205:         $items = &escape($store).'=&';
                   5206:     } elsif (ref($store) eq 'SCALAR') {
                   5207:         $items = &escape($$store).'=&';        
                   5208:     } elsif (ref($store) eq 'ARRAY') {
                   5209:         $items = join('=&',map {&escape($_);} @{$store});
                   5210:     } elsif (ref($store) eq 'HASH') {
                   5211:         while (my($key,$value) = each(%{$store})) {
                   5212:             $items.= &escape($key).'='.&escape($value).'&';
                   5213:         }
                   5214:     }
                   5215:     $items=~s/\&$//;
1.627     albertel 5216:     if ($critical) {
                   5217: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5218:     } else {
                   5219: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5220:     }
1.449     matthew  5221: }
                   5222: 
1.12      www      5223: # --------------------------------------------------------------- put interface
                   5224: 
                   5225: sub put {
1.134     albertel 5226:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5227:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5228:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5229:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5230:    my $items='';
1.800     albertel 5231:    foreach my $item (keys(%$storehash)) {
                   5232:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5233:    }
1.12      www      5234:    $items=~s/\&$//;
1.134     albertel 5235:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5236: }
                   5237: 
1.631     albertel 5238: # ------------------------------------------------------------ newput interface
                   5239: 
                   5240: sub newput {
                   5241:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5242:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5243:    if (!$uname) { $uname=$env{'user.name'}; }
                   5244:    my $uhome=&homeserver($uname,$udomain);
                   5245:    my $items='';
                   5246:    foreach my $key (keys(%$storehash)) {
                   5247:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5248:    }
                   5249:    $items=~s/\&$//;
                   5250:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5251: }
                   5252: 
                   5253: # ---------------------------------------------------------  putstore interface
                   5254: 
1.524     raeburn  5255: sub putstore {
1.715     albertel 5256:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5257:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5258:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5259:    my $uhome=&homeserver($uname,$udomain);
                   5260:    my $items='';
1.715     albertel 5261:    foreach my $key (keys(%$storehash)) {
                   5262:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5263:    }
1.715     albertel 5264:    $items=~s/\&$//;
1.716     albertel 5265:    my $esc_symb=&escape($symb);
                   5266:    my $esc_v=&escape($version);
1.715     albertel 5267:    my $reply =
1.716     albertel 5268:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5269: 	      $uhome);
                   5270:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5271:        # gfall back to way things use to be done
1.715     albertel 5272:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5273: 			    $uname);
1.524     raeburn  5274:    }
1.715     albertel 5275:    return $reply;
                   5276: }
                   5277: 
                   5278: sub old_putstore {
1.716     albertel 5279:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5280:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5281:     if (!$uname) { $uname=$env{'user.name'}; }
                   5282:     my $uhome=&homeserver($uname,$udomain);
                   5283:     my %newstorehash;
1.800     albertel 5284:     foreach my $item (keys(%$storehash)) {
                   5285: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5286: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5287:     }
                   5288:     my $items='';
                   5289:     my %allitems = ();
1.800     albertel 5290:     foreach my $item (keys(%newstorehash)) {
                   5291: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5292: 	    my $key = $1.':keys:'.$2;
                   5293: 	    $allitems{$key} .= $3.':';
                   5294: 	}
1.800     albertel 5295: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5296:     }
1.800     albertel 5297:     foreach my $item (keys(%allitems)) {
                   5298: 	$allitems{$item} =~ s/\:$//;
                   5299: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5300:     }
                   5301:     $items=~s/\&$//;
                   5302:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5303: }
                   5304: 
1.47      www      5305: # ------------------------------------------------------ critical put interface
                   5306: 
                   5307: sub cput {
1.134     albertel 5308:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5309:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5310:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5311:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5312:    my $items='';
1.800     albertel 5313:    foreach my $item (keys(%$storehash)) {
                   5314:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5315:    }
1.47      www      5316:    $items=~s/\&$//;
1.134     albertel 5317:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5318: }
                   5319: 
                   5320: # -------------------------------------------------------------- eget interface
                   5321: 
                   5322: sub eget {
1.133     albertel 5323:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5324:    my $items='';
1.800     albertel 5325:    foreach my $item (@$storearr) {
                   5326:        $items.=&escape($item).'&';
1.191     harris41 5327:    }
1.12      www      5328:    $items=~s/\&$//;
1.620     albertel 5329:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5330:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5331:    my $uhome=&homeserver($uname,$udomain);
                   5332:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5333:    my @pairs=split(/\&/,$rep);
                   5334:    my %returnhash=();
1.42      www      5335:    my $i=0;
1.800     albertel 5336:    foreach my $item (@$storearr) {
                   5337:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5338:       $i++;
1.191     harris41 5339:    }
1.12      www      5340:    return %returnhash;
                   5341: }
                   5342: 
1.667     albertel 5343: # ------------------------------------------------------------ tmpput interface
                   5344: sub tmpput {
1.802     raeburn  5345:     my ($storehash,$server,$context)=@_;
1.667     albertel 5346:     my $items='';
1.800     albertel 5347:     foreach my $item (keys(%$storehash)) {
                   5348: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5349:     }
                   5350:     $items=~s/\&$//;
1.802     raeburn  5351:     if (defined($context)) {
                   5352:         $items .= ':'.&escape($context);
                   5353:     }
1.667     albertel 5354:     return &reply("tmpput:$items",$server);
                   5355: }
                   5356: 
                   5357: # ------------------------------------------------------------ tmpget interface
                   5358: sub tmpget {
1.688     albertel 5359:     my ($token,$server)=@_;
                   5360:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5361:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5362:     my %returnhash;
                   5363:     foreach my $item (split(/\&/,$rep)) {
                   5364: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5365:         next if ($key =~ /^error: 2 /);
1.667     albertel 5366: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5367:     }
                   5368:     return %returnhash;
                   5369: }
                   5370: 
1.1113    raeburn  5371: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5372: sub tmpdel {
                   5373:     my ($token,$server)=@_;
                   5374:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5375:     return &reply("tmpdel:$token",$server);
                   5376: }
                   5377: 
1.765     albertel 5378: # -------------------------------------------------- portfolio access checking
                   5379: 
                   5380: sub portfolio_access {
1.766     albertel 5381:     my ($requrl) = @_;
1.765     albertel 5382:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5383:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5384:     if ($result) {
                   5385:         my %setters;
                   5386:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5387:             my ($startblock,$endblock) =
                   5388:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5389:             if ($startblock && $endblock) {
                   5390:                 return 'B';
                   5391:             }
                   5392:         } else {
                   5393:             my ($startblock,$endblock) =
                   5394:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5395:             if ($startblock && $endblock) {
                   5396:                 return 'B';
                   5397:             }
                   5398:         }
                   5399:     }
1.765     albertel 5400:     if ($result eq 'ok') {
1.766     albertel 5401:        return 'F';
1.765     albertel 5402:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5403:        return 'A';
1.765     albertel 5404:     }
1.766     albertel 5405:     return '';
1.765     albertel 5406: }
                   5407: 
                   5408: sub get_portfolio_access {
1.767     albertel 5409:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5410: 
                   5411:     if (!ref($access_hash)) {
                   5412: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5413: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5414: 						   $file_name);
                   5415: 	$access_hash = $access_controls{$file_name};
                   5416:     }
                   5417: 
1.765     albertel 5418:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5419:     my $now = time;
                   5420:     if (ref($access_hash) eq 'HASH') {
                   5421:         foreach my $key (keys(%{$access_hash})) {
                   5422:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5423:             if ($start > $now) {
                   5424:                 next;
                   5425:             }
                   5426:             if ($end && $end<$now) {
                   5427:                 next;
                   5428:             }
                   5429:             if ($scope eq 'public') {
                   5430:                 $public = $key;
                   5431:                 last;
                   5432:             } elsif ($scope eq 'guest') {
                   5433:                 $guest = $key;
                   5434:             } elsif ($scope eq 'domains') {
                   5435:                 push(@domains,$key);
                   5436:             } elsif ($scope eq 'users') {
                   5437:                 push(@users,$key);
                   5438:             } elsif ($scope eq 'course') {
                   5439:                 push(@courses,$key);
                   5440:             } elsif ($scope eq 'group') {
                   5441:                 push(@groups,$key);
                   5442:             }
                   5443:         }
                   5444:         if ($public) {
                   5445:             return 'ok';
                   5446:         }
                   5447:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5448:             if ($guest) {
                   5449:                 return $guest;
                   5450:             }
                   5451:         } else {
                   5452:             if (@domains > 0) {
                   5453:                 foreach my $domkey (@domains) {
                   5454:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5455:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5456:                             return 'ok';
                   5457:                         }
                   5458:                     }
                   5459:                 }
                   5460:             }
                   5461:             if (@users > 0) {
                   5462:                 foreach my $userkey (@users) {
1.865     raeburn  5463:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5464:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5465:                             if (ref($item) eq 'HASH') {
                   5466:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5467:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5468:                                     return 'ok';
                   5469:                                 }
                   5470:                             }
                   5471:                         }
                   5472:                     } 
1.765     albertel 5473:                 }
                   5474:             }
                   5475:             my %roleshash;
                   5476:             my @courses_and_groups = @courses;
                   5477:             push(@courses_and_groups,@groups); 
                   5478:             if (@courses_and_groups > 0) {
                   5479:                 my (%allgroups,%allroles); 
                   5480:                 my ($start,$end,$role,$sec,$group);
                   5481:                 foreach my $envkey (%env) {
1.1060    raeburn  5482:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5483:                         my $cid = $2.'_'.$3; 
                   5484:                         if ($1 eq 'gr') {
                   5485:                             $group = $4;
                   5486:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5487:                         } else {
                   5488:                             if ($4 eq '') {
                   5489:                                 $sec = 'none';
                   5490:                             } else {
                   5491:                                 $sec = $4;
                   5492:                             }
                   5493:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5494:                         }
1.811     albertel 5495:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5496:                         my $cid = $2.'_'.$3;
                   5497:                         if ($4 eq '') {
                   5498:                             $sec = 'none';
                   5499:                         } else {
                   5500:                             $sec = $4;
                   5501:                         }
                   5502:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5503:                     }
                   5504:                 }
                   5505:                 if (keys(%allroles) == 0) {
                   5506:                     return;
                   5507:                 }
                   5508:                 foreach my $key (@courses_and_groups) {
                   5509:                     my %content = %{$$access_hash{$key}};
                   5510:                     my $cnum = $content{'number'};
                   5511:                     my $cdom = $content{'domain'};
                   5512:                     my $cid = $cdom.'_'.$cnum;
                   5513:                     if (!exists($allroles{$cid})) {
                   5514:                         next;
                   5515:                     }    
                   5516:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5517:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5518:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5519:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5520:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5521:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5522:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5523:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5524:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5525:                                         if (grep/^all$/,@sections) {
                   5526:                                             return 'ok';
                   5527:                                         } else {
                   5528:                                             if (grep/^$sec$/,@sections) {
                   5529:                                                 return 'ok';
                   5530:                                             }
                   5531:                                         }
                   5532:                                     }
                   5533:                                 }
                   5534:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5535:                                     if (grep/^none$/,@groups) {
                   5536:                                         return 'ok';
                   5537:                                     }
                   5538:                                 } else {
                   5539:                                     if (grep/^all$/,@groups) {
                   5540:                                         return 'ok';
                   5541:                                     } 
                   5542:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5543:                                         if (grep/^$group$/,@groups) {
                   5544:                                             return 'ok';
                   5545:                                         }
                   5546:                                     }
                   5547:                                 } 
                   5548:                             }
                   5549:                         }
                   5550:                     }
                   5551:                 }
                   5552:             }
                   5553:             if ($guest) {
                   5554:                 return $guest;
                   5555:             }
                   5556:         }
                   5557:     }
                   5558:     return;
                   5559: }
                   5560: 
                   5561: sub course_group_datechecker {
                   5562:     my ($dates,$now,$status) = @_;
                   5563:     my ($start,$end) = split(/\./,$dates);
                   5564:     if (!$start && !$end) {
                   5565:         return 'ok';
                   5566:     }
                   5567:     if (grep/^active$/,@{$status}) {
                   5568:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5569:             return 'ok';
                   5570:         }
                   5571:     }
                   5572:     if (grep/^previous$/,@{$status}) {
                   5573:         if ($end > $now ) {
                   5574:             return 'ok';
                   5575:         }
                   5576:     }
                   5577:     if (grep/^future$/,@{$status}) {
                   5578:         if ($start > $now) {
                   5579:             return 'ok';
                   5580:         }
                   5581:     }
                   5582:     return; 
                   5583: }
                   5584: 
                   5585: sub parse_portfolio_url {
                   5586:     my ($url) = @_;
                   5587: 
                   5588:     my ($type,$udom,$unum,$group,$file_name);
                   5589:     
1.823     albertel 5590:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5591: 	$type = 1;
                   5592:         $udom = $1;
                   5593:         $unum = $2;
                   5594:         $file_name = $3;
1.823     albertel 5595:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5596: 	$type = 2;
                   5597:         $udom = $1;
                   5598:         $unum = $2;
                   5599:         $group = $3;
                   5600:         $file_name = $3.'/'.$4;
                   5601:     }
                   5602:     if (wantarray) {
                   5603: 	return ($type,$udom,$unum,$file_name,$group);
                   5604:     }
                   5605:     return $type;
                   5606: }
                   5607: 
                   5608: sub is_portfolio_url {
                   5609:     my ($url) = @_;
                   5610:     return scalar(&parse_portfolio_url($url));
                   5611: }
                   5612: 
1.798     raeburn  5613: sub is_portfolio_file {
                   5614:     my ($file) = @_;
1.820     raeburn  5615:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5616:         return 1;
                   5617:     }
                   5618:     return;
                   5619: }
                   5620: 
1.976     raeburn  5621: sub usertools_access {
1.1084    raeburn  5622:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5623:     my ($access,%tools);
                   5624:     if ($context eq '') {
                   5625:         $context = 'tools';
                   5626:     }
                   5627:     if ($context eq 'requestcourses') {
                   5628:         %tools = (
                   5629:                       official   => 1,
                   5630:                       unofficial => 1,
1.1006    raeburn  5631:                       community  => 1,
1.985     raeburn  5632:                  );
                   5633:     } else {
                   5634:         %tools = (
                   5635:                       aboutme   => 1,
                   5636:                       blog      => 1,
                   5637:                       portfolio => 1,
                   5638:                  );
                   5639:     }
1.976     raeburn  5640:     return if (!defined($tools{$tool}));
                   5641: 
                   5642:     if ((!defined($udom)) || (!defined($uname))) {
                   5643:         $udom = $env{'user.domain'};
                   5644:         $uname = $env{'user.name'};
                   5645:     }
                   5646: 
1.978     raeburn  5647:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5648:         if ($action ne 'reload') {
1.985     raeburn  5649:             if ($context eq 'requestcourses') {
                   5650:                 return $env{'environment.canrequest.'.$tool};
                   5651:             } else {
                   5652:                 return $env{'environment.availabletools.'.$tool};
                   5653:             }
                   5654:         }
1.976     raeburn  5655:     }
                   5656: 
                   5657:     my ($toolstatus,$inststatus);
                   5658: 
1.985     raeburn  5659:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5660:          ($action ne 'reload')) {
                   5661:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5662:         $inststatus = $env{'environment.inststatus'};
                   5663:     } else {
1.1084    raeburn  5664:         if (ref($userenvref) eq 'HASH') {
                   5665:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5666:             $inststatus = $userenvref->{'inststatus'};
                   5667:         } else {
                   5668:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5669:             $toolstatus = $userenv{$context.'.'.$tool};
                   5670:             $inststatus = $userenv{'inststatus'};
                   5671:         }
1.976     raeburn  5672:     }
                   5673: 
                   5674:     if ($toolstatus ne '') {
                   5675:         if ($toolstatus) {
                   5676:             $access = 1;
                   5677:         } else {
                   5678:             $access = 0;
                   5679:         }
                   5680:         return $access;
                   5681:     }
                   5682: 
1.1084    raeburn  5683:     my ($is_adv,%domdef);
                   5684:     if (ref($is_advref) eq 'HASH') {
                   5685:         $is_adv = $is_advref->{'is_adv'};
                   5686:     } else {
                   5687:         $is_adv = &is_advanced_user($udom,$uname);
                   5688:     }
                   5689:     if (ref($domdefref) eq 'HASH') {
                   5690:         %domdef = %{$domdefref};
                   5691:     } else {
                   5692:         %domdef = &get_domain_defaults($udom);
                   5693:     }
1.976     raeburn  5694:     if (ref($domdef{$tool}) eq 'HASH') {
                   5695:         if ($is_adv) {
                   5696:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5697:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5698:                     $access = 1;
                   5699:                 } else {
                   5700:                     $access = 0;
                   5701:                 }
                   5702:                 return $access;
                   5703:             }
                   5704:         }
                   5705:         if ($inststatus ne '') {
                   5706:             my ($hasaccess,$hasnoaccess);
                   5707:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5708:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5709:                     if ($domdef{$tool}{$affiliation}) {
                   5710:                         $hasaccess = 1;
                   5711:                     } else {
                   5712:                         $hasnoaccess = 1;
                   5713:                     }
                   5714:                 }
                   5715:             }
                   5716:             if ($hasaccess || $hasnoaccess) {
                   5717:                 if ($hasaccess) {
                   5718:                     $access = 1;
                   5719:                 } elsif ($hasnoaccess) {
                   5720:                     $access = 0; 
                   5721:                 }
                   5722:                 return $access;
                   5723:             }
                   5724:         } else {
                   5725:             if ($domdef{$tool}{'default'} ne '') {
                   5726:                 if ($domdef{$tool}{'default'}) {
                   5727:                     $access = 1;
                   5728:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5729:                     $access = 0;
                   5730:                 }
                   5731:                 return $access;
                   5732:             }
                   5733:         }
                   5734:     } else {
1.985     raeburn  5735:         if ($context eq 'tools') {
                   5736:             $access = 1;
                   5737:         } else {
                   5738:             $access = 0;
                   5739:         }
1.976     raeburn  5740:         return $access;
                   5741:     }
                   5742: }
                   5743: 
1.1050    raeburn  5744: sub is_course_owner {
                   5745:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5746:     if (($udom eq '') || ($uname eq '')) {
                   5747:         $udom = $env{'user.domain'};
                   5748:         $uname = $env{'user.name'};
                   5749:     }
                   5750:     unless (($udom eq '') || ($uname eq '')) {
                   5751:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5752:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5753:                 return 1;
                   5754:             } else {
                   5755:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5756:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5757:                     return 1;
                   5758:                 }
                   5759:             }
                   5760:         }
                   5761:     }
                   5762:     return;
                   5763: }
                   5764: 
1.976     raeburn  5765: sub is_advanced_user {
                   5766:     my ($udom,$uname) = @_;
1.1085    raeburn  5767:     if ($udom ne '' && $uname ne '') {
                   5768:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5769:             if (wantarray) {
                   5770:                 return ($env{'user.adv'},$env{'user.author'});
                   5771:             } else {
                   5772:                 return $env{'user.adv'};
                   5773:             }
1.1085    raeburn  5774:         }
                   5775:     }
1.976     raeburn  5776:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5777:     my %allroles;
1.1128    raeburn  5778:     my ($is_adv,$is_author);
1.976     raeburn  5779:     foreach my $role (keys(%roleshash)) {
                   5780:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5781:         my $area = '/'.$tdomain.'/'.$trest;
                   5782:         if ($sec ne '') {
                   5783:             $area .= '/'.$sec;
                   5784:         }
                   5785:         if (($area ne '') && ($trole ne '')) {
                   5786:             my $spec=$trole.'.'.$area;
                   5787:             if ($trole =~ /^cr\//) {
                   5788:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5789:             } elsif ($trole ne 'gr') {
                   5790:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5791:             }
1.1128    raeburn  5792:             if ($trole eq 'au') {
                   5793:                 $is_author = 1;
                   5794:             }
1.976     raeburn  5795:         }
                   5796:     }
                   5797:     foreach my $role (keys(%allroles)) {
                   5798:         last if ($is_adv);
                   5799:         foreach my $item (split(/:/,$allroles{$role})) {
                   5800:             if ($item ne '') {
                   5801:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5802:                 if ($privilege eq 'adv') {
                   5803:                     $is_adv = 1;
                   5804:                     last;
                   5805:                 }
                   5806:             }
                   5807:         }
                   5808:     }
1.1128    raeburn  5809:     if (wantarray) {
                   5810:         return ($is_adv,$is_author);
                   5811:     }
1.976     raeburn  5812:     return $is_adv;
                   5813: }
1.798     raeburn  5814: 
1.1035    raeburn  5815: sub check_can_request {
1.1036    raeburn  5816:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5817:     my $canreq = 0;
                   5818:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5819:     my @options = ('approval','validate','autolimit');
                   5820:     my $optregex = join('|',@options);
                   5821:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5822:         foreach my $type (@{$types}) {
                   5823:             if (&usertools_access($env{'user.name'},
                   5824:                                   $env{'user.domain'},
                   5825:                                   $type,undef,'requestcourses')) {
                   5826:                 $canreq ++;
1.1036    raeburn  5827:                 if (ref($request_domains) eq 'HASH') {
                   5828:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5829:                 }
1.1035    raeburn  5830:                 if ($dom eq $env{'user.domain'}) {
                   5831:                     $can_request->{$type} = 1;
                   5832:                 }
                   5833:             }
                   5834:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5835:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5836:                 if (@curr > 0) {
1.1036    raeburn  5837:                     foreach my $item (@curr) {
                   5838:                         if (ref($request_domains) eq 'HASH') {
                   5839:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5840:                             if ($otherdom ne '') {
                   5841:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5842:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5843:                                         push(@{$request_domains->{$type}},$otherdom);
                   5844:                                     }
                   5845:                                 } else {
                   5846:                                     push(@{$request_domains->{$type}},$otherdom);
                   5847:                                 }
                   5848:                             }
                   5849:                         }
                   5850:                     }
                   5851:                     unless($dom eq $env{'user.domain'}) {
                   5852:                         $canreq ++;
1.1035    raeburn  5853:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5854:                             $can_request->{$type} = 1;
                   5855:                         }
                   5856:                     }
                   5857:                 }
                   5858:             }
                   5859:         }
                   5860:     }
                   5861:     return $canreq;
                   5862: }
                   5863: 
1.341     www      5864: # ---------------------------------------------- Custom access rule evaluation
                   5865: 
                   5866: sub customaccess {
                   5867:     my ($priv,$uri)=@_;
1.807     albertel 5868:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5869:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5870:     $udom = &LONCAPA::clean_domain($udom);
                   5871:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5872:     my $access=0;
1.800     albertel 5873:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5874: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5875: 	if ($type eq 'user') {
                   5876: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5877: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5878: 		if ($tdom) {
                   5879: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5880: 		}
1.896     albertel 5881: 		if ($tuname) {
                   5882: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5883: 		}
                   5884: 		$access=($effect eq 'allow');
                   5885: 		last;
                   5886: 	    }
                   5887: 	} else {
                   5888: 	    if ($role) {
                   5889: 		if ($role ne $urole) { next; }
                   5890: 	    }
                   5891: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5892: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5893: 		if ($tdom) {
                   5894: 		    if ($tdom ne $udom) { next; }
                   5895: 		}
                   5896: 		if ($tcrs) {
                   5897: 		    if ($tcrs ne $ucrs) { next; }
                   5898: 		}
                   5899: 		if ($tsec) {
                   5900: 		    if ($tsec ne $usec) { next; }
                   5901: 		}
                   5902: 		$access=($effect eq 'allow');
                   5903: 		last;
                   5904: 	    }
                   5905: 	    if ($realm eq '' && $role eq '') {
                   5906: 		$access=($effect eq 'allow');
                   5907: 	    }
1.402     bowersj2 5908: 	}
1.341     www      5909:     }
                   5910:     return $access;
                   5911: }
                   5912: 
1.103     harris41 5913: # ------------------------------------------------- Check for a user privilege
1.12      www      5914: 
                   5915: sub allowed {
1.810     raeburn  5916:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5917:     my $ver_orguri=$uri;
1.439     www      5918:     $uri=&deversion($uri);
1.152     www      5919:     my $orguri=$uri;
1.52      www      5920:     $uri=&declutter($uri);
1.809     raeburn  5921: 
1.810     raeburn  5922:     if ($priv eq 'evb') {
                   5923: # Evade communication block restrictions for specified role in a course
                   5924:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5925:             return $1;
                   5926:         } else {
                   5927:             return;
                   5928:         }
                   5929:     }
                   5930: 
1.620     albertel 5931:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5932: # Free bre access to adm and meta resources
1.775     albertel 5933:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5934: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5935: 	&& ($priv eq 'bre')) {
1.14      www      5936: 	return 'F';
1.159     www      5937:     }
                   5938: 
1.545     banghart 5939: # Free bre access to user's own portfolio contents
1.714     raeburn  5940:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5941:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5942: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5943:         my %setters;
                   5944:         my ($startblock,$endblock) = 
                   5945:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5946:         if ($startblock && $endblock) {
                   5947:             return 'B';
                   5948:         } else {
                   5949:             return 'F';
                   5950:         }
1.545     banghart 5951:     }
                   5952: 
1.762     raeburn  5953: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5954:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5955:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5956:         if (exists($env{'request.course.id'})) {
                   5957:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5958:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5959:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5960:                 my $courseprivid=$env{'request.course.id'};
                   5961:                 $courseprivid=~s/\_/\//;
                   5962:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5963:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5964:                     return $1; 
1.762     raeburn  5965:                 } else {
                   5966:                     if ($env{'request.course.sec'}) {
                   5967:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5968:                     }
                   5969:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5970:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5971:                         return $2;
                   5972:                     }
1.714     raeburn  5973:                 }
                   5974:             }
                   5975:         }
                   5976:     }
                   5977: 
1.159     www      5978: # Free bre to public access
                   5979: 
                   5980:     if ($priv eq 'bre') {
1.238     www      5981:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5982: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5983:            return 'F'; 
                   5984:         }
1.238     www      5985:         if ($copyright eq 'priv') {
                   5986:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5987: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5988: 		return '';
                   5989:             }
                   5990:         }
                   5991:         if ($copyright eq 'domain') {
                   5992:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5993: 	    unless (($env{'user.domain'} eq $1) ||
                   5994:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5995: 		return '';
                   5996:             }
1.262     matthew  5997:         }
1.620     albertel 5998:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5999:             # Library role, so allow browsing of resources in this domain.
                   6000:             return 'F';
1.238     www      6001:         }
1.341     www      6002:         if ($copyright eq 'custom') {
                   6003: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6004:         }
1.14      www      6005:     }
1.264     matthew  6006:     # Domain coordinator is trying to create a course
1.620     albertel 6007:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6008:         # uri is the requested domain in this case.
                   6009:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6010:         # a role of dc for the domain in question.
1.620     albertel 6011:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6012:     }
1.29      www      6013: 
1.52      www      6014:     my $thisallowed='';
                   6015:     my $statecond=0;
                   6016:     my $courseprivid='';
                   6017: 
1.1039    raeburn  6018:     my $ownaccess;
1.1043    raeburn  6019:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6020:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6021:         if ($uri eq '') {
                   6022:             $ownaccess = 1;
                   6023:         } else {
                   6024:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6025:                 my $udom = $env{'user.domain'};
                   6026:                 my $uname = $env{'user.name'};
                   6027:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6028:                     $ownaccess = 1;
1.1040    raeburn  6029:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6030:                     unless ($uri =~ m{\.\./}) {
                   6031:                         $ownaccess = 1;
                   6032:                     }
                   6033:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6034:                     my $now = time;
                   6035:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6036:                         my $adom = $1;
                   6037:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6038:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6039:                                 my ($start,$end) = split('.',$env{$key});
                   6040:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6041:                                     $ownaccess = 1;
                   6042:                                     last;
                   6043:                                 }
                   6044:                             }
                   6045:                         }
                   6046:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6047:                         my $adom = $1;
                   6048:                         my $aname = $2;
1.1042    raeburn  6049:                         foreach my $role ('ca','aa') { 
                   6050:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6051:                                 my ($start,$end) =
                   6052:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6053:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6054:                                     $ownaccess = 1;
                   6055:                                     last;
                   6056:                                 }
1.1039    raeburn  6057:                             }
                   6058:                         }
                   6059:                     }
                   6060:                 }
                   6061:             }
                   6062:         }
                   6063:     }
                   6064: 
1.52      www      6065: # Course
                   6066: 
1.620     albertel 6067:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6068:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6069:             $thisallowed.=$1;
                   6070:         }
1.52      www      6071:     }
1.29      www      6072: 
1.52      www      6073: # Domain
                   6074: 
1.620     albertel 6075:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6076:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6077:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6078:             $thisallowed.=$1;
                   6079:         }
1.12      www      6080:     }
1.52      www      6081: 
1.1141    raeburn  6082: # User who is not author or co-author might still be able to edit
                   6083: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6084:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6085:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6086:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6087:             $thisallowed.=$1;
                   6088:         }
                   6089:     }
                   6090: 
1.52      www      6091: # Course: uri itself is a course
1.66      www      6092:     my $courseuri=$uri;
                   6093:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6094:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6095: 
1.620     albertel 6096:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6097:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6098:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6099:             $thisallowed.=$1;
                   6100:         }
1.12      www      6101:     }
1.29      www      6102: 
1.665     albertel 6103: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6104: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6105:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6106: 	$thisallowed='';
1.671     raeburn  6107:         my ($match)=&is_on_map($uri);
                   6108:         if ($match) {
                   6109:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6110:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6111:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6112:                 if (@blockers > 0) {
                   6113:                     $thisallowed = 'B';
                   6114:                 } else {
                   6115:                     $thisallowed.=$1;
                   6116:                 }
1.671     raeburn  6117:             }
                   6118:         } else {
1.705     albertel 6119:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6120:             if ($refuri) {
                   6121:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6122:                     $thisallowed='F';
1.671     raeburn  6123:                 } else {
                   6124:                     $refuri=&declutter($refuri);
                   6125:                     my ($match) = &is_on_map($refuri);
                   6126:                     if ($match) {
1.1162    raeburn  6127:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6128:                         if (@blockers > 0) {
                   6129:                             $thisallowed = 'B';
                   6130:                         } else {
                   6131:                             $thisallowed='F';
                   6132:                         }
1.671     raeburn  6133:                     }
1.669     raeburn  6134:                 }
1.671     raeburn  6135:             }
                   6136:         }
1.314     www      6137:     }
1.492     albertel 6138: 
1.766     albertel 6139:     if ($priv eq 'bre'
                   6140: 	&& $thisallowed ne 'F' 
                   6141: 	&& $thisallowed ne '2'
                   6142: 	&& &is_portfolio_url($uri)) {
                   6143: 	$thisallowed = &portfolio_access($uri);
                   6144:     }
                   6145:     
1.52      www      6146: # Full access at system, domain or course-wide level? Exit.
1.29      www      6147:     if ($thisallowed=~/F/) {
                   6148: 	return 'F';
                   6149:     }
                   6150: 
1.52      www      6151: # If this is generating or modifying users, exit with special codes
1.29      www      6152: 
1.643     www      6153:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6154: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6155: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6156: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6157: 	    unless ($auname) { return $thisallowed; }
                   6158: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6159: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6160: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6161: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6162: 	}
1.52      www      6163: 	return $thisallowed;
                   6164:     }
                   6165: #
1.103     harris41 6166: # Gathered so far: system, domain and course wide privileges
1.52      www      6167: #
                   6168: # Course: See if uri or referer is an individual resource that is part of 
                   6169: # the course
                   6170: 
1.620     albertel 6171:     if ($env{'request.course.id'}) {
1.232     www      6172: 
1.620     albertel 6173:        $courseprivid=$env{'request.course.id'};
                   6174:        if ($env{'request.course.sec'}) {
                   6175:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6176:        }
                   6177:        $courseprivid=~s/\_/\//;
                   6178:        my $checkreferer=1;
1.232     www      6179:        my ($match,$cond)=&is_on_map($uri);
                   6180:        if ($match) {
                   6181:            $statecond=$cond;
1.620     albertel 6182:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6183:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6184:                my $value = $1;
                   6185:                if ($priv eq 'bre') {
                   6186:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6187:                    if (@blockers > 0) {
                   6188:                        $thisallowed = 'B';
                   6189:                    } else {
                   6190:                        $thisallowed.=$value;
                   6191:                    }
                   6192:                } else {
                   6193:                    $thisallowed.=$value;
                   6194:                }
1.52      www      6195:                $checkreferer=0;
                   6196:            }
1.29      www      6197:        }
1.83      www      6198:        
1.148     www      6199:        if ($checkreferer) {
1.620     albertel 6200: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6201:             unless ($refuri) {
1.800     albertel 6202:                 foreach my $key (keys(%env)) {
                   6203: 		    if ($key=~/^httpref\..*\*/) {
                   6204: 			my $pattern=$key;
1.156     www      6205:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6206:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6207:                         $pattern=~s/\//\\\//g;
1.152     www      6208:                         if ($orguri=~/$pattern/) {
1.800     albertel 6209: 			    $refuri=$env{$key};
1.148     www      6210:                         }
                   6211:                     }
1.191     harris41 6212:                 }
1.148     www      6213:             }
1.232     www      6214: 
1.148     www      6215:          if ($refuri) { 
1.152     www      6216: 	  $refuri=&declutter($refuri);
1.232     www      6217:           my ($match,$cond)=&is_on_map($refuri);
                   6218:             if ($match) {
                   6219:               my $refstatecond=$cond;
1.620     albertel 6220:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6221:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6222:                   my $value = $1;
                   6223:                   if ($priv eq 'bre') {
                   6224:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6225:                       if (@blockers > 0) {
                   6226:                           $thisallowed = 'B';
                   6227:                       } else {
                   6228:                           $thisallowed.=$value;
                   6229:                       }
                   6230:                   } else {
                   6231:                       $thisallowed.=$value;
                   6232:                   }
1.53      www      6233:                   $uri=$refuri;
                   6234:                   $statecond=$refstatecond;
1.52      www      6235:               }
                   6236:           }
1.148     www      6237:         }
1.29      www      6238:        }
1.52      www      6239:    }
1.29      www      6240: 
1.52      www      6241: #
1.103     harris41 6242: # Gathered now: all privileges that could apply, and condition number
1.52      www      6243: # 
                   6244: #
                   6245: # Full or no access?
                   6246: #
1.29      www      6247: 
1.52      www      6248:     if ($thisallowed=~/F/) {
                   6249: 	return 'F';
                   6250:     }
1.29      www      6251: 
1.52      www      6252:     unless ($thisallowed) {
                   6253:         return '';
                   6254:     }
1.29      www      6255: 
1.52      www      6256: # Restrictions exist, deal with them
                   6257: #
                   6258: #   C:according to course preferences
                   6259: #   R:according to resource settings
                   6260: #   L:unless locked
                   6261: #   X:according to user session state
                   6262: #
                   6263: 
                   6264: # Possibly locked functionality, check all courses
1.54      www      6265: # Locks might take effect only after 10 minutes cache expiration for other
                   6266: # courses, and 2 minutes for current course
1.52      www      6267: 
                   6268:     my $envkey;
                   6269:     if ($thisallowed=~/L/) {
1.1000    raeburn  6270:         foreach $envkey (keys(%env)) {
1.54      www      6271:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6272:                my $courseid=$2;
                   6273:                my $roleid=$1.'.'.$2;
1.92      www      6274:                $courseid=~s/^\///;
1.54      www      6275:                my $expiretime=600;
1.620     albertel 6276:                if ($env{'request.role'} eq $roleid) {
1.54      www      6277: 		  $expiretime=120;
                   6278:                }
                   6279: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6280:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6281:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6282: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6283:                }
1.620     albertel 6284:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6285:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6286: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6287:                        &log($env{'user.domain'},$env{'user.name'},
                   6288:                             $env{'user.home'},
1.57      www      6289:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6290:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6291:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6292: 		       return '';
                   6293:                    }
                   6294:                }
1.620     albertel 6295:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6296:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6297: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6298:                        &log($env{'user.domain'},$env{'user.name'},
                   6299:                             $env{'user.home'},
1.57      www      6300:                             'Locked by priv: '.$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:                }
                   6306: 	   }
1.29      www      6307:        }
1.52      www      6308:     }
                   6309:    
                   6310: #
                   6311: # Rest of the restrictions depend on selected course
                   6312: #
                   6313: 
1.620     albertel 6314:     unless ($env{'request.course.id'}) {
1.766     albertel 6315: 	if ($thisallowed eq 'A') {
                   6316: 	    return 'A';
1.814     raeburn  6317:         } elsif ($thisallowed eq 'B') {
                   6318:             return 'B';
1.766     albertel 6319: 	} else {
                   6320: 	    return '1';
                   6321: 	}
1.52      www      6322:     }
1.29      www      6323: 
1.52      www      6324: #
                   6325: # Now user is definitely in a course
                   6326: #
1.53      www      6327: 
                   6328: 
                   6329: # Course preferences
                   6330: 
                   6331:    if ($thisallowed=~/C/) {
1.620     albertel 6332:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6333:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6334:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6335: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6336: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6337: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6338: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6339: 			$env{'request.course.id'});
                   6340: 	   }
1.237     www      6341:            return '';
                   6342:        }
                   6343: 
1.620     albertel 6344:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6345: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6346: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6347: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6348: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6349: 			$env{'request.course.id'});
                   6350: 	   }
1.54      www      6351:            return '';
                   6352:        }
1.53      www      6353:    }
                   6354: 
                   6355: # Resource preferences
                   6356: 
                   6357:    if ($thisallowed=~/R/) {
1.620     albertel 6358:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6359:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6360: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6361: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6362: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6363: 	   }
                   6364: 	   return '';
1.54      www      6365:        }
1.53      www      6366:    }
1.30      www      6367: 
1.246     www      6368: # Restricted by state or randomout?
1.30      www      6369: 
1.52      www      6370:    if ($thisallowed=~/X/) {
1.620     albertel 6371:       if ($env{'acc.randomout'}) {
1.579     albertel 6372: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6373:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6374:             return ''; 
                   6375:          }
1.247     www      6376:       }
                   6377:       if (&condval($statecond)) {
1.52      www      6378: 	 return '2';
                   6379:       } else {
                   6380:          return '';
                   6381:       }
                   6382:    }
1.30      www      6383: 
1.766     albertel 6384:     if ($thisallowed eq 'A') {
                   6385: 	return 'A';
1.814     raeburn  6386:     } elsif ($thisallowed eq 'B') {
                   6387:         return 'B';
1.766     albertel 6388:     }
1.52      www      6389:    return 'F';
1.232     www      6390: }
1.1162    raeburn  6391: 
                   6392: sub get_comm_blocks {
                   6393:     my ($cdom,$cnum) = @_;
                   6394:     if ($cdom eq '' || $cnum eq '') {
                   6395:         return unless ($env{'request.course.id'});
                   6396:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6397:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6398:     }
                   6399:     my %commblocks;
                   6400:     my $hashid=$cdom.'_'.$cnum;
                   6401:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6402:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6403:         %commblocks = %{$blocksref};
                   6404:     } else {
                   6405:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6406:         my $cachetime = 600;
                   6407:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6408:     }
                   6409:     return %commblocks;
                   6410: }
                   6411: 
                   6412: sub has_comm_blocking {
                   6413:     my ($priv,$symb,$uri,$blocks) = @_;
                   6414:     return unless ($env{'request.course.id'});
                   6415:     return unless ($priv eq 'bre');
                   6416:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6417:     my %commblocks;
                   6418:     if (ref($blocks) eq 'HASH') {
                   6419:         %commblocks = %{$blocks};
                   6420:     } else {
                   6421:         %commblocks = &get_comm_blocks();
                   6422:     }
                   6423:     return unless (keys(%commblocks) > 0);
                   6424:     if (!$symb) { $symb=&symbread($uri,1); }
                   6425:     my ($map,$resid,undef)=&decode_symb($symb);
                   6426:     my %tocheck = (
                   6427:                     maps      => $map,
                   6428:                     resources => $symb,
                   6429:                   );
                   6430:     my @blockers;
                   6431:     my $now = time;
1.1163    raeburn  6432:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6433:     foreach my $block (keys(%commblocks)) {
                   6434:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6435:             my ($start,$end) = ($1,$2);
                   6436:             if ($start <= $now && $end >= $now) {
                   6437:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6438:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6439:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6440:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6441:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6442:                                     push(@blockers,$block);
                   6443:                                 }
                   6444:                             }
                   6445:                         }
                   6446:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6447:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6448:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6449:                                     push(@blockers,$block);
                   6450:                                 }
                   6451:                             }
                   6452:                         }
                   6453:                     }
                   6454:                 }
                   6455:             }
                   6456:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6457:             my $item = $1;
1.1163    raeburn  6458:             my @to_test;
1.1162    raeburn  6459:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6460:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6461:                     my $check_interval;
                   6462:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6463:                         my @interval;
                   6464:                         my $type = 'map';
                   6465:                         if ($item eq 'course') {
                   6466:                             $type = 'course';
                   6467:                             @interval=&EXT("resource.0.interval");
                   6468:                         } else {
                   6469:                             if ($item =~ /___\d+___/) {
                   6470:                                 $type = 'resource';
                   6471:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6472:                                 if (ref($navmap)) {                        
                   6473:                                     my $res = $navmap->getBySymb($item); 
                   6474:                                     push(@to_test,$res);
                   6475:                                 }
1.1162    raeburn  6476:                             } else {
                   6477:                                 my $mapsymb = &symbread($item,1);
                   6478:                                 if ($mapsymb) {
                   6479:                                     if (ref($navmap)) {
                   6480:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6481:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6482:                                         foreach my $res (@to_test) {
1.1162    raeburn  6483:                                             my $symb = $res->symb();
                   6484:                                             next if ($symb eq $mapsymb);
                   6485:                                             if ($symb ne '') {
                   6486:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6487:                                                 last;
                   6488:                                             }
                   6489:                                         }
                   6490:                                     }
                   6491:                                 }
                   6492:                             }
                   6493:                         }
                   6494:                         if ($interval[0] =~ /\d+/) {
                   6495:                             my $first_access;
                   6496:                             if ($type eq 'resource') {
                   6497:                                 $first_access=&get_first_access($interval[1],$item);
                   6498:                             } elsif ($type eq 'map') {
                   6499:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6500:                             } else {
                   6501:                                 $first_access=&get_first_access($interval[1]);
                   6502:                             }
                   6503:                             if ($first_access) {
                   6504:                                 my $timesup = $first_access+$interval[0];
                   6505:                                 if ($timesup > $now) {
1.1163    raeburn  6506:                                     foreach my $res (@to_test) {
                   6507:                                         if ($res->is_problem()) {
                   6508:                                             if ($res->completable()) {
                   6509:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6510:                                                     push(@blockers,$block);
                   6511:                                                 }
                   6512:                                                 last;
                   6513:                                             }
                   6514:                                         }
1.1162    raeburn  6515:                                     }
                   6516:                                 }
                   6517:                             }
                   6518:                         }
                   6519:                     }
                   6520:                 }
                   6521:             }
                   6522:         }
                   6523:     }
                   6524:     return @blockers;
                   6525: }
                   6526: 
                   6527: sub check_docs_block {
                   6528:     my ($docsblock,$tocheck) =@_;
                   6529:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6530:         return;
                   6531:     }
                   6532:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6533:         if ($tocheck->{'maps'}) {
                   6534:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6535:                 return 1;
                   6536:             }
                   6537:         }
                   6538:     }
                   6539:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6540:         if ($tocheck->{'resources'}) {
                   6541:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6542:                 return 1;
                   6543:             }
                   6544:         }
                   6545:     }
                   6546:     return;
                   6547: }
                   6548: 
1.1133    foxr     6549: #
                   6550: #   Removes the versino from a URI and
                   6551: #   splits it in to its filename and path to the filename.
                   6552: #   Seems like File::Basename could have done this more clearly.
                   6553: #   Parameters:
                   6554: #      $uri   - input URI
                   6555: #   Returns:
                   6556: #     Two element list consisting of 
                   6557: #     $pathname  - the URI up to and excluding the trailing /
                   6558: #     $filename  - The part of the URI following the last /
                   6559: #  NOTE:
                   6560: #    Another realization of this is simply:
                   6561: #    use File::Basename;
                   6562: #    ...
                   6563: #    $uri = shift;
                   6564: #    $filename = basename($uri);
                   6565: #    $path     = dirname($uri);
                   6566: #    return ($filename, $path);
                   6567: #
                   6568: #     The implementation below is probably faster however.
                   6569: #
1.710     albertel 6570: sub split_uri_for_cond {
                   6571:     my $uri=&deversion(&declutter(shift));
                   6572:     my @uriparts=split(/\//,$uri);
                   6573:     my $filename=pop(@uriparts);
                   6574:     my $pathname=join('/',@uriparts);
                   6575:     return ($pathname,$filename);
                   6576: }
1.232     www      6577: # --------------------------------------------------- Is a resource on the map?
                   6578: 
                   6579: sub is_on_map {
1.710     albertel 6580:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6581:     #Trying to find the conditional for the file
1.620     albertel 6582:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6583: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6584:     if ($match) {
1.289     bowersj2 6585: 	return (1,$1);
                   6586:     } else {
1.434     www      6587: 	return (0,0);
1.289     bowersj2 6588:     }
1.12      www      6589: }
                   6590: 
1.427     www      6591: # --------------------------------------------------------- Get symb from alias
                   6592: 
                   6593: sub get_symb_from_alias {
                   6594:     my $symb=shift;
                   6595:     my ($map,$resid,$url)=&decode_symb($symb);
                   6596: # Already is a symb
                   6597:     if ($url) { return $symb; }
                   6598: # Must be an alias
                   6599:     my $aliassymb='';
                   6600:     my %bighash;
1.620     albertel 6601:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6602:                             &GDBM_READER(),0640)) {
                   6603:         my $rid=$bighash{'mapalias_'.$symb};
                   6604: 	if ($rid) {
                   6605: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6606: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6607: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6608: 	}
                   6609:         untie %bighash;
                   6610:     }
                   6611:     return $aliassymb;
                   6612: }
                   6613: 
1.12      www      6614: # ----------------------------------------------------------------- Define Role
                   6615: 
                   6616: sub definerole {
                   6617:   if (allowed('mcr','/')) {
                   6618:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6619:     foreach my $role (split(':',$sysrole)) {
                   6620: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6621:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6622:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6623: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6624:                return "refused:s:$crole&$cqual"; 
                   6625:             }
                   6626:         }
1.191     harris41 6627:     }
1.800     albertel 6628:     foreach my $role (split(':',$domrole)) {
                   6629: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6630:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6631:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6632: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6633:                return "refused:d:$crole&$cqual"; 
                   6634:             }
                   6635:         }
1.191     harris41 6636:     }
1.800     albertel 6637:     foreach my $role (split(':',$courole)) {
                   6638: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6639:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6640:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6641: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6642:                return "refused:c:$crole&$cqual"; 
                   6643:             }
                   6644:         }
1.191     harris41 6645:     }
1.620     albertel 6646:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6647:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6648: 	        "rolesdef_$rolename=".
                   6649:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6650:     return reply($command,$env{'user.home'});
1.12      www      6651:   } else {
                   6652:     return 'refused';
                   6653:   }
1.105     harris41 6654: }
                   6655: 
                   6656: # ---------------- Make a metadata query against the network of library servers
                   6657: 
                   6658: sub metadata_query {
1.244     matthew  6659:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6660:     my %rhash;
1.845     albertel 6661:     my %libserv = &all_library();
1.244     matthew  6662:     my @server_list = (defined($server_array) ? @$server_array
                   6663:                                               : keys(%libserv) );
                   6664:     for my $server (@server_list) {
1.118     harris41 6665: 	unless ($custom or $customshow) {
                   6666: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6667: 	    $rhash{$server}=$reply;
                   6668: 	}
                   6669: 	else {
                   6670: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6671: 			     &escape($custom).':'.&escape($customshow),
                   6672: 			     $server);
                   6673: 	    $rhash{$server}=$reply;
                   6674: 	}
1.112     harris41 6675:     }
1.118     harris41 6676:     return \%rhash;
1.240     www      6677: }
                   6678: 
                   6679: # ----------------------------------------- Send log queries and wait for reply
                   6680: 
                   6681: sub log_query {
                   6682:     my ($uname,$udom,$query,%filters)=@_;
                   6683:     my $uhome=&homeserver($uname,$udom);
                   6684:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6685:     my $uhost=&hostname($uhome);
1.800     albertel 6686:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6687:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6688:                        $uhome);
1.479     albertel 6689:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6690:     return get_query_reply($queryid);
                   6691: }
                   6692: 
1.818     raeburn  6693: # -------------------------- Update MySQL table for portfolio file
                   6694: 
                   6695: sub update_portfolio_table {
1.821     raeburn  6696:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6697:     if ($group ne '') {
                   6698:         $file_name =~s /^\Q$group\E//;
                   6699:     }
1.818     raeburn  6700:     my $homeserver = &homeserver($uname,$udom);
                   6701:     my $queryid=
1.821     raeburn  6702:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6703:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6704:     my $reply = &get_query_reply($queryid);
                   6705:     return $reply;
                   6706: }
                   6707: 
1.899     raeburn  6708: # -------------------------- Update MySQL allusers table
                   6709: 
                   6710: sub update_allusers_table {
                   6711:     my ($uname,$udom,$names) = @_;
                   6712:     my $homeserver = &homeserver($uname,$udom);
                   6713:     my $queryid=
                   6714:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6715:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6716:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6717:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6718:                'generation='.&escape($names->{'generation'}).'%%'.
                   6719:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6720:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6721:     return;
1.899     raeburn  6722: }
                   6723: 
1.508     raeburn  6724: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6725: 
                   6726: sub fetch_enrollment_query {
1.511     raeburn  6727:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6728:     my $homeserver;
1.547     raeburn  6729:     my $maxtries = 1;
1.508     raeburn  6730:     if ($context eq 'automated') {
                   6731:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6732:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6733:     } else {
                   6734:         $homeserver = &homeserver($cnum,$dom);
                   6735:     }
1.838     albertel 6736:     my $host=&hostname($homeserver);
1.506     raeburn  6737:     my $cmd = '';
1.1000    raeburn  6738:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6739:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6740:     }
                   6741:     $cmd =~ s/%%$//;
                   6742:     $cmd = &escape($cmd);
                   6743:     my $query = 'fetchenrollment';
1.620     albertel 6744:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6745:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6746:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6747:         return 'error: '.$queryid;
                   6748:     }
1.506     raeburn  6749:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6750:     my $tries = 1;
                   6751:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6752:         $reply = &get_query_reply($queryid);
                   6753:         $tries ++;
                   6754:     }
1.526     raeburn  6755:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6756:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6757:     } else {
1.901     albertel 6758:         my @responses = split(/:/,$reply);
1.515     raeburn  6759:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6760:             foreach my $line (@responses) {
                   6761:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6762:                 $$replyref{$key} = $value;
                   6763:             }
                   6764:         } else {
1.1117    foxr     6765:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6766:             foreach my $line (@responses) {
                   6767:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6768:                 $$replyref{$key} = $value;
                   6769:                 if ($value > 0) {
1.800     albertel 6770:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6771:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6772:                         my $destname = $pathname.'/'.$filename;
                   6773:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6774:                         if ($xml_classlist =~ /^error/) {
                   6775:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6776:                         } else {
1.506     raeburn  6777:                             if ( open(FILE,">$destname") ) {
                   6778:                                 print FILE &unescape($xml_classlist);
                   6779:                                 close(FILE);
1.526     raeburn  6780:                             } else {
                   6781:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6782:                             }
                   6783:                         }
                   6784:                     }
                   6785:                 }
                   6786:             }
                   6787:         }
                   6788:         return 'ok';
                   6789:     }
                   6790:     return 'error';
                   6791: }
                   6792: 
1.242     www      6793: sub get_query_reply {
                   6794:     my $queryid=shift;
1.1117    foxr     6795:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6796:     my $reply='';
                   6797:     for (1..100) {
                   6798: 	sleep 2;
                   6799:         if (-e $replyfile.'.end') {
1.448     albertel 6800: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6801: 		$reply = join('',<$fh>);
                   6802: 		close($fh);
1.240     www      6803: 	   } else { return 'error: reply_file_error'; }
1.242     www      6804:            return &unescape($reply);
                   6805: 	}
1.240     www      6806:     }
1.242     www      6807:     return 'timeout:'.$queryid;
1.240     www      6808: }
                   6809: 
                   6810: sub courselog_query {
1.241     www      6811: #
                   6812: # possible filters:
                   6813: # url: url or symb
                   6814: # username
                   6815: # domain
                   6816: # action: view, submit, grade
                   6817: # start: timestamp
                   6818: # end: timestamp
                   6819: #
1.240     www      6820:     my (%filters)=@_;
1.620     albertel 6821:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6822:     if ($filters{'url'}) {
                   6823: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6824:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6825:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6826:     }
1.620     albertel 6827:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6828:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6829:     return &log_query($cname,$cdom,'courselog',%filters);
                   6830: }
                   6831: 
                   6832: sub userlog_query {
1.858     raeburn  6833: #
                   6834: # possible filters:
                   6835: # action: log check role
                   6836: # start: timestamp
                   6837: # end: timestamp
                   6838: #
1.240     www      6839:     my ($uname,$udom,%filters)=@_;
                   6840:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6841: }
                   6842: 
1.506     raeburn  6843: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6844: 
                   6845: sub auto_run {
1.508     raeburn  6846:     my ($cnum,$cdom) = @_;
1.876     raeburn  6847:     my $response = 0;
                   6848:     my $settings;
                   6849:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6850:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6851:         $settings = $domconfig{'autoenroll'};
                   6852:         if ($settings->{'run'} eq '1') {
                   6853:             $response = 1;
                   6854:         }
                   6855:     } else {
1.934     raeburn  6856:         my $homeserver;
                   6857:         if (&is_course($cdom,$cnum)) {
                   6858:             $homeserver = &homeserver($cnum,$cdom);
                   6859:         } else {
                   6860:             $homeserver = &domain($cdom,'primary');
                   6861:         }
                   6862:         if ($homeserver ne 'no_host') {
                   6863:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6864:         }
1.876     raeburn  6865:     }
1.506     raeburn  6866:     return $response;
                   6867: }
1.776     albertel 6868: 
1.506     raeburn  6869: sub auto_get_sections {
1.508     raeburn  6870:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6871:     my $homeserver;
                   6872:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6873:         $homeserver = &homeserver($cnum,$cdom);
                   6874:     }
                   6875:     if (!defined($homeserver)) { 
                   6876:         if ($cdom =~ /^$match_domain$/) {
                   6877:             $homeserver = &domain($cdom,'primary');
                   6878:         }
                   6879:     }
                   6880:     my @secs;
                   6881:     if (defined($homeserver)) {
                   6882:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6883:         unless ($response eq 'refused') {
                   6884:             @secs = split(/:/,$response);
                   6885:         }
1.506     raeburn  6886:     }
                   6887:     return @secs;
                   6888: }
1.776     albertel 6889: 
1.506     raeburn  6890: sub auto_new_course {
1.1099    raeburn  6891:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6892:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6893:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6894:     return $response;
                   6895: }
1.776     albertel 6896: 
1.506     raeburn  6897: sub auto_validate_courseID {
1.508     raeburn  6898:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6899:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6900:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6901:     return $response;
                   6902: }
1.776     albertel 6903: 
1.1007    raeburn  6904: sub auto_validate_instcode {
1.1020    raeburn  6905:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6906:     my ($homeserver,$response);
                   6907:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6908:         $homeserver = &homeserver($cnum,$cdom);
                   6909:     }
                   6910:     if (!defined($homeserver)) {
                   6911:         if ($cdom =~ /^$match_domain$/) {
                   6912:             $homeserver = &domain($cdom,'primary');
                   6913:         }
                   6914:     }
1.1065    raeburn  6915:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6916:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6917:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6918:     return ($outcome,$description);
1.1007    raeburn  6919: }
                   6920: 
1.506     raeburn  6921: sub auto_create_password {
1.873     raeburn  6922:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6923:     my ($homeserver,$response);
1.506     raeburn  6924:     my $create_passwd = 0;
                   6925:     my $authchk = '';
1.873     raeburn  6926:     if ($udom =~ /^$match_domain$/) {
                   6927:         $homeserver = &domain($udom,'primary');
                   6928:     }
                   6929:     if ($homeserver eq '') {
                   6930:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6931:             $homeserver = &homeserver($cnum,$cdom);
                   6932:         }
                   6933:     }
                   6934:     if ($homeserver eq '') {
                   6935:         $authchk = 'nodomain';
1.506     raeburn  6936:     } else {
1.873     raeburn  6937:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6938:         if ($response eq 'refused') {
                   6939:             $authchk = 'refused';
                   6940:         } else {
1.901     albertel 6941:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6942:         }
1.506     raeburn  6943:     }
                   6944:     return ($authparam,$create_passwd,$authchk);
                   6945: }
                   6946: 
1.706     raeburn  6947: sub auto_photo_permission {
                   6948:     my ($cnum,$cdom,$students) = @_;
                   6949:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6950:     my ($outcome,$perm_reqd,$conditions) = 
                   6951: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6952:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6953: 	return (undef,undef);
                   6954:     }
1.706     raeburn  6955:     return ($outcome,$perm_reqd,$conditions);
                   6956: }
                   6957: 
                   6958: sub auto_checkphotos {
                   6959:     my ($uname,$udom,$pid) = @_;
                   6960:     my $homeserver = &homeserver($uname,$udom);
                   6961:     my ($result,$resulttype);
                   6962:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6963: 				   &escape($uname).':'.&escape($pid),
                   6964: 				   $homeserver));
1.709     albertel 6965:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6966: 	return (undef,undef);
                   6967:     }
1.706     raeburn  6968:     if ($outcome) {
                   6969:         ($result,$resulttype) = split(/:/,$outcome);
                   6970:     } 
                   6971:     return ($result,$resulttype);
                   6972: }
                   6973: 
                   6974: sub auto_photochoice {
                   6975:     my ($cnum,$cdom) = @_;
                   6976:     my $homeserver = &homeserver($cnum,$cdom);
                   6977:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6978: 						       &escape($cdom),
                   6979: 						       $homeserver)));
1.709     albertel 6980:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6981: 	return (undef,undef);
                   6982:     }
1.706     raeburn  6983:     return ($update,$comment);
                   6984: }
                   6985: 
                   6986: sub auto_photoupdate {
                   6987:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6988:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6989:     my $host=&hostname($homeserver);
1.706     raeburn  6990:     my $cmd = '';
                   6991:     my $maxtries = 1;
1.800     albertel 6992:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6993:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6994:     }
                   6995:     $cmd =~ s/%%$//;
                   6996:     $cmd = &escape($cmd);
                   6997:     my $query = 'institutionalphotos';
                   6998:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6999:     unless ($queryid=~/^\Q$host\E\_/) {
                   7000:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7001:         return 'error: '.$queryid;
                   7002:     }
                   7003:     my $reply = &get_query_reply($queryid);
                   7004:     my $tries = 1;
                   7005:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7006:         $reply = &get_query_reply($queryid);
                   7007:         $tries ++;
                   7008:     }
                   7009:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7010:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7011:     } else {
                   7012:         my @responses = split(/:/,$reply);
                   7013:         my $outcome = shift(@responses); 
                   7014:         foreach my $item (@responses) {
                   7015:             my ($key,$value) = split(/=/,$item);
                   7016:             $$photo{$key} = $value;
                   7017:         }
                   7018:         return $outcome;
                   7019:     }
                   7020:     return 'error';
                   7021: }
                   7022: 
1.521     raeburn  7023: sub auto_instcode_format {
1.793     albertel 7024:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7025: 	$cat_order) = @_;
1.521     raeburn  7026:     my $courses = '';
1.772     raeburn  7027:     my @homeservers;
1.521     raeburn  7028:     if ($caller eq 'global') {
1.841     albertel 7029: 	my %servers = &get_servers($codedom,'library');
                   7030: 	foreach my $tryserver (keys(%servers)) {
                   7031: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7032: 		push(@homeservers,$tryserver);
                   7033: 	    }
1.584     raeburn  7034:         }
1.1022    raeburn  7035:     } elsif ($caller eq 'requests') {
                   7036:         if ($codedom =~ /^$match_domain$/) {
                   7037:             my $chome = &domain($codedom,'primary');
                   7038:             unless ($chome eq 'no_host') {
                   7039:                 push(@homeservers,$chome);
                   7040:             }
                   7041:         }
1.521     raeburn  7042:     } else {
1.772     raeburn  7043:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7044:     }
1.793     albertel 7045:     foreach my $code (keys(%{$instcodes})) {
                   7046:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7047:     }
                   7048:     chop($courses);
1.772     raeburn  7049:     my $ok_response = 0;
                   7050:     my $response;
                   7051:     while (@homeservers > 0 && $ok_response == 0) {
                   7052:         my $server = shift(@homeservers); 
                   7053:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7054:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7055:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7056: 		split(/:/,$response);
1.772     raeburn  7057:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7058:             push(@{$codetitles},&str2array($codetitles_str));
                   7059:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7060:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7061:             $ok_response = 1;
                   7062:         }
                   7063:     }
                   7064:     if ($ok_response) {
1.521     raeburn  7065:         return 'ok';
1.772     raeburn  7066:     } else {
                   7067:         return $response;
1.521     raeburn  7068:     }
                   7069: }
                   7070: 
1.792     raeburn  7071: sub auto_instcode_defaults {
                   7072:     my ($domain,$returnhash,$code_order) = @_;
                   7073:     my @homeservers;
1.841     albertel 7074: 
                   7075:     my %servers = &get_servers($domain,'library');
                   7076:     foreach my $tryserver (keys(%servers)) {
                   7077: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7078: 	    push(@homeservers,$tryserver);
                   7079: 	}
1.792     raeburn  7080:     }
1.841     albertel 7081: 
1.792     raeburn  7082:     my $response;
1.841     albertel 7083:     foreach my $server (@homeservers) {
1.792     raeburn  7084:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7085:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7086: 	
                   7087: 	foreach my $pair (split(/\&/,$response)) {
                   7088: 	    my ($name,$value)=split(/\=/,$pair);
                   7089: 	    if ($name eq 'code_order') {
                   7090: 		@{$code_order} = split(/\&/,&unescape($value));
                   7091: 	    } else {
                   7092: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7093: 	    }
                   7094: 	}
                   7095: 	return 'ok';
1.792     raeburn  7096:     }
1.841     albertel 7097: 
                   7098:     return $response;
1.1003    raeburn  7099: }
                   7100: 
                   7101: sub auto_possible_instcodes {
1.1007    raeburn  7102:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7103:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7104:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7105:         return;
                   7106:     }
1.1003    raeburn  7107:     my (@homeservers,$uhome);
                   7108:     if (defined(&domain($domain,'primary'))) {
                   7109:         $uhome=&domain($domain,'primary');
                   7110:         push(@homeservers,&domain($domain,'primary'));
                   7111:     } else {
                   7112:         my %servers = &get_servers($domain,'library');
                   7113:         foreach my $tryserver (keys(%servers)) {
                   7114:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7115:                 push(@homeservers,$tryserver);
                   7116:             }
                   7117:         }
                   7118:     }
                   7119:     my $response;
                   7120:     foreach my $server (@homeservers) {
                   7121:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7122:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7123:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7124:             split(':',$response);
                   7125:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7126:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7127:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7128:             my ($name,$value)=split('=',$item);
                   7129:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7130:         }
                   7131:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7132:             my ($name,$value)=split('=',$item);
                   7133:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7134:         }
                   7135:         return 'ok';
                   7136:     }
                   7137:     return $response;
                   7138: }
1.792     raeburn  7139: 
1.1010    raeburn  7140: sub auto_courserequest_checks {
                   7141:     my ($dom) = @_;
1.1020    raeburn  7142:     my ($homeserver,%validations);
                   7143:     if ($dom =~ /^$match_domain$/) {
                   7144:         $homeserver = &domain($dom,'primary');
                   7145:     }
                   7146:     unless ($homeserver eq 'no_host') {
                   7147:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7148:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7149:             my @items = split(/&/,$response);
                   7150:             foreach my $item (@items) {
                   7151:                 my ($key,$value) = split('=',$item);
                   7152:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7153:             }
                   7154:         }
                   7155:     }
1.1010    raeburn  7156:     return %validations; 
                   7157: }
                   7158: 
1.1020    raeburn  7159: sub auto_courserequest_validation {
                   7160:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7161:     my ($homeserver,$response);
                   7162:     if ($dom =~ /^$match_domain$/) {
                   7163:         $homeserver = &domain($dom,'primary');
                   7164:     }
                   7165:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7166:           
1.1020    raeburn  7167:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7168:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7169:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7170:                                     $homeserver));
                   7171:     }
                   7172:     return $response;
                   7173: }
                   7174: 
1.777     albertel 7175: sub auto_validate_class_sec {
1.918     raeburn  7176:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7177:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7178:     my $ownerlist;
                   7179:     if (ref($owners) eq 'ARRAY') {
                   7180:         $ownerlist = join(',',@{$owners});
                   7181:     } else {
                   7182:         $ownerlist = $owners;
                   7183:     }
1.773     raeburn  7184:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7185:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7186:     return $response;
                   7187: }
                   7188: 
1.679     raeburn  7189: # ------------------------------------------------------- Course Group routines
                   7190: 
                   7191: sub get_coursegroups {
1.809     raeburn  7192:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7193:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7194: }
                   7195: 
1.679     raeburn  7196: sub modify_coursegroup {
                   7197:     my ($cdom,$cnum,$groupsettings) = @_;
                   7198:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7199: }
                   7200: 
1.809     raeburn  7201: sub toggle_coursegroup_status {
                   7202:     my ($cdom,$cnum,$group,$action) = @_;
                   7203:     my ($from_namespace,$to_namespace);
                   7204:     if ($action eq 'delete') {
                   7205:         $from_namespace = 'coursegroups';
                   7206:         $to_namespace = 'deleted_groups';
                   7207:     } else {
                   7208:         $from_namespace = 'deleted_groups';
                   7209:         $to_namespace = 'coursegroups';
                   7210:     }
                   7211:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7212:     if (my $tmp = &error(%curr_group)) {
                   7213:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7214:         return ('read error',$tmp);
                   7215:     } else {
                   7216:         my %savedsettings = %curr_group; 
1.809     raeburn  7217:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7218:         my $deloutcome;
                   7219:         if ($result eq 'ok') {
1.809     raeburn  7220:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7221:         } else {
                   7222:             return ('write error',$result);
                   7223:         }
                   7224:         if ($deloutcome eq 'ok') {
                   7225:             return 'ok';
                   7226:         } else {
                   7227:             return ('delete error',$deloutcome);
                   7228:         }
                   7229:     }
                   7230: }
                   7231: 
1.679     raeburn  7232: sub modify_group_roles {
1.957     raeburn  7233:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7234:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7235:     my $role = 'gr/'.&escape($userprivs);
                   7236:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7237:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7238:     if ($result eq 'ok') {
                   7239:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7240:     }
1.679     raeburn  7241:     return $result;
                   7242: }
                   7243: 
                   7244: sub modify_coursegroup_membership {
                   7245:     my ($cdom,$cnum,$membership) = @_;
                   7246:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7247:     return $result;
                   7248: }
                   7249: 
1.682     raeburn  7250: sub get_active_groups {
                   7251:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7252:     my $now = time;
                   7253:     my %groups = ();
                   7254:     foreach my $key (keys(%env)) {
1.811     albertel 7255:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7256:             my ($start,$end) = split(/\./,$env{$key});
                   7257:             if (($end!=0) && ($end<$now)) { next; }
                   7258:             if (($start!=0) && ($start>$now)) { next; }
                   7259:             if ($1 eq $cdom && $2 eq $cnum) {
                   7260:                 $groups{$3} = $env{$key} ;
                   7261:             }
                   7262:         }
                   7263:     }
                   7264:     return %groups;
                   7265: }
                   7266: 
1.683     raeburn  7267: sub get_group_membership {
                   7268:     my ($cdom,$cnum,$group) = @_;
                   7269:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7270: }
                   7271: 
                   7272: sub get_users_groups {
                   7273:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7274:     my @usersgroups;
1.683     raeburn  7275:     my $cachetime=1800;
                   7276: 
                   7277:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7278:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7279:     if (defined($cached)) {
1.734     albertel 7280:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7281:     } else {  
                   7282:         $grouplist = '';
1.816     raeburn  7283:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7284:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7285:         my $access_end = $env{'course.'.$courseid.
                   7286:                               '.default_enrollment_end_date'};
                   7287:         my $now = time;
                   7288:         foreach my $key (keys(%roleshash)) {
                   7289:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7290:                 my $group = $1;
                   7291:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7292:                     my $start = $2;
                   7293:                     my $end = $1;
                   7294:                     if ($start == -1) { next; } # deleted from group
                   7295:                     if (($start!=0) && ($start>$now)) { next; }
                   7296:                     if (($end!=0) && ($end<$now)) {
                   7297:                         if ($access_end && $access_end < $now) {
                   7298:                             if ($access_end - $end < 86400) {
                   7299:                                 push(@usersgroups,$group);
1.733     raeburn  7300:                             }
                   7301:                         }
1.817     raeburn  7302:                         next;
1.733     raeburn  7303:                     }
1.817     raeburn  7304:                     push(@usersgroups,$group);
1.683     raeburn  7305:                 }
                   7306:             }
                   7307:         }
1.817     raeburn  7308:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7309:         $grouplist = join(':',@usersgroups);
                   7310:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7311:     }
1.733     raeburn  7312:     return @usersgroups;
1.683     raeburn  7313: }
                   7314: 
                   7315: sub devalidate_getgroups_cache {
                   7316:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7317:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7318: 
1.683     raeburn  7319:     my $hashid="$udom:$uname:$courseid";
                   7320:     &devalidate_cache_new('getgroups',$hashid);
                   7321: }
                   7322: 
1.12      www      7323: # ------------------------------------------------------------------ Plain Text
                   7324: 
                   7325: sub plaintext {
1.988     raeburn  7326:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7327:     if ($short =~ m{^cr/}) {
1.758     albertel 7328: 	return (split('/',$short))[-1];
                   7329:     }
1.742     raeburn  7330:     if (!defined($cid)) {
                   7331:         $cid = $env{'request.course.id'};
                   7332:     }
                   7333:     my %rolenames = (
1.1008    raeburn  7334:                       Course    => 'std',
                   7335:                       Community => 'alt1',
1.742     raeburn  7336:                     );
1.1037    raeburn  7337:     if ($cid ne '') {
                   7338:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7339:             unless ($forcedefault) {
                   7340:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7341:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7342:                 return &Apache::lonlocal::mt($roletext);
                   7343:             }
                   7344:         }
                   7345:     }
                   7346:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7347:         (defined($rolenames{$type})) && 
                   7348:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7349:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7350:     } elsif ($cid ne '') {
                   7351:         my $crstype = $env{'course.'.$cid.'.type'};
                   7352:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7353:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7354:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7355:         }
1.742     raeburn  7356:     }
1.1037    raeburn  7357:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7358: }
                   7359: 
                   7360: # ----------------------------------------------------------------- Assign Role
                   7361: 
                   7362: sub assignrole {
1.957     raeburn  7363:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7364:         $context)=@_;
1.21      www      7365:     my $mrole;
                   7366:     if ($role =~ /^cr\//) {
1.393     www      7367:         my $cwosec=$url;
1.811     albertel 7368:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7369: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7370:            my $refused = 1;
                   7371:            if ($context eq 'requestcourses') {
                   7372:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7373:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7374:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7375:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7376:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7377:                            if ($crsenv{'internal.courseowner'} eq
                   7378:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7379:                                $refused = '';
                   7380:                            }
                   7381:                        }
                   7382:                    }
                   7383:                }
                   7384:            }
                   7385:            if ($refused) {
                   7386:                &logthis('Refused custom assignrole: '.
                   7387:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7388:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7389:                return 'refused';
                   7390:            }
1.104     www      7391:         }
1.21      www      7392:         $mrole='cr';
1.678     raeburn  7393:     } elsif ($role =~ /^gr\//) {
                   7394:         my $cwogrp=$url;
1.811     albertel 7395:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7396:         unless (&allowed('mdg',$cwogrp)) {
                   7397:             &logthis('Refused group assignrole: '.
                   7398:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7399:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7400:             return 'refused';
                   7401:         }
                   7402:         $mrole='gr';
1.21      www      7403:     } else {
1.82      www      7404:         my $cwosec=$url;
1.811     albertel 7405:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7406:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7407:             my $refused;
                   7408:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7409:                 if (!(&allowed('c'.$role,$url))) {
                   7410:                     $refused = 1;
                   7411:                 }
                   7412:             } else {
                   7413:                 $refused = 1;
                   7414:             }
1.947     raeburn  7415:             if ($refused) {
1.1045    raeburn  7416:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7417:                 if (!$selfenroll && $context eq 'course') {
                   7418:                     my %crsenv;
                   7419:                     if ($role eq 'cc' || $role eq 'co') {
                   7420:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7421:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7422:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7423:                                 if ($crsenv{'internal.courseowner'} eq 
                   7424:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7425:                                     $refused = '';
                   7426:                                 }
                   7427:                             }
                   7428:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7429:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7430:                                 if ($crsenv{'internal.courseowner'} eq 
                   7431:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7432:                                     $refused = '';
                   7433:                                 }
                   7434:                             }
                   7435:                         }
                   7436:                     }
                   7437:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7438:                     $refused = '';
1.1017    raeburn  7439:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7440:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7441:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7442:                         my $wrongcc;
                   7443:                         if ($cnum =~ /^$match_community$/) {
                   7444:                             $wrongcc = 1 if ($role eq 'cc');
                   7445:                         } else {
                   7446:                             $wrongcc = 1 if ($role eq 'co');
                   7447:                         }
                   7448:                         unless ($wrongcc) {
                   7449:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7450:                             if ($crsenv{'internal.courseowner'} eq 
                   7451:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7452:                                 $refused = '';
                   7453:                             }
1.1017    raeburn  7454:                         }
                   7455:                     }
                   7456:                 }
                   7457:                 if ($refused) {
1.947     raeburn  7458:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7459:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7460: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7461:                     return 'refused';
                   7462:                 }
1.932     raeburn  7463:             }
1.1131    raeburn  7464:         } elsif ($role eq 'au') {
                   7465:             if ($url ne '/'.$udom.'/') {
                   7466:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7467:                          ' to assign author role for '.$uname.':'.$udom.
                   7468:                          ' in domain: '.$url.' refused (wrong domain).');
                   7469:                 return 'refused';
                   7470:             }
1.104     www      7471:         }
1.21      www      7472:         $mrole=$role;
                   7473:     }
1.620     albertel 7474:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7475:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7476:     if ($end) { $command.='_'.$end; }
1.21      www      7477:     if ($start) {
                   7478: 	if ($end) { 
1.81      www      7479:            $command.='_'.$start; 
1.21      www      7480:         } else {
1.81      www      7481:            $command.='_0_'.$start;
1.21      www      7482:         }
                   7483:     }
1.739     raeburn  7484:     my $origstart = $start;
                   7485:     my $origend = $end;
1.957     raeburn  7486:     my $delflag;
1.357     www      7487: # actually delete
                   7488:     if ($deleteflag) {
1.373     www      7489: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7490: # modify command to delete the role
1.620     albertel 7491:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7492:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7493: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7494: # set start and finish to negative values for userrolelog
                   7495:            $start=-1;
                   7496:            $end=-1;
1.957     raeburn  7497:            $delflag = 1;
1.357     www      7498:         }
                   7499:     }
                   7500: # send command
1.349     www      7501:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7502: # log new user role if status is ok
1.349     www      7503:     if ($answer eq 'ok') {
1.663     raeburn  7504: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7505: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7506:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7507:         unless ($role =~ /^gr/) {
                   7508:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7509:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7510:         }
1.1053    raeburn  7511:         if ($role eq 'cc') {
                   7512:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7513:         }
1.349     www      7514:     }
                   7515:     return $answer;
1.169     harris41 7516: }
                   7517: 
1.1053    raeburn  7518: sub autoupdate_coowners {
                   7519:     my ($url,$end,$start,$uname,$udom) = @_;
                   7520:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7521:     if (($cdom ne '') && ($cnum ne '')) {
                   7522:         my $now = time;
                   7523:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7524:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7525:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7526:             my $instcode = $coursehash{'internal.coursecode'};
                   7527:             if ($instcode ne '') {
1.1056    raeburn  7528:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7529:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7530:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7531:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7532:                         if ($result eq 'valid') {
                   7533:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7534:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7535:                                     push(@newcoowners,$coowner);
                   7536:                                 }
                   7537:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7538:                                     push(@newcoowners,$uname.':'.$udom);
                   7539:                                 }
                   7540:                                 @newcoowners = sort(@newcoowners);
                   7541:                             } else {
                   7542:                                 push(@newcoowners,$uname.':'.$udom);
                   7543:                             }
                   7544:                         } else {
                   7545:                             if ($coursehash{'internal.co-owners'}) {
                   7546:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7547:                                     unless ($coowner eq $uname.':'.$udom) {
                   7548:                                         push(@newcoowners,$coowner);
                   7549:                                     }
                   7550:                                 }
                   7551:                                 unless (@newcoowners > 0) {
                   7552:                                     $delcoowners = 1;
                   7553:                                     $coowners = '';
                   7554:                                 }
                   7555:                             }
                   7556:                         }
                   7557:                         if (@newcoowners || $delcoowners) {
                   7558:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7559:                                             $delcoowners,@newcoowners);
                   7560:                         }
                   7561:                     }
                   7562:                 }
                   7563:             }
                   7564:         }
                   7565:     }
                   7566: }
                   7567: 
                   7568: sub store_coowners {
                   7569:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7570:     my $cid = $cdom.'_'.$cnum;
                   7571:     my ($coowners,$delresult,$putresult);
                   7572:     if (@newcoowners) {
                   7573:         $coowners = join(',',@newcoowners);
                   7574:         my %coownershash = (
                   7575:                             'internal.co-owners' => $coowners,
                   7576:                            );
                   7577:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7578:         if ($putresult eq 'ok') {
                   7579:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7580:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7581:             }
                   7582:         }
                   7583:     }
                   7584:     if ($delcoowners) {
                   7585:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7586:         if ($delresult eq 'ok') {
                   7587:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7588:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7589:             }
                   7590:         }
                   7591:     }
                   7592:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7593:         my %crsinfo =
                   7594:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7595:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7596:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7597:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7598:         }
                   7599:     }
                   7600: }
                   7601: 
1.169     harris41 7602: # -------------------------------------------------- Modify user authentication
1.197     www      7603: # Overrides without validation
                   7604: 
1.169     harris41 7605: sub modifyuserauth {
                   7606:     my ($udom,$uname,$umode,$upass)=@_;
                   7607:     my $uhome=&homeserver($uname,$udom);
1.197     www      7608:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7609:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7610:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7611:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7612:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7613: 		     &escape($upass),$uhome);
1.620     albertel 7614:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7615:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7616:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7617:     &log($udom,,$uname,$uhome,
1.620     albertel 7618:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7619:                                      $env{'user.name'}.', '.$umode.
1.197     www      7620:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7621:     unless ($reply eq 'ok') {
1.197     www      7622:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7623: 	return 'error: '.$reply;
                   7624:     }   
1.170     harris41 7625:     return 'ok';
1.80      www      7626: }
                   7627: 
1.81      www      7628: # --------------------------------------------------------------- Modify a user
1.80      www      7629: 
1.81      www      7630: sub modifyuser {
1.206     matthew  7631:     my ($udom,    $uname, $uid,
                   7632:         $umode,   $upass, $first,
                   7633:         $middle,  $last,  $gene,
1.1058    raeburn  7634:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7635:     $udom= &LONCAPA::clean_domain($udom);
                   7636:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7637:     my $showcandelete = 'none';
                   7638:     if (ref($candelete) eq 'ARRAY') {
                   7639:         if (@{$candelete} > 0) {
                   7640:             $showcandelete = join(', ',@{$candelete});
                   7641:         }
                   7642:     }
1.81      www      7643:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7644:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7645: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7646:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7647:                                      ' desiredhome not specified'). 
1.620     albertel 7648:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7649:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7650:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7651:     my $newuser;
                   7652:     if ($uhome eq 'no_host') {
                   7653:         $newuser = 1;
                   7654:     }
1.80      www      7655: # ----------------------------------------------------------------- Create User
1.406     albertel 7656:     if (($uhome eq 'no_host') && 
                   7657: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7658:         my $unhome='';
1.844     albertel 7659:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7660:             $unhome = $desiredhome;
1.620     albertel 7661: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7662: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7663:         } else { # load balancing routine for determining $unhome
1.81      www      7664:             my $loadm=10000000;
1.841     albertel 7665: 	    my %servers = &get_servers($udom,'library');
                   7666: 	    foreach my $tryserver (keys(%servers)) {
                   7667: 		my $answer=reply('load',$tryserver);
                   7668: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7669: 		    $loadm=$answer;
                   7670: 		    $unhome=$tryserver;
                   7671: 		}
1.80      www      7672: 	    }
                   7673:         }
                   7674:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7675: 	    return 'error: unable to find a home server for '.$uname.
                   7676:                    ' in domain '.$udom;
1.80      www      7677:         }
                   7678:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7679:                          &escape($upass),$unhome);
                   7680: 	unless ($reply eq 'ok') {
                   7681:             return 'error: '.$reply;
                   7682:         }   
1.230     stredwic 7683:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7684:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7685: 	    return 'error: unable verify users home machine.';
1.80      www      7686:         }
1.209     matthew  7687:     }   # End of creation of new user
1.80      www      7688: # ---------------------------------------------------------------------- Add ID
                   7689:     if ($uid) {
                   7690:        $uid=~tr/A-Z/a-z/;
                   7691:        my %uidhash=&idrget($udom,$uname);
1.196     www      7692:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7693:          && (!$forceid)) {
1.80      www      7694: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7695: 	      return 'error: user id "'.$uid.'" does not match '.
                   7696:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7697:           }
                   7698:        } else {
                   7699: 	  &idput($udom,($uname => $uid));
                   7700:        }
                   7701:     }
                   7702: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7703:     my @tmp=&get('environment',
1.899     raeburn  7704: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7705:                     'permanentemail','inststatus'],
1.134     albertel 7706: 		   $udom,$uname);
1.1075    raeburn  7707:     my (%names,%oldnames);
1.313     matthew  7708:     if ($tmp[0] =~ m/^error:.*/) { 
                   7709:         %names=(); 
                   7710:     } else {
                   7711:         %names = @tmp;
1.1075    raeburn  7712:         %oldnames = %names;
1.313     matthew  7713:     }
1.388     www      7714: #
1.1058    raeburn  7715: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7716: # of users did not contain them), do not overwrite existing values
                   7717: # unless field is in $candelete array ref.  
                   7718: #
                   7719: 
                   7720:     my @fields = ('firstname','middlename','lastname','generation',
                   7721:                   'permanentemail','id');
                   7722:     my %newvalues;
                   7723:     if (ref($candelete) eq 'ARRAY') {
                   7724:         foreach my $field (@fields) {
                   7725:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7726:                 if ($field eq 'firstname') {
                   7727:                     $names{$field} = $first;
                   7728:                 } elsif ($field eq 'middlename') {
                   7729:                     $names{$field} = $middle;
                   7730:                 } elsif ($field eq 'lastname') {
                   7731:                     $names{$field} = $last;
                   7732:                 } elsif ($field eq 'generation') { 
                   7733:                     $names{$field} = $gene;
                   7734:                 } elsif ($field eq 'permanentemail') {
                   7735:                     $names{$field} = $email;
                   7736:                 } elsif ($field eq 'id') {
                   7737:                     $names{$field}  = $uid;
                   7738:                 }
                   7739:             }
                   7740:         }
                   7741:     }
1.388     www      7742:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7743:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7744:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7745:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7746:     if ($email) {
                   7747:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7748:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7749:     }
1.899     raeburn  7750:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7751:     if (defined($inststatus)) {
                   7752:         $names{'inststatus'} = '';
                   7753:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7754:         if (ref($usertypes) eq 'HASH') {
                   7755:             my @okstatuses; 
                   7756:             foreach my $item (split(/:/,$inststatus)) {
                   7757:                 if (defined($usertypes->{$item})) {
                   7758:                     push(@okstatuses,$item);  
                   7759:                 }
                   7760:             }
                   7761:             if (@okstatuses) {
                   7762:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7763:             }
                   7764:         }
                   7765:     }
1.1075    raeburn  7766:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7767:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7768:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7769:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7770:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7771:     } else {
                   7772:         $logmsg .= ' during self creation';
                   7773:     }
1.1075    raeburn  7774:     my $changed;
                   7775:     if ($newuser) {
                   7776:         $changed = 1;
                   7777:     } else {
                   7778:         foreach my $field (@fields) {
                   7779:             if ($names{$field} ne $oldnames{$field}) {
                   7780:                 $changed = 1;
                   7781:                 last;
                   7782:             }
                   7783:         }
                   7784:     }
                   7785:     unless ($changed) {
                   7786:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7787:         &logthis($logmsg);
                   7788:         return 'ok';
                   7789:     }
                   7790:     my $reply = &put('environment', \%names, $udom,$uname);
                   7791:     if ($reply ne 'ok') { 
                   7792:         return 'error: '.$reply;
                   7793:     }
1.1087    raeburn  7794:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7795:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7796:     }
1.1075    raeburn  7797:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7798:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7799:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7800:     &logthis($logmsg);
1.134     albertel 7801:     return 'ok';
1.80      www      7802: }
                   7803: 
1.81      www      7804: # -------------------------------------------------------------- Modify student
1.80      www      7805: 
1.81      www      7806: sub modifystudent {
                   7807:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7808:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7809:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7810:     if (!$cid) {
1.620     albertel 7811: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7812: 	    return 'not_in_class';
                   7813: 	}
1.80      www      7814:     }
                   7815: # --------------------------------------------------------------- Make the user
1.81      www      7816:     my $reply=&modifyuser
1.209     matthew  7817: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7818:          $desiredhome,$email,$inststatus);
1.80      www      7819:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7820:     # This will cause &modify_student_enrollment to get the uid from the
                   7821:     # students environment
                   7822:     $uid = undef if (!$forceid);
1.455     albertel 7823:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7824: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7825:     return $reply;
                   7826: }
                   7827: 
                   7828: sub modify_student_enrollment {
1.957     raeburn  7829:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7830:     my ($cdom,$cnum,$chome);
                   7831:     if (!$cid) {
1.620     albertel 7832: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7833: 	    return 'not_in_class';
                   7834: 	}
1.620     albertel 7835: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7836: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7837:     } else {
                   7838: 	($cdom,$cnum)=split(/_/,$cid);
                   7839:     }
1.620     albertel 7840:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7841:     if (!$chome) {
1.457     raeburn  7842: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7843:     }
1.455     albertel 7844:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7845:     # Make sure the user exists
1.81      www      7846:     my $uhome=&homeserver($uname,$udom);
                   7847:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7848: 	return 'error: no such user';
                   7849:     }
1.297     matthew  7850:     # Get student data if we were not given enough information
                   7851:     if (!defined($first)  || $first  eq '' || 
                   7852:         !defined($last)   || $last   eq '' || 
                   7853:         !defined($uid)    || $uid    eq '' || 
                   7854:         !defined($middle) || $middle eq '' || 
                   7855:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7856:         # They did not supply us with enough data to enroll the student, so
                   7857:         # we need to pick up more information.
1.297     matthew  7858:         my %tmp = &get('environment',
1.294     matthew  7859:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7860:                        ,$udom,$uname);
                   7861: 
1.800     albertel 7862:         #foreach my $key (keys(%tmp)) {
                   7863:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7864:         #}
1.294     matthew  7865:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7866:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7867:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7868:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7869:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7870:     }
1.556     albertel 7871:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7872:     my $user = "$uname:$udom";
                   7873:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7874:     my $reply=cput('classlist',
1.1148    raeburn  7875: 		   {$user => 
1.515     raeburn  7876: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7877: 		   $cdom,$cnum);
1.1148    raeburn  7878:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7879:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7880:     } else { 
1.81      www      7881: 	return 'error: '.$reply;
                   7882:     }
1.297     matthew  7883:     # Add student role to user
1.83      www      7884:     my $uurl='/'.$cid;
1.81      www      7885:     $uurl=~s/\_/\//g;
                   7886:     if ($usec) {
                   7887: 	$uurl.='/'.$usec;
                   7888:     }
1.1148    raeburn  7889:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7890:                              $selfenroll,$context);
                   7891:     if ($result ne 'ok') {
                   7892:         if ($old_entry{$user} ne '') {
                   7893:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7894:         } else {
                   7895:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7896:         }
                   7897:     }
                   7898:     return $result; 
1.21      www      7899: }
                   7900: 
1.556     albertel 7901: sub format_name {
                   7902:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7903:     my $name;
                   7904:     if ($first ne 'lastname') {
                   7905: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7906:     } else {
                   7907: 	if ($lastname=~/\S/) {
                   7908: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7909: 	    $name=~s/\s+,/,/;
                   7910: 	} else {
                   7911: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7912: 	}
                   7913:     }
                   7914:     $name=~s/^\s+//;
                   7915:     $name=~s/\s+$//;
                   7916:     $name=~s/\s+/ /g;
                   7917:     return $name;
                   7918: }
                   7919: 
1.84      www      7920: # ------------------------------------------------- Write to course preferences
                   7921: 
                   7922: sub writecoursepref {
                   7923:     my ($courseid,%prefs)=@_;
                   7924:     $courseid=~s/^\///;
                   7925:     $courseid=~s/\_/\//g;
                   7926:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7927:     my $chome=homeserver($cnum,$cdomain);
                   7928:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7929: 	return 'error: no such course';
                   7930:     }
                   7931:     my $cstring='';
1.800     albertel 7932:     foreach my $pref (keys(%prefs)) {
                   7933: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7934:     }
1.84      www      7935:     $cstring=~s/\&$//;
                   7936:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7937: }
                   7938: 
                   7939: # ---------------------------------------------------------- Make/modify course
                   7940: 
                   7941: sub createcourse {
1.741     raeburn  7942:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7943:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7944:     $url=&declutter($url);
                   7945:     my $cid='';
1.1028    raeburn  7946:     if ($context eq 'requestcourses') {
                   7947:         my $can_create = 0;
                   7948:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7949:         if ($udom eq $ownerdom) {
                   7950:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7951:                                   $context)) {
                   7952:                 $can_create = 1;
                   7953:             }
                   7954:         } else {
                   7955:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7956:                                            $category);
                   7957:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7958:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7959:                 if (@curr > 0) {
                   7960:                     my @options = qw(approval validate autolimit);
                   7961:                     my $optregex = join('|',@options);
                   7962:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7963:                         $can_create = 1;
                   7964:                     }
                   7965:                 }
                   7966:             }
                   7967:         }
                   7968:         if ($can_create) {
                   7969:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7970:                 unless (&allowed('ccc',$udom)) {
                   7971:                     return 'refused'; 
                   7972:                 }
1.1017    raeburn  7973:             }
                   7974:         } else {
                   7975:             return 'refused';
                   7976:         }
1.1028    raeburn  7977:     } elsif (!&allowed('ccc',$udom)) {
                   7978:         return 'refused';
1.84      www      7979:     }
1.1011    raeburn  7980: # --------------------------------------------------------------- Get Unique ID
                   7981:     my $uname;
                   7982:     if ($cnum =~ /^$match_courseid$/) {
                   7983:         my $chome=&homeserver($cnum,$udom,'true');
                   7984:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7985:             $uname = $cnum;
                   7986:         } else {
1.1038    raeburn  7987:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7988:         }
                   7989:     } else {
1.1038    raeburn  7990:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7991:     }
                   7992:     return $uname if ($uname =~ /^error/);
                   7993: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7994:     if (!defined($course_server)) {
                   7995:         if (defined(&domain($udom,'primary'))) {
                   7996:             $course_server = &domain($udom,'primary');
                   7997:         } else {
                   7998:             $course_server = $env{'user.home'}; 
                   7999:         }
                   8000:     }
                   8001:     my %host_servers =
                   8002:         &Apache::lonnet::get_servers($udom,'library');
                   8003:     unless ($host_servers{$course_server}) {
                   8004:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8005:     }
1.84      www      8006: # ------------------------------------------------------------- Make the course
                   8007:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8008:                       $course_server);
1.84      www      8009:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8010:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8011:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8012: 	return 'error: no such course';
                   8013:     }
1.271     www      8014: # ----------------------------------------------------------------- Course made
1.516     raeburn  8015: # log existence
1.1029    raeburn  8016:     my $now = time;
1.918     raeburn  8017:     my $newcourse = {
                   8018:                     $udom.'_'.$uname => {
1.921     raeburn  8019:                                      description => $description,
                   8020:                                      inst_code   => $inst_code,
                   8021:                                      owner       => $course_owner,
                   8022:                                      type        => $crstype,
1.1029    raeburn  8023:                                      creator     => $env{'user.name'}.':'.
                   8024:                                                     $env{'user.domain'},
                   8025:                                      created     => $now,
                   8026:                                      context     => $context,
1.918     raeburn  8027:                                                 },
                   8028:                     };
1.921     raeburn  8029:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8030: # set toplevel url
1.271     www      8031:     my $topurl=$url;
                   8032:     unless ($nonstandard) {
                   8033: # ------------------------------------------ For standard courses, make top url
                   8034:         my $mapurl=&clutter($url);
1.278     www      8035:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8036:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8037: <map>
                   8038: <resource id="1" type="start"></resource>
                   8039: <resource id="2" src="$mapurl"></resource>
                   8040: <resource id="3" type="finish"></resource>
                   8041: <link index="1" from="1" to="2"></link>
                   8042: <link index="2" from="2" to="3"></link>
                   8043: </map>
                   8044: ENDINITMAP
                   8045:         $topurl=&declutter(
1.638     albertel 8046:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8047:                           );
                   8048:     }
                   8049: # ----------------------------------------------------------- Write preferences
1.84      www      8050:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8051:                      ('description'              => $description,
                   8052:                       'url'                      => $topurl,
                   8053:                       'internal.creator'         => $env{'user.name'}.':'.
                   8054:                                                     $env{'user.domain'},
                   8055:                       'internal.created'         => $now,
                   8056:                       'internal.creationcontext' => $context)
                   8057:                     );
1.84      www      8058:     return '/'.$udom.'/'.$uname;
                   8059: }
                   8060: 
1.1011    raeburn  8061: # ------------------------------------------------------------------- Create ID
                   8062: sub generate_coursenum {
1.1038    raeburn  8063:     my ($udom,$crstype) = @_;
1.1011    raeburn  8064:     my $domdesc = &domain($udom);
                   8065:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8066:     my $first;
                   8067:     if ($crstype eq 'Community') {
                   8068:         $first = '0';
                   8069:     } else {
                   8070:         $first = int(1+rand(9)); 
                   8071:     } 
                   8072:     my $uname=$first.
1.1011    raeburn  8073:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8074:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8075:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8076: # ----------------------------------------------- Make sure that does not exist
                   8077:     my $uhome=&homeserver($uname,$udom,'true');
                   8078:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8079:         if ($crstype eq 'Community') {
                   8080:             $first = '0';
                   8081:         } else {
                   8082:             $first = int(1+rand(9));
                   8083:         }
                   8084:         $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:         $uhome=&homeserver($uname,$udom,'true');
                   8089:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8090:             return 'error: unable to generate unique course-ID';
                   8091:         }
                   8092:     }
                   8093:     return $uname;
                   8094: }
                   8095: 
1.813     albertel 8096: sub is_course {
1.1167    droeschl 8097:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8098:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8099: 
                   8100:     return unless $cdom and $cnum;
                   8101: 
                   8102:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8103:         '.');
                   8104: 
                   8105:     return unless exists($courses{$cdom.'_'.$cnum});
                   8106:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8107: }
                   8108: 
1.1015    raeburn  8109: sub store_userdata {
                   8110:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8111:     my $result;
1.1016    raeburn  8112:     if ($datakey ne '') {
1.1013    raeburn  8113:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8114:             if ($udom eq '' || $uname eq '') {
                   8115:                 $udom = $env{'user.domain'};
                   8116:                 $uname = $env{'user.name'};
                   8117:             }
                   8118:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8119:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8120:                 $result = 'error: no_host';
                   8121:             } else {
                   8122:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8123:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8124: 
                   8125:                 my $namevalue='';
                   8126:                 foreach my $key (keys(%{$storehash})) {
                   8127:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8128:                 }
                   8129:                 $namevalue=~s/\&$//;
1.1105    raeburn  8130:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8131:                                   $namevalue,$uhome);
1.1013    raeburn  8132:             }
                   8133:         } else {
                   8134:             $result = 'error: data to store was not a hash reference'; 
                   8135:         }
                   8136:     } else {
                   8137:         $result= 'error: invalid requestkey'; 
                   8138:     }
                   8139:     return $result;
                   8140: }
                   8141: 
1.21      www      8142: # ---------------------------------------------------------- Assign Custom Role
                   8143: 
                   8144: sub assigncustomrole {
1.957     raeburn  8145:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8146:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8147:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8148: }
                   8149: 
                   8150: # ----------------------------------------------------------------- Revoke Role
                   8151: 
                   8152: sub revokerole {
1.957     raeburn  8153:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8154:     my $now=time;
1.965     raeburn  8155:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8156: }
                   8157: 
                   8158: # ---------------------------------------------------------- Revoke Custom Role
                   8159: 
                   8160: sub revokecustomrole {
1.957     raeburn  8161:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8162:     my $now=time;
1.357     www      8163:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8164:            $deleteflag,$selfenroll,$context);
1.17      www      8165: }
                   8166: 
1.533     banghart 8167: # ------------------------------------------------------------ Disk usage
1.535     albertel 8168: sub diskusage {
1.955     raeburn  8169:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8170:     $directorypath =~ s/\/$//;
                   8171:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8172:                        .&escape($getpropath).':'.&escape($uname).':'
                   8173:                        .&escape($udom),homeserver($uname,$udom));
                   8174:     if ($listing eq 'unknown_cmd') {
                   8175:         if ($getpropath) {
                   8176:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8177:         }
                   8178:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8179:     }
1.514     albertel 8180:     return $listing;
1.512     banghart 8181: }
                   8182: 
1.566     banghart 8183: sub is_locked {
1.1096    raeburn  8184:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8185:     my @check;
                   8186:     my $is_locked;
1.1093    raeburn  8187:     push (@check,$file_name);
1.613     albertel 8188:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8189: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8190:     my ($tmp)=keys(%locked);
                   8191:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8192:     
1.566     banghart 8193:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8194:         $is_locked = 'false';
                   8195:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8196:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8197:                $is_locked = 'true';
1.1096    raeburn  8198:                if (ref($which) eq 'ARRAY') {
                   8199:                    push(@{$which},$entry);
                   8200:                } else {
                   8201:                    last;
                   8202:                }
1.745     raeburn  8203:            }
                   8204:        }
1.566     banghart 8205:     } else {
                   8206:         $is_locked = 'false';
                   8207:     }
1.1093    raeburn  8208:     return $is_locked;
1.566     banghart 8209: }
                   8210: 
1.759     albertel 8211: sub declutter_portfile {
                   8212:     my ($file) = @_;
1.833     albertel 8213:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8214:     return $file;
                   8215: }
                   8216: 
1.559     banghart 8217: # ------------------------------------------------------------- Mark as Read Only
                   8218: 
                   8219: sub mark_as_readonly {
                   8220:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8221:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8222:     my ($tmp)=keys(%current_permissions);
                   8223:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8224:     foreach my $file (@{$files}) {
1.759     albertel 8225: 	$file = &declutter_portfile($file);
1.561     banghart 8226:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8227:     }
1.613     albertel 8228:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8229:     return;
                   8230: }
                   8231: 
1.572     banghart 8232: # ------------------------------------------------------------Save Selected Files
                   8233: 
                   8234: sub save_selected_files {
                   8235:     my ($user, $path, @files) = @_;
                   8236:     my $filename = $user."savedfiles";
1.573     banghart 8237:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8238:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8239:     foreach my $file (@files) {
1.620     albertel 8240:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8241:     }
                   8242:     foreach my $file (@other_files) {
1.574     banghart 8243:         print (OUT $file."\n");
1.572     banghart 8244:     }
1.574     banghart 8245:     close (OUT);
1.572     banghart 8246:     return 'ok';
                   8247: }
                   8248: 
1.574     banghart 8249: sub clear_selected_files {
                   8250:     my ($user) = @_;
                   8251:     my $filename = $user."savedfiles";
1.1117    foxr     8252:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8253:     print (OUT undef);
                   8254:     close (OUT);
                   8255:     return ("ok");    
                   8256: }
                   8257: 
1.572     banghart 8258: sub files_in_path {
                   8259:     my ($user, $path) = @_;
                   8260:     my $filename = $user."savedfiles";
                   8261:     my %return_files;
1.1117    foxr     8262:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8263:     while (my $line_in = <IN>) {
1.574     banghart 8264:         chomp ($line_in);
                   8265:         my @paths_and_file = split (m!/!, $line_in);
                   8266:         my $file_part = pop (@paths_and_file);
                   8267:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8268:         $path_part.='/';
                   8269:         my $path_and_file = $path_part.$file_part;
                   8270:         if ($path_part eq $path) {
                   8271:             $return_files{$file_part}= 'selected';
                   8272:         }
                   8273:     }
1.574     banghart 8274:     close (IN);
                   8275:     return (\%return_files);
1.572     banghart 8276: }
                   8277: 
                   8278: # called in portfolio select mode, to show files selected NOT in current directory
                   8279: sub files_not_in_path {
                   8280:     my ($user, $path) = @_;
                   8281:     my $filename = $user."savedfiles";
                   8282:     my @return_files;
                   8283:     my $path_part;
1.1117    foxr     8284:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8285:     while (my $line = <IN>) {
1.572     banghart 8286:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8287:         my @paths_and_file = split(m|/|, $line);
                   8288:         my $file_part = pop(@paths_and_file);
                   8289:         chomp($file_part);
                   8290:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8291:         $path_part .= '/';
                   8292:         my $path_and_file = $path_part.$file_part;
                   8293:         if ($path_part ne $path) {
1.800     albertel 8294:             push(@return_files, ($path_and_file));
1.572     banghart 8295:         }
                   8296:     }
1.800     albertel 8297:     close(OUT);
1.574     banghart 8298:     return (@return_files);
1.572     banghart 8299: }
                   8300: 
1.745     raeburn  8301: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8302: 
1.745     raeburn  8303: sub get_portfile_permissions {
                   8304:     my ($domain,$user) = @_;
1.613     albertel 8305:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8306:     my ($tmp)=keys(%current_permissions);
                   8307:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8308:     return \%current_permissions;
                   8309: }
                   8310: 
                   8311: #---------------------------------------------Get portfolio file access controls
                   8312: 
1.749     raeburn  8313: sub get_access_controls {
1.745     raeburn  8314:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8315:     my %access;
                   8316:     my $real_file = $file;
                   8317:     $file =~ s/\.meta$//;
1.745     raeburn  8318:     if (defined($file)) {
1.749     raeburn  8319:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8320:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8321:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8322:             }
                   8323:         }
1.745     raeburn  8324:     } else {
1.749     raeburn  8325:         foreach my $key (keys(%{$current_permissions})) {
                   8326:             if ($key =~ /\0accesscontrol$/) {
                   8327:                 if (defined($group)) {
                   8328:                     if ($key !~ m-^\Q$group\E/-) {
                   8329:                         next;
                   8330:                     }
                   8331:                 }
                   8332:                 my ($fullpath) = split(/\0/,$key);
                   8333:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8334:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8335:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8336:                     }
                   8337:                 }
                   8338:             }
                   8339:         }
                   8340:     }
                   8341:     return %access;
                   8342: }
                   8343: 
                   8344: sub modify_access_controls {
                   8345:     my ($file_name,$changes,$domain,$user)=@_;
                   8346:     my ($outcome,$deloutcome);
                   8347:     my %store_permissions;
                   8348:     my %new_values;
                   8349:     my %new_control;
                   8350:     my %translation;
                   8351:     my @deletions = ();
                   8352:     my $now = time;
                   8353:     if (exists($$changes{'activate'})) {
                   8354:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8355:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8356:             my $numnew = scalar(@newitems);
                   8357:             for (my $i=0; $i<$numnew; $i++) {
                   8358:                 my $newkey = $newitems[$i];
                   8359:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8360:                 if ($newkey =~ /^\d+:/) { 
                   8361:                     $newkey =~ s/^(\d+)/$newid/;
                   8362:                     $translation{$1} = $newid;
                   8363:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8364:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8365:                     $translation{$1} = $newid;
                   8366:                 }
1.749     raeburn  8367:                 $new_values{$file_name."\0".$newkey} = 
                   8368:                                           $$changes{'activate'}{$newitems[$i]};
                   8369:                 $new_control{$newkey} = $now;
                   8370:             }
                   8371:         }
                   8372:     }
                   8373:     my %todelete;
                   8374:     my %changed_items;
                   8375:     foreach my $action ('delete','update') {
                   8376:         if (exists($$changes{$action})) {
                   8377:             if (ref($$changes{$action}) eq 'HASH') {
                   8378:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8379:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8380:                     if ($action eq 'delete') { 
                   8381:                         $todelete{$itemnum} = 1;
                   8382:                     } else {
                   8383:                         $changed_items{$itemnum} = $key;
                   8384:                     }
                   8385:                 }
1.745     raeburn  8386:             }
                   8387:         }
1.749     raeburn  8388:     }
                   8389:     # get lock on access controls for file.
                   8390:     my $lockhash = {
                   8391:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8392:                                                        ':'.$env{'user.domain'},
                   8393:                    }; 
                   8394:     my $tries = 0;
                   8395:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8396:    
                   8397:     while (($gotlock ne 'ok') && $tries <3) {
                   8398:         $tries ++;
                   8399:         sleep 1;
                   8400:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8401:     }
                   8402:     if ($gotlock eq 'ok') {
                   8403:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8404:         my ($tmp)=keys(%curr_permissions);
                   8405:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8406:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8407:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8408:             if (ref($curr_controls) eq 'HASH') {
                   8409:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8410:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8411:                     if (defined($todelete{$itemnum})) {
                   8412:                         push(@deletions,$file_name."\0".$control_item);
                   8413:                     } else {
                   8414:                         if (defined($changed_items{$itemnum})) {
                   8415:                             $new_control{$changed_items{$itemnum}} = $now;
                   8416:                             push(@deletions,$file_name."\0".$control_item);
                   8417:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8418:                         } else {
                   8419:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8420:                         }
                   8421:                     }
1.745     raeburn  8422:                 }
                   8423:             }
                   8424:         }
1.970     raeburn  8425:         my ($group);
                   8426:         if (&is_course($domain,$user)) {
                   8427:             ($group,my $file) = split(/\//,$file_name,2);
                   8428:         }
1.749     raeburn  8429:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8430:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8431:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8432:         #  remove lock
                   8433:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8434:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8435:         my $sqlresult =
1.970     raeburn  8436:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8437:                                     $group);
1.749     raeburn  8438:     } else {
                   8439:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8440:     }
1.749     raeburn  8441:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8442: }
                   8443: 
1.827     raeburn  8444: sub make_public_indefinitely {
                   8445:     my ($requrl) = @_;
                   8446:     my $now = time;
                   8447:     my $action = 'activate';
                   8448:     my $aclnum = 0;
                   8449:     if (&is_portfolio_url($requrl)) {
                   8450:         my (undef,$udom,$unum,$file_name,$group) =
                   8451:             &parse_portfolio_url($requrl);
                   8452:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8453:         my %access_controls = &get_access_controls($current_perms,
                   8454:                                                    $group,$file_name);
                   8455:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8456:             my ($num,$scope,$end,$start) = 
                   8457:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8458:             if ($scope eq 'public') {
                   8459:                 if ($start <= $now && $end == 0) {
                   8460:                     $action = 'none';
                   8461:                 } else {
                   8462:                     $action = 'update';
                   8463:                     $aclnum = $num;
                   8464:                 }
                   8465:                 last;
                   8466:             }
                   8467:         }
                   8468:         if ($action eq 'none') {
                   8469:              return 'ok';
                   8470:         } else {
                   8471:             my %changes;
                   8472:             my $newend = 0;
                   8473:             my $newstart = $now;
                   8474:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8475:             $changes{$action}{$newkey} = {
                   8476:                 type => 'public',
                   8477:                 time => {
                   8478:                     start => $newstart,
                   8479:                     end   => $newend,
                   8480:                 },
                   8481:             };
                   8482:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8483:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8484:             return $outcome;
                   8485:         }
                   8486:     } else {
                   8487:         return 'invalid';
                   8488:     }
                   8489: }
                   8490: 
1.745     raeburn  8491: #------------------------------------------------------Get Marked as Read Only
                   8492: 
                   8493: sub get_marked_as_readonly {
                   8494:     my ($domain,$user,$what,$group) = @_;
                   8495:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8496:     my @readonly_files;
1.629     banghart 8497:     my $cmp1=$what;
                   8498:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8499:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8500:         if (defined($group)) {
                   8501:             if ($file_name !~ m-^\Q$group\E/-) {
                   8502:                 next;
                   8503:             }
                   8504:         }
1.561     banghart 8505:         if (ref($value) eq "ARRAY"){
                   8506:             foreach my $stored_what (@{$value}) {
1.629     banghart 8507:                 my $cmp2=$stored_what;
1.759     albertel 8508:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8509:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8510:                 }
1.629     banghart 8511:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8512:                     push(@readonly_files, $file_name);
1.745     raeburn  8513:                     last;
1.563     banghart 8514:                 } elsif (!defined($what)) {
                   8515:                     push(@readonly_files, $file_name);
1.745     raeburn  8516:                     last;
1.561     banghart 8517:                 }
                   8518:             }
1.745     raeburn  8519:         }
1.561     banghart 8520:     }
                   8521:     return @readonly_files;
                   8522: }
1.577     banghart 8523: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8524: 
1.577     banghart 8525: sub get_marked_as_readonly_hash {
1.745     raeburn  8526:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8527:     my %readonly_files;
1.745     raeburn  8528:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8529:         if (defined($group)) {
                   8530:             if ($file_name !~ m-^\Q$group\E/-) {
                   8531:                 next;
                   8532:             }
                   8533:         }
1.577     banghart 8534:         if (ref($value) eq "ARRAY"){
                   8535:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8536:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8537:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8538:                         if ($lock_descriptor eq 'graded') {
                   8539:                             $readonly_files{$file_name} = 'graded';
                   8540:                         } elsif ($lock_descriptor eq 'handback') {
                   8541:                             $readonly_files{$file_name} = 'handback';
                   8542:                         } else {
                   8543:                             if (!exists($readonly_files{$file_name})) {
                   8544:                                 $readonly_files{$file_name} = 'locked';
                   8545:                             }
                   8546:                         }
1.745     raeburn  8547:                     }
1.750     banghart 8548:                 } 
1.577     banghart 8549:             }
                   8550:         } 
                   8551:     }
                   8552:     return %readonly_files;
                   8553: }
1.559     banghart 8554: # ------------------------------------------------------------ Unmark as Read Only
                   8555: 
                   8556: sub unmark_as_readonly {
1.629     banghart 8557:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8558:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8559:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8560:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8561:     my $symb_crs = $what;
                   8562:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8563:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8564:     my ($tmp)=keys(%current_permissions);
                   8565:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8566:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8567:     foreach my $file (@readonly_files) {
1.759     albertel 8568: 	my $clean_file = &declutter_portfile($file);
                   8569: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8570: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8571:         my @new_locks;
                   8572:         my @del_keys;
                   8573:         if (ref($current_locks) eq "ARRAY"){
                   8574:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8575:                 my $compare=$locker;
1.749     raeburn  8576:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8577:                     $compare=join('',@{$locker});
1.746     raeburn  8578:                     if ($compare ne $symb_crs) {
                   8579:                         push(@new_locks, $locker);
                   8580:                     }
1.563     banghart 8581:                 }
                   8582:             }
1.650     albertel 8583:             if (scalar(@new_locks) > 0) {
1.563     banghart 8584:                 $current_permissions{$file} = \@new_locks;
                   8585:             } else {
                   8586:                 push(@del_keys, $file);
1.613     albertel 8587:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8588:                 delete($current_permissions{$file});
1.563     banghart 8589:             }
                   8590:         }
1.561     banghart 8591:     }
1.613     albertel 8592:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8593:     return;
                   8594: }
1.512     banghart 8595: 
1.17      www      8596: # ------------------------------------------------------------ Directory lister
                   8597: 
                   8598: sub dirlist {
1.955     raeburn  8599:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8600:     $uri=~s/^\///;
                   8601:     $uri=~s/\/$//;
1.253     stredwic 8602:     my ($udom, $uname);
1.955     raeburn  8603:     if ($getuserdir) {
1.253     stredwic 8604:         $udom = $userdomain;
                   8605:         $uname = $username;
1.955     raeburn  8606:     } else {
                   8607:         (undef,$udom,$uname)=split(/\//,$uri);
                   8608:         if(defined($userdomain)) {
                   8609:             $udom = $userdomain;
                   8610:         }
                   8611:         if(defined($username)) {
                   8612:             $uname = $username;
                   8613:         }
1.253     stredwic 8614:     }
1.955     raeburn  8615:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8616: 
1.955     raeburn  8617:     $dirRoot = $perlvar{'lonDocRoot'};
                   8618:     if (defined($getpropath)) {
                   8619:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8620:         $dirRoot =~ s/\/$//;
1.955     raeburn  8621:     } elsif (defined($getuserdir)) {
                   8622:         my $subdir=$uname.'__';
                   8623:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8624:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8625:                    ."/$udom/$subdir/$uname";
                   8626:     } elsif (defined($alternateRoot)) {
                   8627:         $dirRoot = $alternateRoot;
1.751     banghart 8628:     }
1.253     stredwic 8629: 
                   8630:     if($udom) {
                   8631:         if($uname) {
1.1135    raeburn  8632:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8633:             if ($uhome eq 'no_host') {
                   8634:                 return ([],'no_host');
                   8635:             }
1.955     raeburn  8636:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8637:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8638:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8639:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8640:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8641:             } else {
                   8642:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8643:             }
1.605     matthew  8644:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8645:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8646:                 @listing_results = split(/:/,$listing);
                   8647:             } else {
                   8648:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8649:             }
1.1135    raeburn  8650:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8651:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8652:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8653:                 return ([],$listing);
                   8654:             } else {
                   8655:                 return (\@listing_results);
1.1135    raeburn  8656:             }
1.955     raeburn  8657:         } elsif(!$alternateRoot) {
1.1136    raeburn  8658:             my (%allusers,%listerror);
1.841     albertel 8659: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8660:  	    foreach my $tryserver (keys(%servers)) {
                   8661:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8662:                                   &escape($udom),$tryserver);
                   8663:                 if ($listing eq 'unknown_cmd') {
                   8664: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8665: 				      $udom, $tryserver);
                   8666:                 } else {
                   8667:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8668:                 }
1.841     albertel 8669: 		if ($listing eq 'unknown_cmd') {
                   8670: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8671: 				      $udom, $tryserver);
                   8672: 		    @listing_results = split(/:/,$listing);
                   8673: 		} else {
                   8674: 		    @listing_results =
                   8675: 			map { &unescape($_); } split(/:/,$listing);
                   8676: 		}
1.1136    raeburn  8677:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8678:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8679:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8680:                     $listerror{$tryserver} = $listing;
                   8681:                 } else {
1.841     albertel 8682: 		    foreach my $line (@listing_results) {
                   8683: 			my ($entry) = split(/&/,$line,2);
                   8684: 			$allusers{$entry} = 1;
                   8685: 		    }
                   8686: 		}
1.253     stredwic 8687:             }
1.1136    raeburn  8688:             my @alluserslist=();
1.800     albertel 8689:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8690:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8691:             }
1.1136    raeburn  8692:             return (\@alluserslist);
1.253     stredwic 8693:         } else {
1.1136    raeburn  8694:             return ([],'missing username');
1.253     stredwic 8695:         }
1.955     raeburn  8696:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8697:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8698:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8699:         return (\@all_domains);
1.955     raeburn  8700:     } else {
1.1136    raeburn  8701:         return ([],'missing domain');
1.275     stredwic 8702:     }
                   8703: }
                   8704: 
                   8705: # --------------------------------------------- GetFileTimestamp
                   8706: # This function utilizes dirlist and returns the date stamp for
                   8707: # when it was last modified.  It will also return an error of -1
                   8708: # if an error occurs
                   8709: 
                   8710: sub GetFileTimestamp {
1.955     raeburn  8711:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8712:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8713:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8714:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8715:                                     undef,$getuserdir);
                   8716:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8717:         return -1;
                   8718:     }
                   8719:     if (ref($fileref) eq 'ARRAY') {
                   8720:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8721:         # @stats contains first the filename, then the stat output
                   8722:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8723:     } else {
                   8724:         return -1;
1.253     stredwic 8725:     }
1.26      www      8726: }
                   8727: 
1.712     albertel 8728: sub stat_file {
                   8729:     my ($uri) = @_;
1.787     albertel 8730:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8731: 
1.955     raeburn  8732:     my ($udom,$uname,$file);
1.712     albertel 8733:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8734: 	($udom,$uname,$file) =
1.811     albertel 8735: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8736: 	$file = 'userfiles/'.$file;
                   8737:     }
                   8738:     if ($uri =~ m-^/res/-) {
                   8739: 	($udom,$uname) = 
1.807     albertel 8740: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8741: 	$file = $uri;
                   8742:     }
                   8743: 
                   8744:     if (!$udom || !$uname || !$file) {
                   8745: 	# unable to handle the uri
                   8746: 	return ();
                   8747:     }
1.956     raeburn  8748:     my $getpropath;
                   8749:     if ($file =~ /^userfiles\//) {
                   8750:         $getpropath = 1;
                   8751:     }
1.1136    raeburn  8752:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8753:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8754:         return ();
                   8755:     } else {
                   8756:         if (ref($listref) eq 'ARRAY') {
                   8757:             my @stats = split('&',$listref->[0]);
                   8758: 	    shift(@stats); #filename is first
                   8759: 	    return @stats;
                   8760:         }
1.712     albertel 8761:     }
                   8762:     return ();
                   8763: }
                   8764: 
1.26      www      8765: # -------------------------------------------------------- Value of a Condition
                   8766: 
1.713     albertel 8767: # gets the value of a specific preevaluated condition
                   8768: #    stored in the string  $env{user.state.<cid>}
                   8769: # or looks up a condition reference in the bighash and if if hasn't
                   8770: # already been evaluated recurses into docondval to get the value of
                   8771: # the condition, then memoizing it to 
                   8772: #   $env{user.state.<cid>.<condition>}
1.40      www      8773: sub directcondval {
                   8774:     my $number=shift;
1.620     albertel 8775:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8776: 	&Apache::lonuserstate::evalstate();
                   8777:     }
1.713     albertel 8778:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8779: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8780:     } elsif ($number =~ /^_/) {
                   8781: 	my $sub_condition;
                   8782: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8783: 		&GDBM_READER(),0640)) {
                   8784: 	    $sub_condition=$bighash{'conditions'.$number};
                   8785: 	    untie(%bighash);
                   8786: 	}
                   8787: 	my $value = &docondval($sub_condition);
1.949     raeburn  8788: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8789: 	return $value;
                   8790:     }
1.620     albertel 8791:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8792:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8793:     } else {
                   8794:        return 2;
                   8795:     }
                   8796: }
                   8797: 
1.713     albertel 8798: # get the collection of conditions for this resource
1.26      www      8799: sub condval {
                   8800:     my $condidx=shift;
1.54      www      8801:     my $allpathcond='';
1.713     albertel 8802:     foreach my $cond (split(/\|/,$condidx)) {
                   8803: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8804: 	    $allpathcond.=
                   8805: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8806: 	}
1.191     harris41 8807:     }
1.54      www      8808:     $allpathcond=~s/\|$//;
1.713     albertel 8809:     return &docondval($allpathcond);
                   8810: }
                   8811: 
                   8812: #evaluates an expression of conditions
                   8813: sub docondval {
                   8814:     my ($allpathcond) = @_;
                   8815:     my $result=0;
                   8816:     if ($env{'request.course.id'}
                   8817: 	&& defined($allpathcond)) {
                   8818: 	my $operand='|';
                   8819: 	my @stack;
                   8820: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8821: 	    if ($chunk eq '(') {
                   8822: 		push @stack,($operand,$result);
                   8823: 	    } elsif ($chunk eq ')') {
                   8824: 		my $before=pop @stack;
                   8825: 		if (pop @stack eq '&') {
                   8826: 		    $result=$result>$before?$before:$result;
                   8827: 		} else {
                   8828: 		    $result=$result>$before?$result:$before;
                   8829: 		}
                   8830: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8831: 		$operand=$chunk;
                   8832: 	    } else {
                   8833: 		my $new=directcondval($chunk);
                   8834: 		if ($operand eq '&') {
                   8835: 		    $result=$result>$new?$new:$result;
                   8836: 		} else {
                   8837: 		    $result=$result>$new?$result:$new;
                   8838: 		}
                   8839: 	    }
                   8840: 	}
1.26      www      8841:     }
                   8842:     return $result;
1.421     albertel 8843: }
                   8844: 
                   8845: # ---------------------------------------------------- Devalidate courseresdata
                   8846: 
                   8847: sub devalidatecourseresdata {
                   8848:     my ($coursenum,$coursedomain)=@_;
                   8849:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8850:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8851: }
                   8852: 
1.763     www      8853: 
1.200     www      8854: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8855: #
                   8856: #  Parameters:
                   8857: #      $coursenum    - Number of the course.
                   8858: #      $coursedomain - Domain at which the course was created.
                   8859: #  Returns:
                   8860: #     A hash of the course parameters along (I think) with timestamps
                   8861: #     and version info.
1.877     foxr     8862: 
1.624     albertel 8863: sub get_courseresdata {
                   8864:     my ($coursenum,$coursedomain)=@_;
1.200     www      8865:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8866:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8867:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8868:     my %dumpreply;
1.417     albertel 8869:     unless (defined($cached)) {
1.624     albertel 8870: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8871: 	$result=\%dumpreply;
1.251     albertel 8872: 	my ($tmp) = keys(%dumpreply);
                   8873: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8874: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8875: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8876: 	    return $tmp;
1.416     albertel 8877: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8878: 	    $result=undef;
1.599     albertel 8879: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8880: 	}
                   8881:     }
1.624     albertel 8882:     return $result;
                   8883: }
                   8884: 
1.633     albertel 8885: sub devalidateuserresdata {
                   8886:     my ($uname,$udom)=@_;
                   8887:     my $hashid="$udom:$uname";
                   8888:     &devalidate_cache_new('userres',$hashid);
                   8889: }
                   8890: 
1.624     albertel 8891: sub get_userresdata {
                   8892:     my ($uname,$udom)=@_;
                   8893:     #most student don\'t have any data set, check if there is some data
                   8894:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8895: 
                   8896:     my $hashid="$udom:$uname";
                   8897:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8898:     if (!defined($cached)) {
                   8899: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8900: 	$result=\%resourcedata;
                   8901: 	&do_cache_new('userres',$hashid,$result,600);
                   8902:     }
                   8903:     my ($tmp)=keys(%$result);
                   8904:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8905: 	return $result;
                   8906:     }
                   8907:     #error 2 occurs when the .db doesn't exist
                   8908:     if ($tmp!~/error: 2 /) {
1.672     albertel 8909: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8910: 		 " Trying to get resource data for ".
                   8911: 		 $uname." at ".$udom.": ".
                   8912: 		 $tmp."</font>");
                   8913:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8914: 	#&EXT_cache_set($udom,$uname);
                   8915: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8916: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8917:     }
                   8918:     return $tmp;
                   8919: }
1.879     foxr     8920: #----------------------------------------------- resdata - return resource data
                   8921: #  Purpose:
                   8922: #    Return resource data for either users or for a course.
                   8923: #  Parameters:
                   8924: #     $name      - Course/user name.
                   8925: #     $domain    - Name of the domain the user/course is registered on.
                   8926: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8927: #     @which     - Array of names of resources desired.
                   8928: #  Returns:
                   8929: #     The value of the first reasource in @which that is found in the
                   8930: #     resource hash.
                   8931: #  Exceptional Conditions:
                   8932: #     If the $type passed in is not valid (not the string 'course' or 
                   8933: #     'user', an undefined  reference is returned.
                   8934: #     If none of the resources are found, an undef is returned
1.624     albertel 8935: sub resdata {
                   8936:     my ($name,$domain,$type,@which)=@_;
                   8937:     my $result;
                   8938:     if ($type eq 'course') {
                   8939: 	$result=&get_courseresdata($name,$domain);
                   8940:     } elsif ($type eq 'user') {
                   8941: 	$result=&get_userresdata($name,$domain);
                   8942:     }
                   8943:     if (!ref($result)) { return $result; }    
1.251     albertel 8944:     foreach my $item (@which) {
1.927     albertel 8945: 	if (defined($result->{$item->[0]})) {
                   8946: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8947: 	}
1.250     albertel 8948:     }
1.291     albertel 8949:     return undef;
1.200     www      8950: }
                   8951: 
1.379     matthew  8952: #
                   8953: # EXT resource caching routines
                   8954: #
                   8955: 
                   8956: sub clear_EXT_cache_status {
1.383     albertel 8957:     &delenv('cache.EXT.');
1.379     matthew  8958: }
                   8959: 
                   8960: sub EXT_cache_status {
                   8961:     my ($target_domain,$target_user) = @_;
1.383     albertel 8962:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8963:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8964:         # We know already the user has no data
                   8965:         return 1;
                   8966:     } else {
                   8967:         return 0;
                   8968:     }
                   8969: }
                   8970: 
                   8971: sub EXT_cache_set {
                   8972:     my ($target_domain,$target_user) = @_;
1.383     albertel 8973:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8974:     #&appenv({$cachename => time});
1.379     matthew  8975: }
                   8976: 
1.28      www      8977: # --------------------------------------------------------- Value of a Variable
1.58      www      8978: sub EXT {
1.715     albertel 8979: 
1.395     albertel 8980:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8981:     unless ($varname) { return ''; }
1.218     albertel 8982:     #get real user name/domain, courseid and symb
                   8983:     my $courseid;
1.359     albertel 8984:     my $publicuser;
1.427     www      8985:     if ($symbparm) {
                   8986: 	$symbparm=&get_symb_from_alias($symbparm);
                   8987:     }
1.218     albertel 8988:     if (!($uname && $udom)) {
1.790     albertel 8989:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8990:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8991:     } else {
1.620     albertel 8992: 	$courseid=$env{'request.course.id'};
1.218     albertel 8993:     }
1.48      www      8994:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8995:     my $rest;
1.320     albertel 8996:     if (defined($therest[0])) {
1.48      www      8997:        $rest=join('.',@therest);
                   8998:     } else {
                   8999:        $rest='';
                   9000:     }
1.320     albertel 9001: 
1.57      www      9002:     my $qualifierrest=$qualifier;
                   9003:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9004:     my $spacequalifierrest=$space;
                   9005:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9006:     if ($realm eq 'user') {
1.48      www      9007: # --------------------------------------------------------------- user.resource
                   9008: 	if ($space eq 'resource') {
1.651     albertel 9009: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9010: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9011: 		 &&
1.744     albertel 9012: 		 ($symbparm eq &symbread()) ) {	
                   9013: 		# if we are in the middle of processing the resource the
                   9014: 		# get the value we are planning on committing
                   9015:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9016:                     return $Apache::lonhomework::results{$qualifierrest};
                   9017:                 } else {
                   9018:                     return $Apache::lonhomework::history{$qualifierrest};
                   9019:                 }
1.335     albertel 9020: 	    } else {
1.359     albertel 9021: 		my %restored;
1.620     albertel 9022: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9023: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9024: 		} else {
                   9025: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9026: 		}
1.335     albertel 9027: 		return $restored{$qualifierrest};
                   9028: 	    }
1.48      www      9029: # ----------------------------------------------------------------- user.access
                   9030:         } elsif ($space eq 'access') {
1.218     albertel 9031: 	    # FIXME - not supporting calls for a specific user
1.48      www      9032:             return &allowed($qualifier,$rest);
                   9033: # ------------------------------------------ user.preferences, user.environment
                   9034:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9035: 	    if (($uname eq $env{'user.name'}) &&
                   9036: 		($udom eq $env{'user.domain'})) {
                   9037: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9038: 	    } else {
1.359     albertel 9039: 		my %returnhash;
                   9040: 		if (!$publicuser) {
                   9041: 		    %returnhash=&userenvironment($udom,$uname,
                   9042: 						 $qualifierrest);
                   9043: 		}
1.218     albertel 9044: 		return $returnhash{$qualifierrest};
                   9045: 	    }
1.48      www      9046: # ----------------------------------------------------------------- user.course
                   9047:         } elsif ($space eq 'course') {
1.218     albertel 9048: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9049:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9050: # ------------------------------------------------------------------- user.role
                   9051:         } elsif ($space eq 'role') {
1.218     albertel 9052: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9053:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9054:             if ($qualifier eq 'value') {
                   9055: 		return $role;
                   9056:             } elsif ($qualifier eq 'extent') {
                   9057:                 return $where;
                   9058:             }
                   9059: # ----------------------------------------------------------------- user.domain
                   9060:         } elsif ($space eq 'domain') {
1.218     albertel 9061:             return $udom;
1.48      www      9062: # ------------------------------------------------------------------- user.name
                   9063:         } elsif ($space eq 'name') {
1.218     albertel 9064:             return $uname;
1.48      www      9065: # ---------------------------------------------------- Any other user namespace
1.29      www      9066:         } else {
1.359     albertel 9067: 	    my %reply;
                   9068: 	    if (!$publicuser) {
                   9069: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9070: 	    }
                   9071: 	    return $reply{$qualifierrest};
1.48      www      9072:         }
1.236     www      9073:     } elsif ($realm eq 'query') {
                   9074: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9075:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9076: 						[$spacequalifierrest]);
1.620     albertel 9077: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9078:    } elsif ($realm eq 'request') {
1.48      www      9079: # ------------------------------------------------------------- request.browser
                   9080:         if ($space eq 'browser') {
1.1145    bisitz   9081:             return $env{'browser.'.$qualifier};
1.57      www      9082: # ------------------------------------------------------------ request.filename
                   9083:         } else {
1.620     albertel 9084:             return $env{'request.'.$spacequalifierrest};
1.29      www      9085:         }
1.28      www      9086:     } elsif ($realm eq 'course') {
1.48      www      9087: # ---------------------------------------------------------- course.description
1.620     albertel 9088:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9089:     } elsif ($realm eq 'resource') {
1.165     www      9090: 
1.620     albertel 9091: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9092: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9093: 	}
1.693     albertel 9094: 
                   9095: 	if ($space eq 'title') {
                   9096: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9097: 	    return &gettitle($symbparm);
                   9098: 	}
                   9099: 	
                   9100: 	if ($space eq 'map') {
                   9101: 	    my ($map) = &decode_symb($symbparm);
                   9102: 	    return &symbread($map);
                   9103: 	}
1.905     albertel 9104: 	if ($space eq 'filename') {
                   9105: 	    if ($symbparm) {
                   9106: 		return &clutter((&decode_symb($symbparm))[2]);
                   9107: 	    }
                   9108: 	    return &hreflocation('',$env{'request.filename'});
                   9109: 	}
1.693     albertel 9110: 
                   9111: 	my ($section, $group, @groups);
1.593     albertel 9112: 	my ($courselevelm,$courselevel);
1.539     albertel 9113: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9114: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9115: 
1.218     albertel 9116: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9117: 
1.60      www      9118: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9119: 	    my $symbp=$symbparm;
1.735     albertel 9120: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9121: 
                   9122: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9123: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9124: 
1.620     albertel 9125: 	    if (($env{'user.name'} eq $uname) &&
                   9126: 		($env{'user.domain'} eq $udom)) {
                   9127: 		$section=$env{'request.course.sec'};
1.733     raeburn  9128:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9129:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9130: 	    } else {
1.539     albertel 9131: 		if (! defined($usection)) {
1.551     albertel 9132: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9133: 		} else {
                   9134: 		    $section = $usection;
                   9135: 		}
1.733     raeburn  9136:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9137: 	    }
                   9138: 
                   9139: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9140: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9141: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9142: 
1.593     albertel 9143: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9144: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9145: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9146: 
1.60      www      9147: # ----------------------------------------------------------- first, check user
1.624     albertel 9148: 
                   9149: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9150: 				       ([$courselevelr,'resource'],
                   9151: 					[$courselevelm,'map'     ],
                   9152: 					[$courselevel, 'course'  ]));
1.931     albertel 9153: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9154: 
1.594     albertel 9155: # ------------------------------------------------ second, check some of course
1.684     raeburn  9156:             my $coursereply;
1.691     raeburn  9157:             if (@groups > 0) {
                   9158:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9159:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9160:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9161:             }
1.96      www      9162: 
1.684     raeburn  9163: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9164: 				  $env{'course.'.$courseid.'.domain'},
                   9165: 				  'course',
                   9166: 				  ([$seclevelr,   'resource'],
                   9167: 				   [$seclevelm,   'map'     ],
                   9168: 				   [$seclevel,    'course'  ],
                   9169: 				   [$courselevelr,'resource']));
                   9170: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9171: 
1.60      www      9172: # ------------------------------------------------------ third, check map parms
1.218     albertel 9173: 	    my %parmhash=();
                   9174: 	    my $thisparm='';
                   9175: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9176: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9177: 		    &GDBM_READER(),0640)) {
1.218     albertel 9178: 		$thisparm=$parmhash{$symbparm};
                   9179: 		untie(%parmhash);
                   9180: 	    }
1.927     albertel 9181: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9182: 	}
1.594     albertel 9183: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9184: 
1.218     albertel 9185: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9186: 	my $filename;
                   9187: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9188: 	if ($symbparm) {
1.409     www      9189: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9190: 	} else {
1.620     albertel 9191: 	    $filename=$env{'request.filename'};
1.282     albertel 9192: 	}
                   9193: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9194: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9195: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9196: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9197: 
1.927     albertel 9198: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9199: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9200: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9201: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9202: 				     $env{'course.'.$courseid.'.domain'},
                   9203: 				     'course',
1.927     albertel 9204: 				     ([$courselevelm,'map'   ],
                   9205: 				      [$courselevel, 'course']));
                   9206: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9207: 	}
1.145     www      9208: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9209: 	unless ($space eq '0') {
1.336     albertel 9210: 	    my @parts=split(/_/,$space);
                   9211: 	    my $id=pop(@parts);
                   9212: 	    my $part=join('_',@parts);
                   9213: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9214: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9215: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9216: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9217: 	}
1.395     albertel 9218: 	if ($recurse) { return undef; }
                   9219: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9220: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9221: # ---------------------------------------------------- Any other user namespace
                   9222:     } elsif ($realm eq 'environment') {
                   9223: # ----------------------------------------------------------------- environment
1.620     albertel 9224: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9225: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9226: 	} else {
1.770     albertel 9227: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9228: 		return '';
                   9229: 	    }
1.219     albertel 9230: 	    my %returnhash=&userenvironment($udom,$uname,
                   9231: 					    $spacequalifierrest);
                   9232: 	    return $returnhash{$spacequalifierrest};
                   9233: 	}
1.28      www      9234:     } elsif ($realm eq 'system') {
1.48      www      9235: # ----------------------------------------------------------------- system.time
                   9236: 	if ($space eq 'time') {
                   9237: 	    return time;
                   9238:         }
1.696     albertel 9239:     } elsif ($realm eq 'server') {
                   9240: # ----------------------------------------------------------------- system.time
                   9241: 	if ($space eq 'name') {
                   9242: 	    return $ENV{'SERVER_NAME'};
                   9243:         }
1.28      www      9244:     }
1.48      www      9245:     return '';
1.61      www      9246: }
                   9247: 
1.927     albertel 9248: sub get_reply {
                   9249:     my ($reply_value) = @_;
1.940     raeburn  9250:     if (ref($reply_value) eq 'ARRAY') {
                   9251:         if (wantarray) {
                   9252: 	    return @$reply_value;
                   9253:         }
                   9254:         return $reply_value->[0];
                   9255:     } else {
                   9256:         return $reply_value;
1.927     albertel 9257:     }
                   9258: }
                   9259: 
1.691     raeburn  9260: sub check_group_parms {
                   9261:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9262:     my @groupitems = ();
                   9263:     my $resultitem;
1.927     albertel 9264:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9265:     foreach my $group (@{$groups}) {
                   9266:         foreach my $level (@levels) {
1.927     albertel 9267:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9268:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9269:         }
                   9270:     }
                   9271:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9272:                             $env{'course.'.$courseid.'.domain'},
                   9273:                                      'course',@groupitems);
                   9274:     return $coursereply;
                   9275: }
                   9276: 
                   9277: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9278:     my ($courseid,@groups) = @_;
                   9279:     @groups = sort(@groups);
1.691     raeburn  9280:     return @groups;
                   9281: }
                   9282: 
1.395     albertel 9283: sub packages_tab_default {
                   9284:     my ($uri,$varname)=@_;
                   9285:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9286: 
                   9287:     my (@extension,@specifics,$do_default);
                   9288:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9289: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9290: 	if ($pack_type eq 'default') {
                   9291: 	    $do_default=1;
                   9292: 	} elsif ($pack_type eq 'extension') {
                   9293: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9294: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9295: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9296: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9297: 	}
                   9298:     }
                   9299:     # first look for a package that matches the requested part id
                   9300:     foreach my $package (@specifics) {
                   9301: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9302: 	next if ($pack_part ne $part);
                   9303: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9304: 	    return $packagetab{"$pack_type&$name&default"};
                   9305: 	}
                   9306:     }
                   9307:     # look for any possible matching non extension_ package
                   9308:     foreach my $package (@specifics) {
                   9309: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9310: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9311: 	    return $packagetab{"$pack_type&$name&default"};
                   9312: 	}
1.585     albertel 9313: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9314: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9315: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9316: 	}
                   9317:     }
1.738     albertel 9318:     # look for any posible extension_ match
                   9319:     foreach my $package (@extension) {
                   9320: 	my ($package,$pack_type)=@{$package};
                   9321: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9322: 	    return $packagetab{"$pack_type&$name&default"};
                   9323: 	}
                   9324: 	if (defined($packagetab{$package."&$name&default"})) {
                   9325: 	    return $packagetab{$package."&$name&default"};
                   9326: 	}
                   9327:     }
                   9328:     # look for a global default setting
                   9329:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9330: 	return $packagetab{"default&$name&default"};
                   9331:     }
1.395     albertel 9332:     return undef;
                   9333: }
                   9334: 
1.334     albertel 9335: sub add_prefix_and_part {
                   9336:     my ($prefix,$part)=@_;
                   9337:     my $keyroot;
                   9338:     if (defined($prefix) && $prefix !~ /^__/) {
                   9339: 	# prefix that has a part already
                   9340: 	$keyroot=$prefix;
                   9341:     } elsif (defined($prefix)) {
                   9342: 	# prefix that is missing a part
                   9343: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9344:     } else {
                   9345: 	# no prefix at all
                   9346: 	if (defined($part)) { $keyroot='_'.$part; }
                   9347:     }
                   9348:     return $keyroot;
                   9349: }
                   9350: 
1.71      www      9351: # ---------------------------------------------------------------- Get metadata
                   9352: 
1.599     albertel 9353: my %metaentry;
1.1070    www      9354: my %importedpartids;
1.71      www      9355: sub metadata {
1.176     www      9356:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9357:     $uri=&declutter($uri);
1.288     albertel 9358:     # if it is a non metadata possible uri return quickly
1.529     albertel 9359:     if (($uri eq '') || 
                   9360: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9361: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9362:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9363: 	return undef;
                   9364:     }
1.1140    www      9365:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9366: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9367: 	return undef;
1.288     albertel 9368:     }
1.73      www      9369:     my $filename=$uri;
                   9370:     $uri=~s/\.meta$//;
1.172     www      9371: #
                   9372: # Is the metadata already cached?
1.177     www      9373: # Look at timestamp of caching
1.172     www      9374: # Everything is cached by the main uri, libraries are never directly cached
                   9375: #
1.428     albertel 9376:     if (!defined($liburi)) {
1.599     albertel 9377: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9378: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9379:     }
                   9380:     {
1.1069    www      9381: # Imported parts would go here
1.1070    www      9382:         my %importedids=();
                   9383:         my @origfileimportpartids=();
1.1069    www      9384:         my $importedparts=0;
1.172     www      9385: #
                   9386: # Is this a recursive call for a library?
                   9387: #
1.599     albertel 9388: #	if (! exists($metacache{$uri})) {
                   9389: #	    $metacache{$uri}={};
                   9390: #	}
1.924     albertel 9391: 	my $cachetime = 60*60;
1.171     www      9392:         if ($liburi) {
                   9393: 	    $liburi=&declutter($liburi);
                   9394:             $filename=$liburi;
1.401     bowersj2 9395:         } else {
1.599     albertel 9396: 	    &devalidate_cache_new('meta',$uri);
                   9397: 	    undef(%metaentry);
1.401     bowersj2 9398: 	}
1.140     www      9399:         my %metathesekeys=();
1.73      www      9400:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9401: 	my $metastring;
1.1140    www      9402: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9403: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9404: 	    $metastring = 
1.929     albertel 9405: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9406: 					  ('grade_target' => 'meta'));
                   9407: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9408: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9409:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9410: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9411: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9412: 	    $metastring=&getfile($file);
1.489     albertel 9413: 	}
1.208     albertel 9414:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9415:         my $token;
1.140     www      9416:         undef %metathesekeys;
1.71      www      9417:         while ($token=$parser->get_token) {
1.339     albertel 9418: 	    if ($token->[0] eq 'S') {
                   9419: 		if (defined($token->[2]->{'package'})) {
1.172     www      9420: #
                   9421: # This is a package - get package info
                   9422: #
1.339     albertel 9423: 		    my $package=$token->[2]->{'package'};
                   9424: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9425: 		    if (defined($token->[2]->{'id'})) { 
                   9426: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9427: 		    }
1.599     albertel 9428: 		    if ($metaentry{':packages'}) {
                   9429: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9430: 		    } else {
1.599     albertel 9431: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9432: 		    }
1.736     albertel 9433: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9434: 			my $part=$keyroot;
                   9435: 			$part=~s/^\_//;
1.736     albertel 9436: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9437: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9438: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9439: 			    # ignore package.tab specified default values
                   9440:                             # here &package_tab_default() will fetch those
                   9441: 			    if ($subp eq 'default') { next; }
1.736     albertel 9442: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9443: 			    my $unikey;
                   9444: 			    if ($pack =~ /_0$/) {
                   9445: 				$unikey='parameter_0_'.$name;
                   9446: 				$part=0;
                   9447: 			    } else {
                   9448: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9449: 			    }
1.339     albertel 9450: 			    if ($subp eq 'display') {
                   9451: 				$value.=' [Part: '.$part.']';
                   9452: 			    }
1.599     albertel 9453: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9454: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9455: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9456: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9457: 			    }
1.599     albertel 9458: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9459: 				$metaentry{':'.$unikey}=
                   9460: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9461: 			    }
1.339     albertel 9462: 			}
                   9463: 		    }
                   9464: 		} else {
1.172     www      9465: #
                   9466: # This is not a package - some other kind of start tag
1.339     albertel 9467: #
                   9468: 		    my $entry=$token->[1];
1.1068    www      9469: 		    my $unikey='';
1.175     www      9470: 
1.339     albertel 9471: 		    if ($entry eq 'import') {
1.175     www      9472: #
                   9473: # Importing a library here
1.339     albertel 9474: #
1.1067    www      9475:                         my $location=$parser->get_text('/import');
                   9476:                         my $dir=$filename;
                   9477:                         $dir=~s|[^/]*$||;
                   9478:                         $location=&filelocation($dir,$location);
1.1069    www      9479:                        
1.1068    www      9480:                         my $importmode=$token->[2]->{'importmode'};
                   9481:                         if ($importmode eq 'problem') {
1.1069    www      9482: # Import as problem/response
1.1068    www      9483:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9484:                         } elsif ($importmode eq 'part') {
                   9485: # Import as part(s)
1.1069    www      9486:                            $importedparts=1;
                   9487: # We need to get the original file and the imported file to get the part order correct
                   9488: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9489: # Load and inspect original file
1.1070    www      9490:                            if ($#origfileimportpartids<0) {
                   9491:                               undef(%importedpartids);
                   9492:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9493:                               my $origfile=&getfile($origfilelocation);
                   9494:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9495:                            }
                   9496: 
1.1069    www      9497: # Load and inspect imported file
                   9498:                            my $impfile=&getfile($location);
                   9499:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9500:                            if ($#impfilepartids>=0) {
                   9501: # This problem had parts
1.1070    www      9502:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9503:                            } else {
                   9504: # Importing by turning a single problem into a problem part
                   9505: # It gets the import-tags ID as part-ID
                   9506:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9507:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9508:                            }
1.1068    www      9509:                         } else {
                   9510: # Normal import
                   9511:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9512:                            if (defined($token->[2]->{'id'})) {
                   9513:                               $unikey.='_'.$token->[2]->{'id'};
                   9514:                            }
1.1067    www      9515:                         }
                   9516: 
1.339     albertel 9517: 			if ($depthcount<20) {
1.736     albertel 9518: 			    my $metadata = 
                   9519: 				&metadata($uri,'keys', $location,$unikey,
                   9520: 					  $depthcount+1);
                   9521: 			    foreach my $meta (split(',',$metadata)) {
                   9522: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9523: 				$metathesekeys{$meta}=1;
1.339     albertel 9524: 			    }
1.1068    www      9525: 			
                   9526:                         }
1.1067    www      9527: 		    } else {
                   9528: #
                   9529: # Not importing, some other kind of non-package, non-library start tag
                   9530: # 
                   9531:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9532:                         if (defined($token->[2]->{'id'})) {
                   9533:                             $unikey.='_'.$token->[2]->{'id'};
                   9534:                         }
1.339     albertel 9535: 			if (defined($token->[2]->{'name'})) { 
                   9536: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9537: 			}
                   9538: 			$metathesekeys{$unikey}=1;
1.736     albertel 9539: 			foreach my $param (@{$token->[3]}) {
                   9540: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9541: 				$token->[2]->{$param};
1.339     albertel 9542: 			}
                   9543: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9544: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9545: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9546: 		 # only ws inside the tag, and not in default, so use default
                   9547: 		 # as value
1.599     albertel 9548: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9549: 			} elsif ( $internaltext =~ /\S/ ) {
                   9550: 		  # something interesting inside the tag
                   9551: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9552: 			} else {
1.908     albertel 9553: 		  # no interesting values, don't set a default
1.339     albertel 9554: 			}
1.172     www      9555: # end of not-a-package not-a-library import
1.339     albertel 9556: 		    }
1.172     www      9557: # end of not-a-package start tag
1.339     albertel 9558: 		}
1.172     www      9559: # the next is the end of "start tag"
1.339     albertel 9560: 	    }
                   9561: 	}
1.483     albertel 9562: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9563: 	$extension = lc($extension);
                   9564: 	if ($extension eq 'htm') { $extension='html'; }
                   9565: 
1.737     albertel 9566: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9567: 	    #no specific packages #how's our extension
                   9568: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9569: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9570: 					 \%metathesekeys);
                   9571: 	}
1.883     albertel 9572: 
                   9573: 	if (!exists($metaentry{':packages'})
                   9574: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9575: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9576: 		#no specific packages well let's get default then
                   9577: 		if ($key!~/^default&/) { next; }
1.488     albertel 9578: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9579: 					     \%metathesekeys);
                   9580: 	    }
                   9581: 	}
1.338     www      9582: # are there custom rights to evaluate
1.599     albertel 9583: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9584: 
1.338     www      9585:     #
                   9586:     # Importing a rights file here
1.339     albertel 9587:     #
                   9588: 	    unless ($depthcount) {
1.599     albertel 9589: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9590: 		my $dir=$filename;
                   9591: 		$dir=~s|[^/]*$||;
                   9592: 		$location=&filelocation($dir,$location);
1.736     albertel 9593: 		my $rights_metadata =
                   9594: 		    &metadata($uri,'keys',$location,'_rights',
                   9595: 			      $depthcount+1);
                   9596: 		foreach my $rights (split(',',$rights_metadata)) {
                   9597: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9598: 		    $metathesekeys{$rights}=1;
1.339     albertel 9599: 		}
                   9600: 	    }
                   9601: 	}
1.737     albertel 9602: 	# uniqifiy package listing
                   9603: 	my %seen;
                   9604: 	my @uniq_packages =
                   9605: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9606: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9607: 
1.1070    www      9608:         if ($importedparts) {
                   9609: # We had imported parts and need to rebuild partorder
                   9610:            $metaentry{':partorder'}='';
                   9611:            $metathesekeys{'partorder'}=1;
                   9612:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9613:                if ($origfileimportpartids[$index] eq 'part') {
                   9614: # original part, part of the problem
                   9615:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9616:                } else {
                   9617: # we have imported parts at this position
                   9618:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9619:                }
                   9620:            }
                   9621:            $metaentry{':partorder'}=~s/^\,//;
                   9622:         }
                   9623: 
1.737     albertel 9624: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9625: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9626: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9627: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9628: # this is the end of "was not already recently cached
1.71      www      9629:     }
1.599     albertel 9630:     return $metaentry{':'.$what};
1.261     albertel 9631: }
                   9632: 
1.488     albertel 9633: sub metadata_create_package_def {
1.483     albertel 9634:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9635:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9636:     if ($subp eq 'default') { next; }
                   9637:     
1.599     albertel 9638:     if (defined($metaentry{':packages'})) {
                   9639: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9640:     } else {
1.599     albertel 9641: 	$metaentry{':packages'}=$package;
1.483     albertel 9642:     }
                   9643:     my $value=$packagetab{$key};
                   9644:     my $unikey;
                   9645:     $unikey='parameter_0_'.$name;
1.599     albertel 9646:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9647:     $$metathesekeys{$unikey}=1;
1.599     albertel 9648:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9649: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9650:     }
1.599     albertel 9651:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9652: 	$metaentry{':'.$unikey}=
                   9653: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9654:     }
                   9655: }
                   9656: 
1.261     albertel 9657: sub metadata_generate_part0 {
                   9658:     my ($metadata,$metacache,$uri) = @_;
                   9659:     my %allnames;
1.737     albertel 9660:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9661: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9662: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9663: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9664: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9665: 	    $allnames{$name}=$part;
                   9666: 	  }
                   9667: 	}
                   9668:     }
                   9669:     foreach my $name (keys(%allnames)) {
                   9670:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9671:       my $key=":parameter_0_$name";
1.261     albertel 9672:       $$metacache{"$key.part"}='0';
                   9673:       $$metacache{"$key.name"}=$name;
1.428     albertel 9674:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9675: 					   $allnames{$name}.'_'.$name.
                   9676: 					   '.type'};
1.428     albertel 9677:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9678: 			     '.display'};
1.644     www      9679:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9680:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9681:       $$metacache{"$key.display"}=$olddis;
                   9682:     }
1.71      www      9683: }
                   9684: 
1.764     albertel 9685: # ------------------------------------------------------ Devalidate title cache
                   9686: 
                   9687: sub devalidate_title_cache {
                   9688:     my ($url)=@_;
                   9689:     if (!$env{'request.course.id'}) { return; }
                   9690:     my $symb=&symbread($url);
                   9691:     if (!$symb) { return; }
                   9692:     my $key=$env{'request.course.id'}."\0".$symb;
                   9693:     &devalidate_cache_new('title',$key);
                   9694: }
                   9695: 
1.1014    droeschl 9696: # ------------------------------------------------- Get the title of a course
                   9697: 
                   9698: sub current_course_title {
                   9699:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9700: }
1.301     www      9701: # ------------------------------------------------- Get the title of a resource
                   9702: 
                   9703: sub gettitle {
                   9704:     my $urlsymb=shift;
                   9705:     my $symb=&symbread($urlsymb);
1.534     albertel 9706:     if ($symb) {
1.620     albertel 9707: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9708: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9709: 	if (defined($cached)) { 
                   9710: 	    return $result;
                   9711: 	}
1.534     albertel 9712: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9713: 	my $title='';
1.907     albertel 9714: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9715: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9716: 	} else {
                   9717: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9718: 		    &GDBM_READER(),0640)) {
                   9719: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9720: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9721: 		untie(%bighash);
                   9722: 	    }
1.534     albertel 9723: 	}
                   9724: 	$title=~s/\&colon\;/\:/gs;
                   9725: 	if ($title) {
1.1159    www      9726: # Remember both $symb and $title for dynamic metadata
                   9727:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9728:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9729: # Cache this title and then return it
1.599     albertel 9730: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9731: 	}
                   9732: 	$urlsymb=$url;
                   9733:     }
                   9734:     my $title=&metadata($urlsymb,'title');
                   9735:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9736:     return $title;
1.301     www      9737: }
1.613     albertel 9738: 
1.614     albertel 9739: sub get_slot {
                   9740:     my ($which,$cnum,$cdom)=@_;
                   9741:     if (!$cnum || !$cdom) {
1.790     albertel 9742: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9743: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9744: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9745:     }
1.703     albertel 9746:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9747:     my %slotinfo;
                   9748:     if (exists($remembered{$key})) {
                   9749: 	$slotinfo{$which} = $remembered{$key};
                   9750:     } else {
                   9751: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9752: 	&Apache::lonhomework::showhash(%slotinfo);
                   9753: 	my ($tmp)=keys(%slotinfo);
                   9754: 	if ($tmp=~/^error:/) { return (); }
                   9755: 	$remembered{$key} = $slotinfo{$which};
                   9756:     }
1.616     albertel 9757:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9758: 	return %{$slotinfo{$which}};
                   9759:     }
                   9760:     return $slotinfo{$which};
1.614     albertel 9761: }
1.1150    raeburn  9762: 
                   9763: sub get_reservable_slots {
                   9764:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9765:     my $now = time;
                   9766:     my $reservable_info;
                   9767:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9768:     if (exists($remembered{$key})) {
                   9769:         $reservable_info = $remembered{$key};
                   9770:     } else {
                   9771:         my %resv;
                   9772:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9773:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9774:         $reservable_info = \%resv;
                   9775:         $remembered{$key} = $reservable_info;
                   9776:     }
                   9777:     return $reservable_info;
                   9778: }
                   9779: 
                   9780: sub get_course_slots {
                   9781:     my ($cnum,$cdom) = @_;
                   9782:     my $hashid=$cnum.':'.$cdom;
                   9783:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9784:     if (defined($cached)) {
                   9785:         if (ref($result) eq 'HASH') {
                   9786:             return %{$result};
                   9787:         }
                   9788:     } else {
                   9789:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9790:         my ($tmp) = keys(%slots);
                   9791:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9792:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9793:             return %slots;
                   9794:         }
                   9795:     }
                   9796:     return;
                   9797: }
                   9798: 
                   9799: sub devalidate_slots_cache {
                   9800:     my ($cnum,$cdom)=@_;
                   9801:     my $hashid=$cnum.':'.$cdom;
                   9802:     &devalidate_cache_new('allslots',$hashid);
                   9803: }
                   9804: 
1.31      www      9805: # ------------------------------------------------- Update symbolic store links
                   9806: 
                   9807: sub symblist {
                   9808:     my ($mapname,%newhash)=@_;
1.438     www      9809:     $mapname=&deversion(&declutter($mapname));
1.31      www      9810:     my %hash;
1.620     albertel 9811:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9812:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9813:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9814: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9815: 		next if ($url eq 'last_known'
                   9816: 			 && $env{'form.no_update_last_known'});
                   9817: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9818: 						    $newhash{$url}->[1],
                   9819: 						    $newhash{$url}->[0]);
1.191     harris41 9820:             }
1.31      www      9821:             if (untie(%hash)) {
                   9822: 		return 'ok';
                   9823:             }
                   9824:         }
                   9825:     }
                   9826:     return 'error';
1.212     www      9827: }
                   9828: 
                   9829: # --------------------------------------------------------------- Verify a symb
                   9830: 
                   9831: sub symbverify {
1.510     www      9832:     my ($symb,$thisurl)=@_;
                   9833:     my $thisfn=$thisurl;
1.439     www      9834:     $thisfn=&declutter($thisfn);
1.215     www      9835: # direct jump to resource in page or to a sequence - will construct own symbs
                   9836:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9837: # check URL part
1.409     www      9838:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9839: 
1.431     www      9840:     unless ($url eq $thisfn) { return 0; }
1.213     www      9841: 
1.216     www      9842:     $symb=&symbclean($symb);
1.510     www      9843:     $thisurl=&deversion($thisurl);
1.439     www      9844:     $thisfn=&deversion($thisfn);
1.213     www      9845: 
                   9846:     my %bighash;
                   9847:     my $okay=0;
1.431     www      9848: 
1.620     albertel 9849:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9850:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9851:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9852:             $thisurl =~ s/\?.+$//;
                   9853:         }
1.510     www      9854:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9855:         unless ($ids) {
                   9856:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9857:             $ids=$bighash{$idkey};
1.216     www      9858:         }
                   9859:         if ($ids) {
                   9860: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9861: 	    foreach my $id (split(/\,/,$ids)) {
                   9862: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9863:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9864:                    $symb =~ s/\?.+$//;
                   9865:                }
1.216     www      9866:                if (
                   9867:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9868:    eq $symb) { 
1.620     albertel 9869: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9870: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9871:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9872: 		       $okay=1; 
                   9873: 		   }
                   9874: 	       }
1.216     www      9875: 	   }
                   9876:         }
1.213     www      9877: 	untie(%bighash);
                   9878:     }
                   9879:     return $okay;
1.31      www      9880: }
                   9881: 
1.210     www      9882: # --------------------------------------------------------------- Clean-up symb
                   9883: 
                   9884: sub symbclean {
                   9885:     my $symb=shift;
1.568     albertel 9886:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9887: # remove version from map
                   9888:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9889: 
1.210     www      9890: # remove version from URL
                   9891:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9892: 
1.507     www      9893: # remove wrapper
                   9894: 
1.510     www      9895:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9896:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9897:     return $symb;
1.409     www      9898: }
                   9899: 
                   9900: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9901: 
                   9902: sub encode_symb {
                   9903:     my ($map,$resid,$url)=@_;
                   9904:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9905: }
1.409     www      9906: 
                   9907: sub decode_symb {
1.568     albertel 9908:     my $symb=shift;
                   9909:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9910:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9911:     return (&fixversion($map),$resid,&fixversion($url));
                   9912: }
                   9913: 
                   9914: sub fixversion {
                   9915:     my $fn=shift;
1.609     banghart 9916:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9917:     my %bighash;
                   9918:     my $uri=&clutter($fn);
1.620     albertel 9919:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9920: # is this cached?
1.599     albertel 9921:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9922:     if (defined($cached)) { return $result; }
                   9923: # unfortunately not cached, or expired
1.620     albertel 9924:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9925: 	    &GDBM_READER(),0640)) {
                   9926:  	if ($bighash{'version_'.$uri}) {
                   9927:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9928:  	    unless (($version eq 'mostrecent') || 
                   9929: 		    ($version==&getversion($uri))) {
1.440     www      9930:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9931:  	    }
                   9932:  	}
                   9933:  	untie %bighash;
1.413     www      9934:     }
1.599     albertel 9935:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9936: }
                   9937: 
                   9938: sub deversion {
                   9939:     my $url=shift;
                   9940:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9941:     return $url;
1.210     www      9942: }
                   9943: 
1.31      www      9944: # ------------------------------------------------------ Return symb list entry
                   9945: 
                   9946: sub symbread {
1.249     www      9947:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9948:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9949:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9950: # no filename provided? try from environment
1.44      www      9951:     unless ($thisfn) {
1.620     albertel 9952:         if ($env{'request.symb'}) {
                   9953: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9954: 	}
1.620     albertel 9955: 	$thisfn=$env{'request.filename'};
1.44      www      9956:     }
1.569     albertel 9957:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9958: # is that filename actually a symb? Verify, clean, and return
                   9959:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9960: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9961: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9962: 	}
1.242     www      9963:     }
1.44      www      9964:     $thisfn=declutter($thisfn);
1.31      www      9965:     my %hash;
1.37      www      9966:     my %bighash;
                   9967:     my $syval='';
1.620     albertel 9968:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9969:         my $targetfn = $thisfn;
1.609     banghart 9970:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9971:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9972:         }
1.687     albertel 9973: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9974: 	    $targetfn=$1;
                   9975: 	}
1.620     albertel 9976:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9977:                       &GDBM_READER(),0640)) {
1.481     raeburn  9978: 	    $syval=$hash{$targetfn};
1.37      www      9979:             untie(%hash);
                   9980:         }
                   9981: # ---------------------------------------------------------- There was an entry
                   9982:         if ($syval) {
1.601     albertel 9983: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9984: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9985: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9986: 		    #return $env{$cache_str}='';
1.601     albertel 9987: 		#}    
                   9988: 		#$syval.=$1;
                   9989: 	    #}
1.37      www      9990:         } else {
                   9991: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9992:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9993:                             &GDBM_READER(),0640)) {
1.37      www      9994: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9995:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9996:               unless ($ids) { 
                   9997:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9998:               }
                   9999:               unless ($ids) {
                   10000: # alias?
                   10001: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10002:               }
1.37      www      10003:               if ($ids) {
                   10004: # ------------------------------------------------------------------- Has ID(s)
                   10005:                  my @possibilities=split(/\,/,$ids);
1.39      www      10006:                  if ($#possibilities==0) {
                   10007: # ----------------------------------------------- There is only one possibility
1.37      www      10008: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10009: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10010: 						    $resid,$thisfn);
1.249     www      10011:                  } elsif (!$donotrecurse) {
1.39      www      10012: # ------------------------------------------ There is more than one possibility
                   10013:                      my $realpossible=0;
1.800     albertel 10014:                      foreach my $id (@possibilities) {
                   10015: 			 my $file=$bighash{'src_'.$id};
1.39      www      10016:                          if (&allowed('bre',$file)) {
1.800     albertel 10017:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10018:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10019: 				$realpossible++;
1.626     albertel 10020:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10021: 						    $resid,$thisfn);
1.39      www      10022:                             }
                   10023: 			 }
1.191     harris41 10024:                      }
1.39      www      10025: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10026:                  } else {
                   10027:                      $syval='';
1.37      www      10028:                  }
                   10029: 	      }
                   10030:               untie(%bighash)
1.481     raeburn  10031:            }
1.31      www      10032:         }
1.62      www      10033:         if ($syval) {
1.620     albertel 10034: 	    return $env{$cache_str}=$syval;
1.62      www      10035:         }
1.31      www      10036:     }
1.949     raeburn  10037:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10038:     return $env{$cache_str}='';
1.31      www      10039: }
                   10040: 
                   10041: # ---------------------------------------------------------- Return random seed
                   10042: 
1.32      www      10043: sub numval {
                   10044:     my $txt=shift;
                   10045:     $txt=~tr/A-J/0-9/;
                   10046:     $txt=~tr/a-j/0-9/;
                   10047:     $txt=~tr/K-T/0-9/;
                   10048:     $txt=~tr/k-t/0-9/;
                   10049:     $txt=~tr/U-Z/0-5/;
                   10050:     $txt=~tr/u-z/0-5/;
                   10051:     $txt=~s/\D//g;
1.564     albertel 10052:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10053:     return int($txt);
1.368     albertel 10054: }
                   10055: 
1.484     albertel 10056: sub numval2 {
                   10057:     my $txt=shift;
                   10058:     $txt=~tr/A-J/0-9/;
                   10059:     $txt=~tr/a-j/0-9/;
                   10060:     $txt=~tr/K-T/0-9/;
                   10061:     $txt=~tr/k-t/0-9/;
                   10062:     $txt=~tr/U-Z/0-5/;
                   10063:     $txt=~tr/u-z/0-5/;
                   10064:     $txt=~s/\D//g;
                   10065:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10066:     my $total;
                   10067:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10068:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10069:     return int($total);
                   10070: }
                   10071: 
1.575     albertel 10072: sub numval3 {
                   10073:     use integer;
                   10074:     my $txt=shift;
                   10075:     $txt=~tr/A-J/0-9/;
                   10076:     $txt=~tr/a-j/0-9/;
                   10077:     $txt=~tr/K-T/0-9/;
                   10078:     $txt=~tr/k-t/0-9/;
                   10079:     $txt=~tr/U-Z/0-5/;
                   10080:     $txt=~tr/u-z/0-5/;
                   10081:     $txt=~s/\D//g;
                   10082:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10083:     my $total;
                   10084:     foreach my $val (@txts) { $total+=$val; }
                   10085:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10086:     return $total;
                   10087: }
                   10088: 
1.675     albertel 10089: sub digest {
                   10090:     my ($data)=@_;
                   10091:     my $digest=&Digest::MD5::md5($data);
                   10092:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10093:     my ($e,$f);
                   10094:     {
                   10095:         use integer;
                   10096:         $e=($a+$b);
                   10097:         $f=($c+$d);
                   10098:         if ($_64bit) {
                   10099:             $e=(($e<<32)>>32);
                   10100:             $f=(($f<<32)>>32);
                   10101:         }
                   10102:     }
                   10103:     if (wantarray) {
                   10104: 	return ($e,$f);
                   10105:     } else {
                   10106: 	my $g;
                   10107: 	{
                   10108: 	    use integer;
                   10109: 	    $g=($e+$f);
                   10110: 	    if ($_64bit) {
                   10111: 		$g=(($g<<32)>>32);
                   10112: 	    }
                   10113: 	}
                   10114: 	return $g;
                   10115:     }
                   10116: }
                   10117: 
1.368     albertel 10118: sub latest_rnd_algorithm_id {
1.675     albertel 10119:     return '64bit5';
1.366     albertel 10120: }
1.32      www      10121: 
1.503     albertel 10122: sub get_rand_alg {
                   10123:     my ($courseid)=@_;
1.790     albertel 10124:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10125:     if ($courseid) {
1.620     albertel 10126: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10127:     }
                   10128:     return &latest_rnd_algorithm_id();
                   10129: }
                   10130: 
1.562     albertel 10131: sub validCODE {
                   10132:     my ($CODE)=@_;
                   10133:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10134:     return 0;
                   10135: }
                   10136: 
1.491     albertel 10137: sub getCODE {
1.620     albertel 10138:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10139:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10140: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10141: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10142: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10143:     }
                   10144:     return undef;
                   10145: }
1.1133    foxr     10146: #
                   10147: #  Determines the random seed for a specific context:
                   10148: #
                   10149: # parameters:
                   10150: #   symb      - in course context the symb for the seed.
                   10151: #   course_id - The course id of the form domain_coursenum.
                   10152: #   domain    - Domain for the user.
                   10153: #   course    - Course for the user.
                   10154: #   cenv      - environment of the course.
                   10155: #
                   10156: # NOTE:
                   10157: #   All parameters are picked out of the environment if missing
                   10158: #   or not defined.
                   10159: #   If a symb cannot be determined the current time is used instead.
                   10160: #
                   10161: #  For a given well defined symb, courside, domain, username,
                   10162: #  and course environment, the seed is reproducible.
                   10163: #
1.31      www      10164: sub rndseed {
1.1133    foxr     10165:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10166:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10167:     if (!defined($symb)) {
1.366     albertel 10168: 	unless ($symb=$wsymb) { return time; }
                   10169:     }
1.1146    foxr     10170:     if (!defined $courseid) { 
                   10171: 	$courseid=$wcourseid; 
                   10172:     }
                   10173:     if (!defined $domain) { $domain=$wdomain; }
                   10174:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10175: 
                   10176:     my $which;
                   10177:     if (defined($cenv->{'rndseed'})) {
                   10178: 	$which = $cenv->{'rndseed'};
                   10179:     } else {
                   10180: 	$which =&get_rand_alg($courseid);
                   10181:     }
1.491     albertel 10182:     if (defined(&getCODE())) {
1.1133    foxr     10183: 
1.675     albertel 10184: 	if ($which eq '64bit5') {
                   10185: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10186: 	} elsif ($which eq '64bit4') {
1.575     albertel 10187: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10188: 	} else {
                   10189: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10190: 	}
1.675     albertel 10191:     } elsif ($which eq '64bit5') {
                   10192: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10193:     } elsif ($which eq '64bit4') {
                   10194: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10195:     } elsif ($which eq '64bit3') {
                   10196: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10197:     } elsif ($which eq '64bit2') {
                   10198: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10199:     } elsif ($which eq '64bit') {
                   10200: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10201:     }
                   10202:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10203: }
                   10204: 
                   10205: sub rndseed_32bit {
                   10206:     my ($symb,$courseid,$domain,$username)=@_;
                   10207:     {
                   10208: 	use integer;
                   10209: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10210: 	my $symbseed=numval($symb) << 22;
                   10211: 	my $namechck=unpack("%32C*",$username) << 17;
                   10212: 	my $nameseed=numval($username) << 12;
                   10213: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10214: 	my $courseseed=unpack("%32C*",$courseid);
                   10215: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10216: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10217: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10218: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10219: 	return $num;
                   10220:     }
                   10221: }
                   10222: 
                   10223: sub rndseed_64bit {
                   10224:     my ($symb,$courseid,$domain,$username)=@_;
                   10225:     {
                   10226: 	use integer;
                   10227: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10228: 	my $symbseed=numval($symb) << 10;
                   10229: 	my $namechck=unpack("%32S*",$username);
                   10230: 	
                   10231: 	my $nameseed=numval($username) << 21;
                   10232: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10233: 	my $courseseed=unpack("%32S*",$courseid);
                   10234: 	
                   10235: 	my $num1=$symbchck+$symbseed+$namechck;
                   10236: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10237: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10238: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10239: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10240: 	return "$num1,$num2";
1.155     albertel 10241:     }
1.366     albertel 10242: }
                   10243: 
1.443     albertel 10244: sub rndseed_64bit2 {
                   10245:     my ($symb,$courseid,$domain,$username)=@_;
                   10246:     {
                   10247: 	use integer;
                   10248: 	# strings need to be an even # of cahracters long, it it is odd the
                   10249:         # last characters gets thrown away
                   10250: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10251: 	my $symbseed=numval($symb) << 10;
                   10252: 	my $namechck=unpack("%32S*",$username.' ');
                   10253: 	
                   10254: 	my $nameseed=numval($username) << 21;
1.501     albertel 10255: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10256: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10257: 	
                   10258: 	my $num1=$symbchck+$symbseed+$namechck;
                   10259: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10260: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10261: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10262: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10263: 	return "$num1,$num2";
                   10264:     }
                   10265: }
                   10266: 
                   10267: sub rndseed_64bit3 {
                   10268:     my ($symb,$courseid,$domain,$username)=@_;
                   10269:     {
                   10270: 	use integer;
                   10271: 	# strings need to be an even # of cahracters long, it it is odd the
                   10272:         # last characters gets thrown away
                   10273: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10274: 	my $symbseed=numval2($symb) << 10;
                   10275: 	my $namechck=unpack("%32S*",$username.' ');
                   10276: 	
                   10277: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10278: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10279: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10280: 	
                   10281: 	my $num1=$symbchck+$symbseed+$namechck;
                   10282: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10283: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10284: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10285: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10286: 	
1.503     albertel 10287: 	return "$num1:$num2";
1.443     albertel 10288:     }
                   10289: }
                   10290: 
1.575     albertel 10291: sub rndseed_64bit4 {
                   10292:     my ($symb,$courseid,$domain,$username)=@_;
                   10293:     {
                   10294: 	use integer;
                   10295: 	# strings need to be an even # of cahracters long, it it is odd the
                   10296:         # last characters gets thrown away
                   10297: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10298: 	my $symbseed=numval3($symb) << 10;
                   10299: 	my $namechck=unpack("%32S*",$username.' ');
                   10300: 	
                   10301: 	my $nameseed=numval3($username) << 21;
                   10302: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10303: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10304: 	
                   10305: 	my $num1=$symbchck+$symbseed+$namechck;
                   10306: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10307: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10308: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10309: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10310: 	
1.575     albertel 10311: 	return "$num1:$num2";
                   10312:     }
                   10313: }
                   10314: 
1.675     albertel 10315: sub rndseed_64bit5 {
                   10316:     my ($symb,$courseid,$domain,$username)=@_;
                   10317:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10318:     return "$num1:$num2";
                   10319: }
                   10320: 
1.366     albertel 10321: sub rndseed_CODE_64bit {
                   10322:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10323:     {
1.366     albertel 10324: 	use integer;
1.443     albertel 10325: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10326: 	my $symbseed=numval2($symb);
1.491     albertel 10327: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10328: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10329: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10330: 	my $num1=$symbseed+$CODEchck;
                   10331: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10332: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10333: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10334: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10335: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10336: 	return "$num1:$num2";
1.366     albertel 10337:     }
                   10338: }
                   10339: 
1.575     albertel 10340: sub rndseed_CODE_64bit4 {
                   10341:     my ($symb,$courseid,$domain,$username)=@_;
                   10342:     {
                   10343: 	use integer;
                   10344: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10345: 	my $symbseed=numval3($symb);
                   10346: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10347: 	my $CODEseed=numval3(&getCODE());
                   10348: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10349: 	my $num1=$symbseed+$CODEchck;
                   10350: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10351: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10352: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10353: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10354: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10355: 	return "$num1:$num2";
                   10356:     }
                   10357: }
                   10358: 
1.675     albertel 10359: sub rndseed_CODE_64bit5 {
                   10360:     my ($symb,$courseid,$domain,$username)=@_;
                   10361:     my $code = &getCODE();
                   10362:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10363:     return "$num1:$num2";
                   10364: }
                   10365: 
1.366     albertel 10366: sub setup_random_from_rndseed {
                   10367:     my ($rndseed)=@_;
1.503     albertel 10368:     if ($rndseed =~/([,:])/) {
                   10369: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10370: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10371:     } else {
                   10372: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10373:     }
1.36      albertel 10374: }
                   10375: 
1.474     albertel 10376: sub latest_receipt_algorithm_id {
1.835     albertel 10377:     return 'receipt3';
1.474     albertel 10378: }
                   10379: 
1.480     www      10380: sub recunique {
                   10381:     my $fucourseid=shift;
                   10382:     my $unique;
1.835     albertel 10383:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10384: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10385: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10386:     } else {
                   10387: 	$unique=$perlvar{'lonReceipt'};
                   10388:     }
                   10389:     return unpack("%32C*",$unique);
                   10390: }
                   10391: 
                   10392: sub recprefix {
                   10393:     my $fucourseid=shift;
                   10394:     my $prefix;
1.835     albertel 10395:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10396: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10397: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10398:     } else {
                   10399: 	$prefix=$perlvar{'lonHostID'};
                   10400:     }
                   10401:     return unpack("%32C*",$prefix);
                   10402: }
                   10403: 
1.76      www      10404: sub ireceipt {
1.474     albertel 10405:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10406: 
                   10407:     my $return =&recprefix($fucourseid).'-';
                   10408: 
                   10409:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10410: 	$env{'request.state'} eq 'construct') {
                   10411: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10412: 	return $return;
                   10413:     }
                   10414: 
1.76      www      10415:     my $cuname=unpack("%32C*",$funame);
                   10416:     my $cudom=unpack("%32C*",$fudom);
                   10417:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10418:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10419:     my $cunique=&recunique($fucourseid);
1.474     albertel 10420:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10421:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10422: 
1.790     albertel 10423: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10424: 			       
                   10425: 	$return.= ($cunique%$cuname+
                   10426: 		   $cunique%$cudom+
                   10427: 		   $cusymb%$cuname+
                   10428: 		   $cusymb%$cudom+
                   10429: 		   $cucourseid%$cuname+
                   10430: 		   $cucourseid%$cudom+
                   10431: 		   $cpart%$cuname+
                   10432: 		   $cpart%$cudom);
                   10433:     } else {
                   10434: 	$return.= ($cunique%$cuname+
                   10435: 		   $cunique%$cudom+
                   10436: 		   $cusymb%$cuname+
                   10437: 		   $cusymb%$cudom+
                   10438: 		   $cucourseid%$cuname+
                   10439: 		   $cucourseid%$cudom);
                   10440:     }
                   10441:     return $return;
1.76      www      10442: }
                   10443: 
                   10444: sub receipt {
1.474     albertel 10445:     my ($part)=@_;
1.790     albertel 10446:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10447:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10448: }
1.260     ng       10449: 
1.790     albertel 10450: sub whichuser {
                   10451:     my ($passedsymb)=@_;
                   10452:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10453:     if (defined($env{'form.grade_symb'})) {
                   10454: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10455: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10456: 	if (!$allowed &&
                   10457: 	    exists($env{'request.course.sec'}) &&
                   10458: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10459: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10460: 			      '/'.$env{'request.course.sec'});
                   10461: 	}
                   10462: 	if ($allowed) {
                   10463: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10464: 	    $courseid=$tmp_courseid;
                   10465: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10466: 	    ($name)=&get_env_multiple('form.grade_username');
                   10467: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10468: 	}
                   10469:     }
                   10470:     if (!$passedsymb) {
                   10471: 	$symb=&symbread();
                   10472:     } else {
                   10473: 	$symb=$passedsymb;
                   10474:     }
                   10475:     $courseid=$env{'request.course.id'};
                   10476:     $domain=$env{'user.domain'};
                   10477:     $name=$env{'user.name'};
                   10478:     if ($name eq 'public' && $domain eq 'public') {
                   10479: 	if (!defined($env{'form.username'})) {
                   10480: 	    $env{'form.username'}.=time.rand(10000000);
                   10481: 	}
                   10482: 	$name.=$env{'form.username'};
                   10483:     }
                   10484:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10485: 
                   10486: }
                   10487: 
1.36      albertel 10488: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10489: # returns either the contents of the file or 
                   10490: # -1 if the file doesn't exist
1.481     raeburn  10491: #
                   10492: # if the target is a file that was uploaded via DOCS, 
                   10493: # a check will be made to see if a current copy exists on the local server,
                   10494: # if it does this will be served, otherwise a copy will be retrieved from
                   10495: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10496: # the local server.   
1.472     albertel 10497: 
1.36      albertel 10498: sub getfile {
1.538     albertel 10499:     my ($file) = @_;
1.609     banghart 10500:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10501:     &repcopy($file);
                   10502:     return &readfile($file);
                   10503: }
                   10504: 
                   10505: sub repcopy_userfile {
                   10506:     my ($file)=@_;
1.1142    raeburn  10507:     my $londocroot = $perlvar{'lonDocRoot'};
                   10508:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10509:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10510:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10511: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10512:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10513:     if (-e "$file") {
1.828     www      10514: # we already have a local copy, check it out
1.538     albertel 10515: 	my @fileinfo = stat($file);
1.828     www      10516: 	my $rtncode;
                   10517: 	my $info;
1.538     albertel 10518: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10519: 	if ($lwpresp ne 'ok') {
1.828     www      10520: # there is no such file anymore, even though we had a local copy
1.482     albertel 10521: 	    if ($rtncode eq '404') {
1.538     albertel 10522: 		unlink($file);
1.482     albertel 10523: 	    }
                   10524: 	    return -1;
                   10525: 	}
                   10526: 	if ($info < $fileinfo[9]) {
1.828     www      10527: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10528: 	    return 'ok';
1.828     www      10529: 	} else {
                   10530: # the file is outdated, get rid of it
                   10531: 	    unlink($file);
1.482     albertel 10532: 	}
1.828     www      10533:     }
                   10534: # one way or the other, at this point, we don't have the file
                   10535: # construct the correct path for the file
                   10536:     my @parts = ($cdom,$cnum); 
                   10537:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10538: 	push @parts, split(/\//,$1);
                   10539:     }
                   10540:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10541:     foreach my $part (@parts) {
                   10542: 	$path .= '/'.$part;
                   10543: 	if (!-e $path) {
                   10544: 	    mkdir($path,0770);
1.482     albertel 10545: 	}
                   10546:     }
1.828     www      10547: # now the path exists for sure
                   10548: # get a user agent
                   10549:     my $ua=new LWP::UserAgent;
                   10550:     my $transferfile=$file.'.in.transfer';
                   10551: # FIXME: this should flock
                   10552:     if (-e $transferfile) { return 'ok'; }
                   10553:     my $request;
                   10554:     $uri=~s/^\///;
1.980     raeburn  10555:     my $homeserver = &homeserver($cnum,$cdom);
                   10556:     my $protocol = $protocol{$homeserver};
                   10557:     $protocol = 'http' if ($protocol ne 'https');
                   10558:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10559:     my $response=$ua->request($request,$transferfile);
                   10560: # did it work?
                   10561:     if ($response->is_error()) {
                   10562: 	unlink($transferfile);
                   10563: 	&logthis("Userfile repcopy failed for $uri");
                   10564: 	return -1;
                   10565:     }
                   10566: # worked, rename the transfer file
                   10567:     rename($transferfile,$file);
1.607     raeburn  10568:     return 'ok';
1.481     raeburn  10569: }
                   10570: 
1.517     albertel 10571: sub tokenwrapper {
                   10572:     my $uri=shift;
1.980     raeburn  10573:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10574:     $uri=~s|^/||;
1.620     albertel 10575:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10576:     my $token=$1;
1.552     albertel 10577:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10578:     if ($udom && $uname && $file) {
                   10579: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10580:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10581:         my $homeserver = &homeserver($uname,$udom);
                   10582:         my $protocol = $protocol{$homeserver};
                   10583:         $protocol = 'http' if ($protocol ne 'https');
                   10584:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10585:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10586:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10587:     } else {
                   10588:         return '/adm/notfound.html';
                   10589:     }
                   10590: }
                   10591: 
1.828     www      10592: # call with reqtype HEAD: get last modification time
                   10593: # call with reqtype GET: get the file contents
                   10594: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10595: #
1.481     raeburn  10596: sub getuploaded {
                   10597:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10598:     $uri=~s/^\///;
1.980     raeburn  10599:     my $homeserver = &homeserver($cnum,$cdom);
                   10600:     my $protocol = $protocol{$homeserver};
                   10601:     $protocol = 'http' if ($protocol ne 'https');
                   10602:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10603:     my $ua=new LWP::UserAgent;
                   10604:     my $request=new HTTP::Request($reqtype,$uri);
                   10605:     my $response=$ua->request($request);
                   10606:     $$rtncode = $response->code;
1.482     albertel 10607:     if (! $response->is_success()) {
                   10608: 	return 'failed';
                   10609:     }      
                   10610:     if ($reqtype eq 'HEAD') {
1.486     www      10611: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10612:     } elsif ($reqtype eq 'GET') {
                   10613: 	$$info = $response->content;
1.472     albertel 10614:     }
1.482     albertel 10615:     return 'ok';
1.36      albertel 10616: }
                   10617: 
1.481     raeburn  10618: sub readfile {
                   10619:     my $file = shift;
                   10620:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10621:     my $fh;
                   10622:     open($fh,"<$file");
                   10623:     my $a='';
1.800     albertel 10624:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10625:     return $a;
                   10626: }
                   10627: 
1.36      albertel 10628: sub filelocation {
1.590     banghart 10629:     my ($dir,$file) = @_;
                   10630:     my $location;
                   10631:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10632: 
                   10633:     if ($file =~ m-^/adm/-) {
                   10634: 	$file=~s-^/adm/wrapper/-/-;
                   10635: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10636:     }
1.882     albertel 10637: 
1.1139    www      10638:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10639:         $location = $file;
1.609     banghart 10640:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10641:         my ($udom,$uname,$filename)=
1.811     albertel 10642:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10643:         my $home=&homeserver($uname,$udom);
                   10644:         my $is_me=0;
                   10645:         my @ids=&current_machine_ids();
                   10646:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10647:         if ($is_me) {
1.1117    foxr     10648:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10649:         } else {
                   10650:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10651:   	      $udom.'/'.$uname.'/'.$filename;
                   10652:         }
1.882     albertel 10653:     } elsif ($file =~ m-^/adm/-) {
                   10654: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10655:     } else {
                   10656:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10657:         $file=~s:^/(res|priv)/:/:;
                   10658:         my $space=$1;
1.590     banghart 10659:         if ( !( $file =~ m:^/:) ) {
                   10660:             $location = $dir. '/'.$file;
                   10661:         } else {
1.1142    raeburn  10662:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10663:         }
1.59      albertel 10664:     }
1.590     banghart 10665:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10666:     while ($location=~m{/\.\./}) {
                   10667: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10668: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10669: 	} else {
                   10670: 	    $location=~ s{/\.\./}{/}g;
                   10671: 	}
                   10672:     } #remove dir/..
1.590     banghart 10673:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10674:     return $location;
1.46      www      10675: }
1.36      albertel 10676: 
1.46      www      10677: sub hreflocation {
                   10678:     my ($dir,$file)=@_;
1.980     raeburn  10679:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10680: 	$file=filelocation($dir,$file);
1.700     albertel 10681:     } elsif ($file=~m-^/adm/-) {
                   10682: 	$file=~s-^/adm/wrapper/-/-;
                   10683: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10684:     }
                   10685:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10686: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10687:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10688: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10689: 	        {/uploaded/$1/$2/}x;
1.46      www      10690:     }
1.913     albertel 10691:     if ($file=~ m{^/userfiles/}) {
                   10692: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10693:     }
1.462     albertel 10694:     return $file;
1.465     albertel 10695: }
                   10696: 
1.1139    www      10697: 
                   10698: 
                   10699: 
                   10700: 
1.465     albertel 10701: sub current_machine_domains {
1.853     albertel 10702:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10703: }
                   10704: 
                   10705: sub machine_domains {
                   10706:     my ($hostname) = @_;
1.465     albertel 10707:     my @domains;
1.838     albertel 10708:     my %hostname = &all_hostnames();
1.465     albertel 10709:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10710: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10711: 	if ($hostname eq $name) {
1.844     albertel 10712: 	    push(@domains,&host_domain($id));
1.465     albertel 10713: 	}
                   10714:     }
                   10715:     return @domains;
                   10716: }
                   10717: 
                   10718: sub current_machine_ids {
1.853     albertel 10719:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10720: }
                   10721: 
                   10722: sub machine_ids {
                   10723:     my ($hostname) = @_;
                   10724:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10725:     my @ids;
1.888     albertel 10726:     my %name_to_host = &all_names();
1.889     albertel 10727:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10728: 	return @{ $name_to_host{$hostname} };
                   10729:     }
                   10730:     return;
1.31      www      10731: }
                   10732: 
1.824     raeburn  10733: sub additional_machine_domains {
                   10734:     my @domains;
                   10735:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10736:     while( my $line = <$fh>) {
                   10737:         $line =~ s/\s//g;
                   10738:         push(@domains,$line);
                   10739:     }
                   10740:     return @domains;
                   10741: }
                   10742: 
                   10743: sub default_login_domain {
                   10744:     my $domain = $perlvar{'lonDefDomain'};
                   10745:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10746:     foreach my $posdom (&current_machine_domains(),
                   10747:                         &additional_machine_domains()) {
                   10748:         if (lc($posdom) eq lc($testdomain)) {
                   10749:             $domain=$posdom;
                   10750:             last;
                   10751:         }
                   10752:     }
                   10753:     return $domain;
                   10754: }
                   10755: 
1.31      www      10756: # ------------------------------------------------------------- Declutters URLs
                   10757: 
                   10758: sub declutter {
                   10759:     my $thisfn=shift;
1.569     albertel 10760:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10761:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10762:     $thisfn=~s/^\///;
1.697     albertel 10763:     $thisfn=~s|^adm/wrapper/||;
                   10764:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10765:     $thisfn=~s/^res\///;
1.1172    bisitz   10766:     $thisfn=~s/^priv\///;
1.1032    raeburn  10767:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10768:         $thisfn=~s/\?.+$//;
                   10769:     }
1.268     www      10770:     return $thisfn;
                   10771: }
                   10772: 
                   10773: # ------------------------------------------------------------- Clutter up URLs
                   10774: 
                   10775: sub clutter {
                   10776:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10777:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10778: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10779:        $thisfn='/res'.$thisfn; 
                   10780:     }
1.1031    raeburn  10781:     if ($thisfn !~m|^/adm|) {
                   10782: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10783: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10784: 	} else {
                   10785: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10786: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10787: 	    if ($embstyle eq 'ssi'
                   10788: 		|| ($embstyle eq 'hdn')
                   10789: 		|| ($embstyle eq 'rat')
                   10790: 		|| ($embstyle eq 'prv')
                   10791: 		|| ($embstyle eq 'ign')) {
                   10792: 		#do nothing with these
                   10793: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10794: 		|| ($embstyle eq 'emb')
                   10795: 		|| ($embstyle eq 'wrp')) {
                   10796: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10797: 	    } elsif ($embstyle eq 'unk'
                   10798: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10799: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10800: 	    } else {
1.718     www      10801: #		&logthis("Got a blank emb style");
1.695     albertel 10802: 	    }
1.694     albertel 10803: 	}
                   10804:     }
1.31      www      10805:     return $thisfn;
1.12      www      10806: }
                   10807: 
1.787     albertel 10808: sub clutter_with_no_wrapper {
                   10809:     my $uri = &clutter(shift);
                   10810:     if ($uri =~ m-^/adm/-) {
                   10811: 	$uri =~ s-^/adm/wrapper/-/-;
                   10812: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10813:     }
                   10814:     return $uri;
                   10815: }
                   10816: 
1.557     albertel 10817: sub freeze_escape {
                   10818:     my ($value)=@_;
                   10819:     if (ref($value)) {
                   10820: 	$value=&nfreeze($value);
                   10821: 	return '__FROZEN__'.&escape($value);
                   10822:     }
                   10823:     return &escape($value);
                   10824: }
                   10825: 
1.11      www      10826: 
1.557     albertel 10827: sub thaw_unescape {
                   10828:     my ($value)=@_;
                   10829:     if ($value =~ /^__FROZEN__/) {
                   10830: 	substr($value,0,10,undef);
                   10831: 	$value=&unescape($value);
                   10832: 	return &thaw($value);
                   10833:     }
                   10834:     return &unescape($value);
                   10835: }
                   10836: 
1.436     albertel 10837: sub correct_line_ends {
                   10838:     my ($result)=@_;
                   10839:     $$result =~s/\r\n/\n/mg;
                   10840:     $$result =~s/\r/\n/mg;
1.415     albertel 10841: }
1.1       albertel 10842: # ================================================================ Main Program
                   10843: 
1.184     www      10844: sub goodbye {
1.204     albertel 10845:    &logthis("Starting Shut down");
1.443     albertel 10846: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10847:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10848: #converted
1.599     albertel 10849: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10850:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10851: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10852: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10853: #1.1 only
1.870     albertel 10854: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10855: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10856: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10857: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10858:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10859:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10860:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10861:    &flushcourselogs();
                   10862:    &logthis("Shutting down");
                   10863: }
                   10864: 
1.852     albertel 10865: sub get_dns {
1.869     albertel 10866:     my ($url,$func,$ignore_cache) = @_;
                   10867:     if (!$ignore_cache) {
                   10868: 	my ($content,$cached)=
                   10869: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10870: 	if ($cached) {
                   10871: 	    &$func($content);
                   10872: 	    return;
                   10873: 	}
                   10874:     }
                   10875: 
                   10876:     my %alldns;
1.852     albertel 10877:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10878:     foreach my $dns (<$config>) {
                   10879: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10880:         my $line = $1;
                   10881:         my ($host,$protocol) = split(/:/,$line);
                   10882:         if ($protocol ne 'https') {
                   10883:             $protocol = 'http';
                   10884:         }
                   10885: 	$alldns{$host} = $protocol;
1.869     albertel 10886:     }
                   10887:     while (%alldns) {
                   10888: 	my ($dns) = keys(%alldns);
1.852     albertel 10889: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10890:         $ua->timeout(30);
1.979     raeburn  10891: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10892: 	my $response=$ua->request($request);
1.979     raeburn  10893:         delete($alldns{$dns});
1.852     albertel 10894: 	next if ($response->is_error());
                   10895: 	my @content = split("\n",$response->content);
1.869     albertel 10896: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10897: 	&$func(\@content);
1.869     albertel 10898: 	return;
1.852     albertel 10899:     }
                   10900:     close($config);
1.871     albertel 10901:     my $which = (split('/',$url))[3];
                   10902:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10903:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10904:     my @content = <$config>;
                   10905:     &$func(\@content);
                   10906:     return;
1.852     albertel 10907: }
1.327     albertel 10908: # ------------------------------------------------------------ Read domain file
                   10909: {
1.852     albertel 10910:     my $loaded;
1.846     albertel 10911:     my %domain;
                   10912: 
1.852     albertel 10913:     sub parse_domain_tab {
                   10914: 	my ($lines) = @_;
                   10915: 	foreach my $line (@$lines) {
                   10916: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10917: 
1.846     albertel 10918: 	    chomp($line);
1.852     albertel 10919: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10920: 	    my %this_domain;
                   10921: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10922: 			       'lang_def', 'city', 'longi', 'lati',
                   10923: 			       'primary') {
                   10924: 		$this_domain{$field} = shift(@elements);
                   10925: 	    }
                   10926: 	    $domain{$name} = \%this_domain;
1.852     albertel 10927: 	}
                   10928:     }
1.864     albertel 10929: 
                   10930:     sub reset_domain_info {
                   10931: 	undef($loaded);
                   10932: 	undef(%domain);
                   10933:     }
                   10934: 
1.852     albertel 10935:     sub load_domain_tab {
1.869     albertel 10936: 	my ($ignore_cache) = @_;
                   10937: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10938: 	my $fh;
                   10939: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10940: 	    my @lines = <$fh>;
                   10941: 	    &parse_domain_tab(\@lines);
1.448     albertel 10942: 	}
1.852     albertel 10943: 	close($fh);
                   10944: 	$loaded = 1;
1.327     albertel 10945:     }
1.846     albertel 10946: 
                   10947:     sub domain {
1.852     albertel 10948: 	&load_domain_tab() if (!$loaded);
                   10949: 
1.846     albertel 10950: 	my ($name,$what) = @_;
                   10951: 	return if ( !exists($domain{$name}) );
                   10952: 
                   10953: 	if (!$what) {
                   10954: 	    return $domain{$name}{'description'};
                   10955: 	}
                   10956: 	return $domain{$name}{$what};
                   10957:     }
1.974     raeburn  10958: 
                   10959:     sub domain_info {
                   10960:         &load_domain_tab() if (!$loaded);
                   10961:         return %domain;
                   10962:     }
                   10963: 
1.327     albertel 10964: }
                   10965: 
                   10966: 
1.1       albertel 10967: # ------------------------------------------------------------- Read hosts file
                   10968: {
1.838     albertel 10969:     my %hostname;
1.844     albertel 10970:     my %hostdom;
1.845     albertel 10971:     my %libserv;
1.852     albertel 10972:     my $loaded;
1.888     albertel 10973:     my %name_to_host;
1.1074    raeburn  10974:     my %internetdom;
1.1107    raeburn  10975:     my %LC_dns_serv;
1.852     albertel 10976: 
                   10977:     sub parse_hosts_tab {
                   10978: 	my ($file) = @_;
                   10979: 	foreach my $configline (@$file) {
                   10980: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10981:             chomp($configline);
                   10982: 	    if ($configline =~ /^\^/) {
                   10983:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10984:                     $LC_dns_serv{$1} = 1;
                   10985:                 }
                   10986:                 next;
                   10987:             }
1.1074    raeburn  10988: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10989: 	    $name=~s/\s//g;
                   10990: 	    if ($id && $domain && $role && $name) {
                   10991: 		$hostname{$id}=$name;
1.888     albertel 10992: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10993: 		$hostdom{$id}=$domain;
                   10994: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10995:                 if (defined($protocol)) {
                   10996:                     if ($protocol eq 'https') {
                   10997:                         $protocol{$id} = $protocol;
                   10998:                     } else {
                   10999:                         $protocol{$id} = 'http'; 
                   11000:                     }
1.968     raeburn  11001:                 } else {
1.969     raeburn  11002:                     $protocol{$id} = 'http';
1.968     raeburn  11003:                 }
1.1074    raeburn  11004:                 if (defined($intdom)) {
                   11005:                     $internetdom{$id} = $intdom;
                   11006:                 }
1.852     albertel 11007: 	    }
                   11008: 	}
                   11009:     }
1.864     albertel 11010:     
                   11011:     sub reset_hosts_info {
1.897     albertel 11012: 	&purge_remembered();
1.864     albertel 11013: 	&reset_domain_info();
                   11014: 	&reset_hosts_ip_info();
1.892     albertel 11015: 	undef(%name_to_host);
1.864     albertel 11016: 	undef(%hostname);
                   11017: 	undef(%hostdom);
                   11018: 	undef(%libserv);
                   11019: 	undef($loaded);
                   11020:     }
1.1       albertel 11021: 
1.852     albertel 11022:     sub load_hosts_tab {
1.869     albertel 11023: 	my ($ignore_cache) = @_;
                   11024: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11025: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11026: 	my @config = <$config>;
                   11027: 	&parse_hosts_tab(\@config);
                   11028: 	close($config);
                   11029: 	$loaded=1;
1.1       albertel 11030:     }
1.852     albertel 11031: 
1.838     albertel 11032:     sub hostname {
1.852     albertel 11033: 	&load_hosts_tab() if (!$loaded);
                   11034: 
1.838     albertel 11035: 	my ($lonid) = @_;
                   11036: 	return $hostname{$lonid};
                   11037:     }
1.845     albertel 11038: 
1.838     albertel 11039:     sub all_hostnames {
1.852     albertel 11040: 	&load_hosts_tab() if (!$loaded);
                   11041: 
1.838     albertel 11042: 	return %hostname;
                   11043:     }
1.845     albertel 11044: 
1.888     albertel 11045:     sub all_names {
                   11046: 	&load_hosts_tab() if (!$loaded);
                   11047: 
                   11048: 	return %name_to_host;
                   11049:     }
                   11050: 
1.974     raeburn  11051:     sub all_host_domain {
                   11052:         &load_hosts_tab() if (!$loaded);
                   11053:         return %hostdom;
                   11054:     }
                   11055: 
1.845     albertel 11056:     sub is_library {
1.852     albertel 11057: 	&load_hosts_tab() if (!$loaded);
                   11058: 
1.845     albertel 11059: 	return exists($libserv{$_[0]});
                   11060:     }
                   11061: 
                   11062:     sub all_library {
1.852     albertel 11063: 	&load_hosts_tab() if (!$loaded);
                   11064: 
1.845     albertel 11065: 	return %libserv;
                   11066:     }
                   11067: 
1.1062    droeschl 11068:     sub unique_library {
                   11069: 	#2x reverse removes all hostnames that appear more than once
                   11070:         my %unique = reverse &all_library();
                   11071:         return reverse %unique;
                   11072:     }
                   11073: 
1.841     albertel 11074:     sub get_servers {
1.852     albertel 11075: 	&load_hosts_tab() if (!$loaded);
                   11076: 
1.841     albertel 11077: 	my ($domain,$type) = @_;
                   11078: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11079: 	                                          : %hostname;
                   11080: 	my %result;
1.842     albertel 11081: 	if (ref($domain) eq 'ARRAY') {
                   11082: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11083: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11084: 		    $result{$host} = $hostname;
                   11085: 		}
                   11086: 	    }
                   11087: 	} else {
                   11088: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11089: 		if ($hostdom{$host} eq $domain) {
                   11090: 		    $result{$host} = $hostname;
                   11091: 		}
1.841     albertel 11092: 	    }
                   11093: 	}
                   11094: 	return %result;
                   11095:     }
1.845     albertel 11096: 
1.1062    droeschl 11097:     sub get_unique_servers {
                   11098:         my %unique = reverse &get_servers(@_);
                   11099: 	return reverse %unique;
                   11100:     }
                   11101: 
1.844     albertel 11102:     sub host_domain {
1.852     albertel 11103: 	&load_hosts_tab() if (!$loaded);
                   11104: 
1.844     albertel 11105: 	my ($lonid) = @_;
                   11106: 	return $hostdom{$lonid};
                   11107:     }
                   11108: 
1.841     albertel 11109:     sub all_domains {
1.852     albertel 11110: 	&load_hosts_tab() if (!$loaded);
                   11111: 
1.841     albertel 11112: 	my %seen;
                   11113: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11114: 	return @uniq;
                   11115:     }
1.1074    raeburn  11116: 
                   11117:     sub internet_dom {
                   11118:         &load_hosts_tab() if (!$loaded);
                   11119: 
                   11120:         my ($lonid) = @_;
                   11121:         return $internetdom{$lonid};
                   11122:     }
1.1107    raeburn  11123: 
                   11124:     sub is_LC_dns {
                   11125:         &load_hosts_tab() if (!$loaded);
                   11126: 
                   11127:         my ($hostname) = @_;
                   11128:         return exists($LC_dns_serv{$hostname});
                   11129:     }
                   11130: 
1.1       albertel 11131: }
                   11132: 
1.847     albertel 11133: { 
                   11134:     my %iphost;
1.856     albertel 11135:     my %name_to_ip;
                   11136:     my %lonid_to_ip;
1.869     albertel 11137: 
1.847     albertel 11138:     sub get_hosts_from_ip {
                   11139: 	my ($ip) = @_;
                   11140: 	my %iphosts = &get_iphost();
                   11141: 	if (ref($iphosts{$ip})) {
                   11142: 	    return @{$iphosts{$ip}};
                   11143: 	}
                   11144: 	return;
1.839     albertel 11145:     }
1.864     albertel 11146:     
                   11147:     sub reset_hosts_ip_info {
                   11148: 	undef(%iphost);
                   11149: 	undef(%name_to_ip);
                   11150: 	undef(%lonid_to_ip);
                   11151:     }
1.856     albertel 11152: 
                   11153:     sub get_host_ip {
                   11154: 	my ($lonid) = @_;
                   11155: 	if (exists($lonid_to_ip{$lonid})) {
                   11156: 	    return $lonid_to_ip{$lonid};
                   11157: 	}
                   11158: 	my $name=&hostname($lonid);
                   11159:    	my $ip = gethostbyname($name);
                   11160: 	return if (!$ip || length($ip) ne 4);
                   11161: 	$ip=inet_ntoa($ip);
                   11162: 	$name_to_ip{$name}   = $ip;
                   11163: 	$lonid_to_ip{$lonid} = $ip;
                   11164: 	return $ip;
                   11165:     }
1.847     albertel 11166:     
                   11167:     sub get_iphost {
1.869     albertel 11168: 	my ($ignore_cache) = @_;
1.894     albertel 11169: 
1.869     albertel 11170: 	if (!$ignore_cache) {
                   11171: 	    if (%iphost) {
                   11172: 		return %iphost;
                   11173: 	    }
                   11174: 	    my ($ip_info,$cached)=
                   11175: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11176: 	    if ($cached) {
                   11177: 		%iphost      = %{$ip_info->[0]};
                   11178: 		%name_to_ip  = %{$ip_info->[1]};
                   11179: 		%lonid_to_ip = %{$ip_info->[2]};
                   11180: 		return %iphost;
                   11181: 	    }
                   11182: 	}
1.894     albertel 11183: 
                   11184: 	# get yesterday's info for fallback
                   11185: 	my %old_name_to_ip;
                   11186: 	my ($ip_info,$cached)=
                   11187: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11188: 	if ($cached) {
                   11189: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11190: 	}
                   11191: 
1.888     albertel 11192: 	my %name_to_host = &all_names();
                   11193: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11194: 	    my $ip;
                   11195: 	    if (!exists($name_to_ip{$name})) {
                   11196: 		$ip = gethostbyname($name);
                   11197: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11198: 		    if (defined($old_name_to_ip{$name})) {
                   11199: 			$ip = $old_name_to_ip{$name};
                   11200: 			&logthis("Can't find $name defaulting to old $ip");
                   11201: 		    } else {
                   11202: 			&logthis("Name $name no IP found");
                   11203: 			next;
                   11204: 		    }
                   11205: 		} else {
                   11206: 		    $ip=inet_ntoa($ip);
1.847     albertel 11207: 		}
                   11208: 		$name_to_ip{$name} = $ip;
                   11209: 	    } else {
                   11210: 		$ip = $name_to_ip{$name};
1.653     albertel 11211: 	    }
1.888     albertel 11212: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11213: 		$lonid_to_ip{$id} = $ip;
                   11214: 	    }
                   11215: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11216: 	}
1.869     albertel 11217: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11218: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11219: 				      48*60*60);
1.869     albertel 11220: 
1.847     albertel 11221: 	return %iphost;
1.598     albertel 11222:     }
                   11223: 
1.992     raeburn  11224:     #
                   11225:     #  Given a DNS returns the loncapa host name for that DNS 
                   11226:     # 
                   11227:     sub host_from_dns {
                   11228:         my ($dns) = @_;
                   11229:         my @hosts;
                   11230:         my $ip;
                   11231: 
1.993     raeburn  11232:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11233:             $ip = $name_to_ip{$dns};
                   11234:         }
                   11235:         if (!$ip) {
                   11236:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11237:             if (length($ip) == 4) { 
                   11238: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11239:             }
                   11240:         }
                   11241:         if ($ip) {
                   11242: 	    @hosts = get_hosts_from_ip($ip);
                   11243: 	    return $hosts[0];
                   11244:         }
                   11245:         return undef;
1.986     foxr     11246:     }
1.992     raeburn  11247: 
1.1074    raeburn  11248:     sub get_internet_names {
                   11249:         my ($lonid) = @_;
                   11250:         return if ($lonid eq '');
                   11251:         my ($idnref,$cached)=
                   11252:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11253:         if ($cached) {
                   11254:             return $idnref;
                   11255:         }
                   11256:         my $ip = &get_host_ip($lonid);
                   11257:         my @hosts = &get_hosts_from_ip($ip);
                   11258:         my %iphost = &get_iphost();
                   11259:         my (@idns,%seen);
                   11260:         foreach my $id (@hosts) {
                   11261:             my $dom = &host_domain($id);
                   11262:             my $prim_id = &domain($dom,'primary');
                   11263:             my $prim_ip = &get_host_ip($prim_id);
                   11264:             next if ($seen{$prim_ip});
                   11265:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11266:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11267:                     my $intdom = &internet_dom($id);
                   11268:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11269:                         push(@idns,$intdom);
                   11270:                     }
                   11271:                 }
                   11272:             }
                   11273:             $seen{$prim_ip} = 1;
                   11274:         }
                   11275:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11276:     }
                   11277: 
1.986     foxr     11278: }
                   11279: 
1.1079    raeburn  11280: sub all_loncaparevs {
                   11281:     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);
                   11282: }
                   11283: 
1.862     albertel 11284: BEGIN {
                   11285: 
                   11286: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11287:     unless ($readit) {
                   11288: {
                   11289:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11290:     %perlvar = (%perlvar,%{$configvars});
                   11291: }
                   11292: 
                   11293: 
1.1       albertel 11294: # ------------------------------------------------------ Read spare server file
                   11295: {
1.448     albertel 11296:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11297: 
                   11298:     while (my $configline=<$config>) {
                   11299:        chomp($configline);
1.284     matthew  11300:        if ($configline) {
1.784     albertel 11301: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11302: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11303: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11304:        }
                   11305:     }
1.448     albertel 11306:     close($config);
1.1       albertel 11307: }
1.11      www      11308: # ------------------------------------------------------------ Read permissions
                   11309: {
1.448     albertel 11310:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11311: 
                   11312:     while (my $configline=<$config>) {
1.448     albertel 11313: 	chomp($configline);
                   11314: 	if ($configline) {
                   11315: 	    my ($role,$perm)=split(/ /,$configline);
                   11316: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11317: 	}
1.11      www      11318:     }
1.448     albertel 11319:     close($config);
1.11      www      11320: }
                   11321: 
                   11322: # -------------------------------------------- Read plain texts for permissions
                   11323: {
1.448     albertel 11324:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11325: 
                   11326:     while (my $configline=<$config>) {
1.448     albertel 11327: 	chomp($configline);
                   11328: 	if ($configline) {
1.742     raeburn  11329: 	    my ($short,@plain)=split(/:/,$configline);
                   11330:             %{$prp{$short}} = ();
                   11331: 	    if (@plain > 0) {
                   11332:                 $prp{$short}{'std'} = $plain[0];
                   11333:                 for (my $i=1; $i<@plain; $i++) {
                   11334:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11335:                 }
                   11336:             }
1.448     albertel 11337: 	}
1.135     www      11338:     }
1.448     albertel 11339:     close($config);
1.135     www      11340: }
                   11341: 
                   11342: # ---------------------------------------------------------- Read package table
                   11343: {
1.448     albertel 11344:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11345: 
                   11346:     while (my $configline=<$config>) {
1.483     albertel 11347: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11348: 	chomp($configline);
                   11349: 	my ($short,$plain)=split(/:/,$configline);
                   11350: 	my ($pack,$name)=split(/\&/,$short);
                   11351: 	if ($plain ne '') {
                   11352: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11353: 	    $packagetab{$short}=$plain; 
                   11354: 	}
1.11      www      11355:     }
1.448     albertel 11356:     close($config);
1.329     matthew  11357: }
                   11358: 
1.1073    raeburn  11359: # ---------------------------------------------------------- Read loncaparev table
                   11360: {
                   11361:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11362:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11363:             while (my $configline=<$config>) {
                   11364:                 chomp($configline);
                   11365:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11366:                 $loncaparevs{$hostid}=$loncaparev;
                   11367:             }
                   11368:             close($config);
                   11369:         }
                   11370:     }
                   11371: }
                   11372: 
1.1074    raeburn  11373: # ---------------------------------------------------------- Read serverhostID table
                   11374: {
                   11375:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11376:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11377:             while (my $configline=<$config>) {
                   11378:                 chomp($configline);
                   11379:                 my ($name,$id)=split(/:/,$configline);
                   11380:                 $serverhomeIDs{$name}=$id;
                   11381:             }
                   11382:             close($config);
                   11383:         }
                   11384:     }
                   11385: }
                   11386: 
1.1079    raeburn  11387: {
                   11388:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11389:     if (-e $file) {
                   11390:         my $parser = HTML::LCParser->new($file);
                   11391:         while (my $token = $parser->get_token()) {
                   11392:             if ($token->[0] eq 'S') {
                   11393:                 my $item = $token->[1];
                   11394:                 my $name = $token->[2]{'name'};
                   11395:                 my $value = $token->[2]{'value'};
                   11396:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11397:                     my $release = $parser->get_text();
                   11398:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11399:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11400:                 }
                   11401:             }
                   11402:         }
                   11403:     }
1.1073    raeburn  11404: }
                   11405: 
1.1138    raeburn  11406: # ---------------------------------------------------------- Read managers table
                   11407: {
                   11408:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11409:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11410:             while (my $configline=<$config>) {
                   11411:                 chomp($configline);
                   11412:                 next if ($configline =~ /^\#/);
                   11413:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11414:                     $managerstab{$configline} = 1;
                   11415:                 }
                   11416:             }
                   11417:             close($config);
                   11418:         }
                   11419:     }
                   11420: }
                   11421: 
1.329     matthew  11422: # ------------- set up temporary directory
                   11423: {
1.1117    foxr     11424:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11425: 
1.11      www      11426: }
                   11427: 
1.794     albertel 11428: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11429: 				'compress_threshold'=> 20_000,
                   11430:  			        });
1.185     www      11431: 
1.281     www      11432: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11433: $dumpcount=0;
1.958     www      11434: $locknum=0;
1.22      www      11435: 
1.163     harris41 11436: &logtouch();
1.672     albertel 11437: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11438: $readit=1;
1.564     albertel 11439:     {
                   11440: 	use integer;
                   11441: 	my $test=(2**32)+1;
1.568     albertel 11442: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11443: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11444:     }
1.195     www      11445: }
1.1       albertel 11446: }
1.179     www      11447: 
1.1       albertel 11448: 1;
1.191     harris41 11449: __END__
                   11450: 
1.243     albertel 11451: =pod
                   11452: 
1.191     harris41 11453: =head1 NAME
                   11454: 
1.243     albertel 11455: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11456: 
                   11457: =head1 SYNOPSIS
                   11458: 
1.243     albertel 11459: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11460: 
                   11461:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11462: 
1.243     albertel 11463: Common parameters:
                   11464: 
                   11465: =over 4
                   11466: 
                   11467: =item *
                   11468: 
                   11469: $uname : an internal username (if $cname expecting a course Id specifically)
                   11470: 
                   11471: =item *
                   11472: 
                   11473: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11474: 
                   11475: =item *
                   11476: 
                   11477: $symb : a resource instance identifier
                   11478: 
                   11479: =item *
                   11480: 
                   11481: $namespace : the name of a .db file that contains the data needed or
                   11482: being set.
                   11483: 
                   11484: =back
                   11485: 
1.394     bowersj2 11486: =head1 OVERVIEW
1.191     harris41 11487: 
1.394     bowersj2 11488: lonnet provides subroutines which interact with the
                   11489: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11490: about classes, users, and resources.
1.243     albertel 11491: 
                   11492: For many of these objects you can also use this to store data about
                   11493: them or modify them in various ways.
1.191     harris41 11494: 
1.394     bowersj2 11495: =head2 Symbs
1.191     harris41 11496: 
1.394     bowersj2 11497: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11498: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11499: map, the resource number of the resource in the map, and the URL of
                   11500: the resource itself. The latter is somewhat redundant, but might help
                   11501: if maps change.
                   11502: 
                   11503: An example is
                   11504: 
                   11505:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11506: 
                   11507: The respective map entry is
                   11508: 
                   11509:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11510:   title="Problem 2">
                   11511:  </resource>
                   11512: 
                   11513: Symbs are used by the random number generator, as well as to store and
                   11514: restore data specific to a certain instance of for example a problem.
                   11515: 
                   11516: =head2 Storing And Retrieving Data
                   11517: 
                   11518: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11519: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11520: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11521: is is the non-critical message twin of cstore. These functions are for
                   11522: handlers to store a perl hash to a user's permanent data space in an
                   11523: easy manner, and to retrieve it again on another call. It is expected
                   11524: that a handler would use this once at the beginning to retrieve data,
                   11525: and then again once at the end to send only the new data back.
                   11526: 
                   11527: The data is stored in the user's data directory on the user's
                   11528: homeserver under the ID of the course.
                   11529: 
                   11530: The hash that is returned by restore will have all of the previous
                   11531: value for all of the elements of the hash.
                   11532: 
                   11533: Example:
                   11534: 
                   11535:  #creating a hash
                   11536:  my %hash;
                   11537:  $hash{'foo'}='bar';
                   11538: 
                   11539:  #storing it
                   11540:  &Apache::lonnet::cstore(\%hash);
                   11541: 
                   11542:  #changing a value
                   11543:  $hash{'foo'}='notbar';
                   11544: 
                   11545:  #adding a new value
                   11546:  $hash{'bar'}='foo';
                   11547:  &Apache::lonnet::cstore(\%hash);
                   11548: 
                   11549:  #retrieving the hash
                   11550:  my %history=&Apache::lonnet::restore();
                   11551: 
                   11552:  #print the hash
                   11553:  foreach my $key (sort(keys(%history))) {
                   11554:    print("\%history{$key} = $history{$key}");
                   11555:  }
                   11556: 
                   11557: Will print out:
1.191     harris41 11558: 
1.394     bowersj2 11559:  %history{1:foo} = bar
                   11560:  %history{1:keys} = foo:timestamp
                   11561:  %history{1:timestamp} = 990455579
                   11562:  %history{2:bar} = foo
                   11563:  %history{2:foo} = notbar
                   11564:  %history{2:keys} = foo:bar:timestamp
                   11565:  %history{2:timestamp} = 990455580
                   11566:  %history{bar} = foo
                   11567:  %history{foo} = notbar
                   11568:  %history{timestamp} = 990455580
                   11569:  %history{version} = 2
                   11570: 
                   11571: Note that the special hash entries C<keys>, C<version> and
                   11572: C<timestamp> were added to the hash. C<version> will be equal to the
                   11573: total number of versions of the data that have been stored. The
                   11574: C<timestamp> attribute will be the UNIX time the hash was
                   11575: stored. C<keys> is available in every historical section to list which
                   11576: keys were added or changed at a specific historical revision of a
                   11577: hash.
                   11578: 
                   11579: B<Warning>: do not store the hash that restore returns directly. This
                   11580: will cause a mess since it will restore the historical keys as if the
                   11581: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11582: 
1.394     bowersj2 11583: Calling convention:
1.191     harris41 11584: 
1.394     bowersj2 11585:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11586:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11587: 
1.394     bowersj2 11588: For more detailed information, see lonnet specific documentation.
1.191     harris41 11589: 
1.394     bowersj2 11590: =head1 RETURN MESSAGES
1.191     harris41 11591: 
1.394     bowersj2 11592: =over 4
1.191     harris41 11593: 
1.394     bowersj2 11594: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11595: 
1.394     bowersj2 11596: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11597: when the connection is brought back up
1.191     harris41 11598: 
1.394     bowersj2 11599: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11600: for later delivery
1.191     harris41 11601: 
1.967     bisitz   11602: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11603: 
1.394     bowersj2 11604: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11605: that was requested
1.191     harris41 11606: 
1.243     albertel 11607: =back
1.191     harris41 11608: 
1.243     albertel 11609: =head1 PUBLIC SUBROUTINES
1.191     harris41 11610: 
1.243     albertel 11611: =head2 Session Environment Functions
1.191     harris41 11612: 
1.243     albertel 11613: =over 4
1.191     harris41 11614: 
1.394     bowersj2 11615: =item * 
                   11616: X<appenv()>
1.949     raeburn  11617: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11618: the user envirnoment file, and will be restored for each access this
1.620     albertel 11619: user makes during this session, also modifies the %env for the current
1.949     raeburn  11620: process. Optional rolesarrayref - if defined contains a reference to an array
                   11621: of roles which are exempt from the restriction on modifying user.role entries 
                   11622: in the user's environment.db and in %env.    
1.191     harris41 11623: 
                   11624: =item *
1.394     bowersj2 11625: X<delenv()>
1.987     raeburn  11626: B<delenv($delthis,$regexp)>: removes all items from the session
                   11627: environment file that begin with $delthis. If the 
                   11628: optional second arg - $regexp - is true, $delthis is treated as a 
                   11629: regular expression, otherwise \Q$delthis\E is used. 
                   11630: The values are also deleted from the current processes %env.
1.191     harris41 11631: 
1.795     albertel 11632: =item * get_env_multiple($name) 
                   11633: 
                   11634: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11635: values may be defined and end up as an array ref.
                   11636: 
                   11637: returns an array of values
                   11638: 
1.243     albertel 11639: =back
                   11640: 
                   11641: =head2 User Information
1.191     harris41 11642: 
1.243     albertel 11643: =over 4
1.191     harris41 11644: 
                   11645: =item *
1.394     bowersj2 11646: X<queryauthenticate()>
                   11647: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11648: authentication scheme
                   11649: 
                   11650: =item *
1.394     bowersj2 11651: X<authenticate()>
1.1073    raeburn  11652: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11653: authenticate user from domain's lib servers (first use the current
                   11654: one). C<$upass> should be the users password.
1.1073    raeburn  11655: $checkdefauth is optional (value is 1 if a check should be made to
                   11656:    authenticate user using default authentication method, and allow
                   11657:    account creation if username does not have account in the domain).
                   11658: $clientcancheckhost is optional (value is 1 if checking whether the
                   11659:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11660: 
                   11661: =item *
1.394     bowersj2 11662: X<homeserver()>
                   11663: B<homeserver($uname,$udom)>: find the server which has
                   11664: the user's directory and files (there must be only one), this caches
                   11665: the answer, and also caches if there is a borken connection.
1.191     harris41 11666: 
                   11667: =item *
1.394     bowersj2 11668: X<idget()>
                   11669: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11670: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11671: username, and only 1 username per ID in a specific domain) (returns
                   11672: hash: id=>name,id=>name)
1.191     harris41 11673: 
                   11674: =item *
1.394     bowersj2 11675: X<idrget()>
                   11676: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11677: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11678: 
                   11679: =item *
1.394     bowersj2 11680: X<idput()>
                   11681: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11682: 
                   11683: =item *
1.394     bowersj2 11684: X<rolesinit()>
1.1169    droeschl 11685: B<rolesinit($udom,$username)>: get user privileges.
                   11686: returns user role, first access and timer interval hashes
1.243     albertel 11687: 
                   11688: =item *
1.1171    droeschl 11689: X<privileged()>
                   11690: B<privileged($username,$domain)>: returns a true if user has a
                   11691: privileged and active role (i.e. su or dc), false otherwise.
                   11692: 
                   11693: =item *
1.551     albertel 11694: X<getsection()>
                   11695: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11696: course $cname, return section name/number or '' for "not in course"
                   11697: and '-1' for "no section"
                   11698: 
                   11699: =item *
1.394     bowersj2 11700: X<userenvironment()>
                   11701: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11702: passed in @what from the requested user's environment, returns a hash
                   11703: 
1.858     raeburn  11704: =item * 
                   11705: X<userlog_query()>
1.859     albertel 11706: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11707: activity.log file. %filters defines filters applied when parsing the
                   11708: log file. These can be start or end timestamps, or the type of action
                   11709: - log to look for Login or Logout events, check for Checkin or
                   11710: Checkout, role for role selection. The response is in the form
                   11711: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11712: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11713: 
1.243     albertel 11714: =back
                   11715: 
                   11716: =head2 User Roles
                   11717: 
                   11718: =over 4
                   11719: 
                   11720: =item *
                   11721: 
1.810     raeburn  11722: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11723:  F: full access
                   11724:  U,I,K: authentication modes (cxx only)
                   11725:  '': forbidden
                   11726:  1: user needs to choose course
                   11727:  2: browse allowed
1.766     albertel 11728:  A: passphrase authentication needed
1.243     albertel 11729: 
                   11730: =item *
                   11731: 
                   11732: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11733: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11734: and course level
                   11735: 
                   11736: =item *
                   11737: 
1.988     raeburn  11738: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11739: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11740: $type is Course (default) or Community.
1.988     raeburn  11741: If $forcedefault evaluates to true, text returned will be default 
                   11742: text for $type. Otherwise, if this is a course, the text returned 
                   11743: will be a custom name for the role (if defined in the course's 
                   11744: environment).  If no custom name is defined the default is returned.
                   11745:    
1.832     raeburn  11746: =item *
                   11747: 
1.935     raeburn  11748: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11749: All arguments are optional. Returns a hash of a roles, either for
                   11750: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11751: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11752: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11753: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11754: For each key, value is set to colon-separated start and end times for
                   11755: the role.  If no username and domain are specified, will default to
1.934     raeburn  11756: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11757: of role statuses (active, future or previous), roles 
                   11758: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11759: to restrict the list of roles reported. If no array ref is 
                   11760: provided for types, will default to return only active roles.
1.834     albertel 11761: 
1.243     albertel 11762: =back
                   11763: 
                   11764: =head2 User Modification
                   11765: 
                   11766: =over 4
                   11767: 
                   11768: =item *
                   11769: 
1.957     raeburn  11770: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11771: user for the level given by URL.  Optional start and end dates (leave empty
                   11772: string or zero for "no date")
1.191     harris41 11773: 
                   11774: =item *
                   11775: 
1.243     albertel 11776: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11777: change a users, password, possible return values are: ok,
                   11778: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11779: refused
1.191     harris41 11780: 
                   11781: =item *
                   11782: 
1.243     albertel 11783: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11784: 
                   11785: =item *
                   11786: 
1.1058    raeburn  11787: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11788:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11789: 
                   11790: will update user information (firstname,middlename,lastname,generation,
                   11791: permanentemail), and if forceid is true, student/employee ID also.
                   11792: A user's institutional affiliation(s) can also be updated.
                   11793: User information fields will not be overwritten with empty entries 
                   11794: unless the field is included in the $candelete array reference.
                   11795: This array is included when a single user is modified via "Manage Users",
                   11796: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11797: 
                   11798: =item *
                   11799: 
1.286     matthew  11800: modifystudent
                   11801: 
1.957     raeburn  11802: modify a student's enrollment and identification information.
1.286     matthew  11803: The course id is resolved based on the current users environment.  
                   11804: This means the envoking user must be a course coordinator or otherwise
                   11805: associated with a course.
                   11806: 
1.297     matthew  11807: This call is essentially a wrapper for lonnet::modifyuser and
                   11808: lonnet::modify_student_enrollment
1.286     matthew  11809: 
                   11810: Inputs: 
                   11811: 
                   11812: =over 4
                   11813: 
1.957     raeburn  11814: =item B<$udom> Student's loncapa domain
1.286     matthew  11815: 
1.957     raeburn  11816: =item B<$uname> Student's loncapa login name
1.286     matthew  11817: 
1.964     bisitz   11818: =item B<$uid> Student/Employee ID
1.286     matthew  11819: 
1.957     raeburn  11820: =item B<$umode> Student's authentication mode
1.286     matthew  11821: 
1.957     raeburn  11822: =item B<$upass> Student's password
1.286     matthew  11823: 
1.957     raeburn  11824: =item B<$first> Student's first name
1.286     matthew  11825: 
1.957     raeburn  11826: =item B<$middle> Student's middle name
1.286     matthew  11827: 
1.957     raeburn  11828: =item B<$last> Student's last name
1.286     matthew  11829: 
1.957     raeburn  11830: =item B<$gene> Student's generation
1.286     matthew  11831: 
1.957     raeburn  11832: =item B<$usec> Student's section in course
1.286     matthew  11833: 
                   11834: =item B<$end> Unix time of the roles expiration
                   11835: 
                   11836: =item B<$start> Unix time of the roles start date
                   11837: 
                   11838: =item B<$forceid> If defined, allow $uid to be changed
                   11839: 
                   11840: =item B<$desiredhome> server to use as home server for student
                   11841: 
1.957     raeburn  11842: =item B<$email> Student's permanent e-mail address
                   11843: 
                   11844: =item B<$type> Type of enrollment (auto or manual)
                   11845: 
1.963     raeburn  11846: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11847: 
                   11848: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11849: 
1.963     raeburn  11850: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11851: 
1.963     raeburn  11852: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11853: 
1.963     raeburn  11854: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11855: 
1.286     matthew  11856: =back
1.297     matthew  11857: 
                   11858: =item *
                   11859: 
                   11860: modify_student_enrollment
                   11861: 
                   11862: Change a students enrollment status in a class.  The environment variable
                   11863: 'role.request.course' must be defined for this function to proceed.
                   11864: 
                   11865: Inputs:
                   11866: 
                   11867: =over 4
                   11868: 
                   11869: =item $udom, students domain
                   11870: 
                   11871: =item $uname, students name
                   11872: 
                   11873: =item $uid, students user id
                   11874: 
                   11875: =item $first, students first name
                   11876: 
                   11877: =item $middle
                   11878: 
                   11879: =item $last
                   11880: 
                   11881: =item $gene
                   11882: 
                   11883: =item $usec
                   11884: 
                   11885: =item $end
                   11886: 
                   11887: =item $start
                   11888: 
1.957     raeburn  11889: =item $type
                   11890: 
                   11891: =item $locktype
                   11892: 
                   11893: =item $cid
                   11894: 
                   11895: =item $selfenroll
                   11896: 
                   11897: =item $context
                   11898: 
1.297     matthew  11899: =back
                   11900: 
1.191     harris41 11901: 
                   11902: =item *
                   11903: 
1.243     albertel 11904: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11905: custom role; give a custom role to a user for the level given by URL.  Specify
                   11906: name and domain of role author, and role name
1.191     harris41 11907: 
                   11908: =item *
                   11909: 
1.243     albertel 11910: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11911: 
                   11912: =item *
                   11913: 
1.243     albertel 11914: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11915: 
                   11916: =back
                   11917: 
                   11918: =head2 Course Infomation
                   11919: 
                   11920: =over 4
1.191     harris41 11921: 
                   11922: =item *
                   11923: 
1.1118    foxr     11924: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11925: specified course id, including all environment settings for the
                   11926: course, the description of the course will be in the hash under the
                   11927: key 'description'
1.191     harris41 11928: 
1.1118    foxr     11929: $options is an optional parameter that if supplied is a hash reference that controls
                   11930: what how this function works.  It has the following key/values:
                   11931: 
                   11932: =over 4
                   11933: 
                   11934: =item freshen_cache
                   11935: 
                   11936: If defined, and the environment cache for the course is valid, it is 
                   11937: returned in the returned hash.
                   11938: 
                   11939: =item one_time
                   11940: 
                   11941: If defined, the last cache time is set to _now_
                   11942: 
                   11943: =item user
                   11944: 
                   11945: If defined, the supplied username is used instead of the current user.
                   11946: 
                   11947: 
                   11948: =back
                   11949: 
1.191     harris41 11950: =item *
                   11951: 
1.624     albertel 11952: resdata($name,$domain,$type,@which) : request for current parameter
                   11953: setting for a specific $type, where $type is either 'course' or 'user',
                   11954: @what should be a list of parameters to ask about. This routine caches
                   11955: answers for 5 minutes.
1.243     albertel 11956: 
1.877     foxr     11957: =item *
                   11958: 
                   11959: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11960: data base, returning a hash that is keyed by the resource name and has
                   11961: values that are the resource value.  I believe that the timestamps and
                   11962: versions are also returned.
                   11963: 
                   11964: 
1.243     albertel 11965: =back
                   11966: 
                   11967: =head2 Course Modification
                   11968: 
                   11969: =over 4
1.191     harris41 11970: 
                   11971: =item *
                   11972: 
1.243     albertel 11973: writecoursepref($courseid,%prefs) : write preferences (environment
                   11974: database) for a course
1.191     harris41 11975: 
                   11976: =item *
                   11977: 
1.1011    raeburn  11978: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11979: 
                   11980: =item *
                   11981: 
1.1038    raeburn  11982: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11983: 
1.1167    droeschl 11984: =item *
                   11985: 
                   11986: is_course($courseid), is_course($cdom, $cnum)
                   11987: 
                   11988: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   11989: two component version $cdom, $cnum. It checks if the specified course exists.
                   11990: 
                   11991: Returns:
                   11992:     undef if the course doesn't exist, otherwise
                   11993:     in scalar context the combined courseid.
                   11994:     in list context the two components of the course identifier, domain and 
                   11995:     courseid.    
                   11996: 
1.243     albertel 11997: =back
                   11998: 
                   11999: =head2 Resource Subroutines
                   12000: 
                   12001: =over 4
1.191     harris41 12002: 
                   12003: =item *
                   12004: 
1.243     albertel 12005: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12006: 
                   12007: =item *
                   12008: 
1.243     albertel 12009: repcopy($filename) : subscribes to the requested file, and attempts to
                   12010: replicate from the owning library server, Might return
1.607     raeburn  12011: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12012: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12013: resource. Expects the local filesystem pathname
                   12014: (/home/httpd/html/res/....)
                   12015: 
                   12016: =back
                   12017: 
                   12018: =head2 Resource Information
                   12019: 
                   12020: =over 4
1.191     harris41 12021: 
                   12022: =item *
                   12023: 
1.243     albertel 12024: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12025: a vairety of different possible values, $varname should be a request
                   12026: string, and the other parameters can be used to specify who and what
                   12027: one is asking about.
                   12028: 
                   12029: Possible values for $varname are environment.lastname (or other item
                   12030: from the envirnment hash), user.name (or someother aspect about the
                   12031: user), resource.0.maxtries (or some other part and parameter of a
                   12032: resource)
1.204     albertel 12033: 
                   12034: =item *
                   12035: 
1.243     albertel 12036: directcondval($number) : get current value of a condition; reads from a state
                   12037: string
1.204     albertel 12038: 
                   12039: =item *
                   12040: 
1.243     albertel 12041: condval($condidx) : value of condition index based on state
1.204     albertel 12042: 
                   12043: =item *
                   12044: 
1.243     albertel 12045: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12046: resource's metadata, $what should be either a specific key, or either
                   12047: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12048: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12049: 
                   12050: this function automatically caches all requests
1.191     harris41 12051: 
                   12052: =item *
                   12053: 
1.243     albertel 12054: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12055: network of library servers; returns file handle of where SQL and regex results
                   12056: will be stored for query
1.191     harris41 12057: 
                   12058: =item *
                   12059: 
1.243     albertel 12060: symbread($filename) : return symbolic list entry (filename argument optional);
                   12061: returns the data handle
1.191     harris41 12062: 
                   12063: =item *
                   12064: 
1.243     albertel 12065: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12066: a possible symb for the URL in $thisfn, and if is an encryypted
                   12067: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12068: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12069: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12070: 
1.191     harris41 12071: 
                   12072: =item *
                   12073: 
1.243     albertel 12074: symbclean($symb) : removes versions numbers from a symb, returns the
                   12075: cleaned symb
1.191     harris41 12076: 
                   12077: =item *
                   12078: 
1.243     albertel 12079: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12080: course map, user must be in a course for it to work.
1.191     harris41 12081: 
                   12082: =item *
                   12083: 
1.243     albertel 12084: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12085: 
                   12086: =item *
                   12087: 
1.243     albertel 12088: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12089: a random seed, all arguments are optional, if they aren't sent it uses the
                   12090: environment to derive them. Note: if symb isn't sent and it can't get one
                   12091: from &symbread it will use the current time as its return value
1.191     harris41 12092: 
                   12093: =item *
                   12094: 
1.243     albertel 12095: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12096: unfakeable, receipt
1.191     harris41 12097: 
                   12098: =item *
                   12099: 
1.620     albertel 12100: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12101: 
                   12102: =item *
                   12103: 
1.243     albertel 12104: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12105: 
                   12106: =item *
                   12107: 
1.243     albertel 12108: 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 12109: 
                   12110: =item *
                   12111: 
1.243     albertel 12112: 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 12113: 
                   12114: =item *
                   12115: 
1.243     albertel 12116: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12117: 
                   12118: =item *
                   12119: 
1.243     albertel 12120: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12121: forcing spreadsheet to reevaluate the resource scores next time.
                   12122: 
                   12123: =back
                   12124: 
                   12125: =head2 Storing/Retreiving Data
                   12126: 
                   12127: =over 4
1.191     harris41 12128: 
                   12129: =item *
                   12130: 
1.243     albertel 12131: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12132: for this url; hashref needs to be given and should be a \%hashname; the
                   12133: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12134: be derived from the env
1.191     harris41 12135: 
                   12136: =item *
                   12137: 
1.243     albertel 12138: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12139: uses critical subroutine
1.191     harris41 12140: 
                   12141: =item *
                   12142: 
1.243     albertel 12143: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12144: all args are optional
1.191     harris41 12145: 
                   12146: =item *
                   12147: 
1.717     albertel 12148: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12149: dumps the complete (or key matching regexp) namespace into a hash
                   12150: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12151: normally &store()ed into
                   12152: 
                   12153: $range should be either an integer '100' (give me the first 100
                   12154:                                            matching records)
                   12155:               or be  two integers sperated by a - with no spaces
                   12156:                  '30-50' (give me the 30th through the 50th matching
                   12157:                           records)
                   12158: 
                   12159: 
                   12160: =item *
                   12161: 
                   12162: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12163: replaces a &store() version of data with a replacement set of data
                   12164: for a particular resource in a namespace passed in the $storehash hash 
                   12165: reference
                   12166: 
                   12167: =item *
                   12168: 
1.243     albertel 12169: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12170: works very similar to store/cstore, but all data is stored in a
                   12171: temporary location and can be reset using tmpreset, $storehash should
                   12172: be a hash reference, returns nothing on success
1.191     harris41 12173: 
                   12174: =item *
                   12175: 
1.243     albertel 12176: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12177: similar to restore, but all data is stored in a temporary location and
                   12178: can be reset using tmpreset. Returns a hash of values on success,
                   12179: error string otherwise.
1.191     harris41 12180: 
                   12181: =item *
                   12182: 
1.243     albertel 12183: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12184: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12185: 
                   12186: =item *
                   12187: 
1.243     albertel 12188: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12189: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12190: 
                   12191: =item *
                   12192: 
1.243     albertel 12193: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12194: namesp ($udom and $uname are optional)
1.191     harris41 12195: 
                   12196: =item *
                   12197: 
1.702     albertel 12198: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12199: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12200: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12201: 
1.702     albertel 12202: $range should be either an integer '100' (give me the first 100
                   12203:                                            matching records)
                   12204:               or be  two integers sperated by a - with no spaces
                   12205:                  '30-50' (give me the 30th through the 50th matching
                   12206:                           records)
1.449     matthew  12207: =item *
                   12208: 
                   12209: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12210: $store can be a scalar, an array reference, or if the amount to be 
                   12211: incremented is > 1, a hash reference.
                   12212: 
                   12213: ($udom and $uname are optional)
1.191     harris41 12214: 
                   12215: =item *
                   12216: 
1.243     albertel 12217: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12218: ($udom and $uname are optional)
1.191     harris41 12219: 
                   12220: =item *
                   12221: 
1.243     albertel 12222: cput($namespace,$storehash,$udom,$uname) : critical put
                   12223: ($udom and $uname are optional)
1.191     harris41 12224: 
                   12225: =item *
                   12226: 
1.748     albertel 12227: newput($namespace,$storehash,$udom,$uname) :
                   12228: 
                   12229: Attempts to store the items in the $storehash, but only if they don't
                   12230: currently exist, if this succeeds you can be certain that you have 
                   12231: successfully created a new key value pair in the $namespace db.
                   12232: 
                   12233: 
                   12234: Args:
                   12235:  $namespace: name of database to store values to
                   12236:  $storehash: hashref to store to the db
                   12237:  $udom: (optional) domain of user containing the db
                   12238:  $uname: (optional) name of user caontaining the db
                   12239: 
                   12240: Returns:
                   12241:  'ok' -> succeeded in storing all keys of $storehash
                   12242:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12243:                         least <key> already existed in the db (other
                   12244:                         requested keys may also already exist)
1.967     bisitz   12245:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12246:  'con_lost' -> unable to contact request server
                   12247:  'refused' -> action was not allowed by remote machine
                   12248: 
                   12249: 
                   12250: =item *
                   12251: 
1.243     albertel 12252: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12253: reference filled in from namesp (encrypts the return communication)
                   12254: ($udom and $uname are optional)
1.191     harris41 12255: 
                   12256: =item *
                   12257: 
1.243     albertel 12258: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12259: critical subroutine
                   12260: 
1.806     raeburn  12261: =item *
                   12262: 
1.860     raeburn  12263: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12264: array reference filled in from namespace found in domain level on either
                   12265: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12266: 
                   12267: =item *
                   12268: 
1.860     raeburn  12269: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12270: domain level either on specified domain server ($uhome) or primary domain 
                   12271: server ($udom and $uhome are optional)
1.806     raeburn  12272: 
1.943     raeburn  12273: =item * 
                   12274: 
                   12275: get_domain_defaults($target_domain) : returns hash with defaults for
                   12276: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12277: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12278: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12279: Values are retrieved from cache (if current), or from domain's configuration.db
                   12280: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12281: or lonTabs/domain.tab. 
                   12282: 
                   12283: %domdefaults = &get_auth_defaults($target_domain);
                   12284: 
1.243     albertel 12285: =back
                   12286: 
                   12287: =head2 Network Status Functions
                   12288: 
                   12289: =over 4
1.191     harris41 12290: 
                   12291: =item *
                   12292: 
1.1137    raeburn  12293: dirlist() : return directory list based on URI (first arg).
                   12294: 
                   12295: Inputs: 1 required, 5 optional.
                   12296: 
                   12297: =over
                   12298: 
                   12299: =item 
                   12300: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12301: 
                   12302: =item
                   12303: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12304: 
                   12305: =item
                   12306: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12307: 
                   12308: =item
                   12309: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12310: 
                   12311: =item
                   12312: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12313: 
                   12314: =item 
                   12315: $alternateRoot - path to prepend in place of path from $uri.
                   12316: 
                   12317: =back
                   12318: 
                   12319: Returns: Array of up to two items.
                   12320: 
                   12321: =over
                   12322: 
                   12323: a reference to an array of files/subdirectories
                   12324: 
                   12325: =over
                   12326: 
                   12327: Each element in the array of files/subdirectories is a & separated list of
                   12328: item name and the result of running stat on the item.  If dirlist was requested
                   12329: for a file instead of a directory, the item name will be ''. For a directory 
                   12330: listing, if the item is a metadata file, the element will end &N&M 
                   12331: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12332: default copyright set (1).  
                   12333: 
                   12334: =back
                   12335: 
                   12336: a scalar containing error condition (if encountered).
                   12337: 
                   12338: =over
                   12339: 
                   12340: =item 
                   12341: no_host (no homeserver identified for $username:$domain).
                   12342: 
                   12343: =item 
                   12344: no_such_host (server contacted for listing not identified as valid host).
                   12345: 
                   12346: =item 
                   12347: con_lost (connection to remote server failed).
                   12348: 
                   12349: =item 
                   12350: refused (invalid $username:$domain received on lond side).
                   12351: 
                   12352: =item 
                   12353: no_such_dir (directory at specified path on lond side does not exist). 
                   12354: 
                   12355: =item 
                   12356: empty (directory at specified path on lond side is empty).
                   12357: 
                   12358: =over
                   12359: 
                   12360: This is currently not encountered because the &ls3, &ls2, 
                   12361: &ls (_handler) routines on the lond side do not filter out
                   12362: . and .. from a directory listing. 
                   12363: 
                   12364: =back
                   12365: 
                   12366: =back
                   12367: 
                   12368: =back
1.191     harris41 12369: 
                   12370: =item *
                   12371: 
1.243     albertel 12372: spareserver() : find server with least workload from spare.tab
                   12373: 
1.986     foxr     12374: 
                   12375: =item *
                   12376: 
                   12377: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12378: if there is no corresponding loncapa host.
                   12379: 
1.243     albertel 12380: =back
                   12381: 
1.986     foxr     12382: 
1.243     albertel 12383: =head2 Apache Request
                   12384: 
                   12385: =over 4
1.191     harris41 12386: 
                   12387: =item *
                   12388: 
1.243     albertel 12389: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12390: localhost, posts hash
                   12391: 
                   12392: =back
                   12393: 
                   12394: =head2 Data to String to Data
                   12395: 
                   12396: =over 4
1.191     harris41 12397: 
                   12398: =item *
                   12399: 
1.243     albertel 12400: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12401: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12402: 
                   12403: =item *
                   12404: 
1.243     albertel 12405: hashref2str($hashref) : convert a hashref into a string complete with
                   12406: escaping and '=' and '&' separators, supports elements that are
                   12407: arrayrefs and hashrefs
1.191     harris41 12408: 
                   12409: =item *
                   12410: 
1.243     albertel 12411: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12412: with escaping and '&' separators, supports elements that are arrayrefs
                   12413: and hashrefs
1.191     harris41 12414: 
                   12415: =item *
                   12416: 
1.243     albertel 12417: str2hash($string) : convert string to hash using unescaping and
                   12418: splitting on '=' and '&', supports elements that are arrayrefs and
                   12419: hashrefs
1.191     harris41 12420: 
                   12421: =item *
                   12422: 
1.243     albertel 12423: str2array($string) : convert string to hash using unescaping and
                   12424: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12425: 
                   12426: =back
                   12427: 
                   12428: =head2 Logging Routines
                   12429: 
                   12430: 
                   12431: These routines allow one to make log messages in the lonnet.log and
                   12432: lonnet.perm logfiles.
1.191     harris41 12433: 
1.1119    foxr     12434: =over 4
                   12435: 
1.191     harris41 12436: =item *
                   12437: 
1.243     albertel 12438: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12439: 
                   12440: =item *
                   12441: 
1.243     albertel 12442: logthis() : append message to the normal lonnet.log file, it gets
                   12443: preiodically rolled over and deleted.
1.191     harris41 12444: 
                   12445: =item *
                   12446: 
1.243     albertel 12447: logperm() : append a permanent message to lonnet.perm.log, this log
                   12448: file never gets deleted by any automated portion of the system, only
                   12449: messages of critical importance should go in here.
                   12450: 
1.1119    foxr     12451: 
1.243     albertel 12452: =back
                   12453: 
                   12454: =head2 General File Helper Routines
                   12455: 
                   12456: =over 4
1.191     harris41 12457: 
                   12458: =item *
                   12459: 
1.481     raeburn  12460: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12461: (a) files in /uploaded
                   12462:   (i) If a local copy of the file exists - 
                   12463:       compares modification date of local copy with last-modified date for 
                   12464:       definitive version stored on home server for course. If local copy is 
                   12465:       stale, requests a new version from the home server and stores it. 
                   12466:       If the original has been removed from the home server, then local copy 
                   12467:       is unlinked.
                   12468:   (ii) If local copy does not exist -
                   12469:       requests the file from the home server and stores it. 
                   12470:   
                   12471:   If $caller is 'uploadrep':  
                   12472:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12473:     for request for files originally uploaded via DOCS. 
                   12474:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12475:   
                   12476:   Otherwise:
                   12477:      This indicates a call from the content generation phase of the request.
                   12478:      -  returns the entire contents of the file or -1.
                   12479:      
                   12480: (b) files in /res
                   12481:    - returns the entire contents of a file or -1; 
                   12482:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12483: 
1.712     albertel 12484: 
                   12485: =item *
                   12486: 
                   12487: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12488:                   reference
                   12489: 
                   12490: returns either a stat() list of data about the file or an empty list
                   12491: if the file doesn't exist or couldn't find out about it (connection
                   12492: problems or user unknown)
                   12493: 
1.191     harris41 12494: =item *
                   12495: 
1.243     albertel 12496: filelocation($dir,$file) : returns file system location of a file
                   12497: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12498: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12499: and a file of ../bob will become /a/bob)
1.191     harris41 12500: 
                   12501: =item *
                   12502: 
                   12503: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12504: filelocation except for hrefs
                   12505: 
                   12506: =item *
                   12507: 
                   12508: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12509: 
1.243     albertel 12510: =back
                   12511: 
1.608     albertel 12512: =head2 Usererfile file routines (/uploaded*)
                   12513: 
                   12514: =over 4
                   12515: 
                   12516: =item *
                   12517: 
                   12518: userfileupload(): main rotine for putting a file in a user or course's
                   12519:                   filespace, arguments are,
                   12520: 
1.620     albertel 12521:  formname - required - this is the name of the element in $env where the
1.608     albertel 12522:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12523:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12524:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12525:  context - if coursedoc, store the file in the course of the active role
                   12526:              of the current user; 
                   12527:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12528:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12529:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12530:          if undefined, it will be placed in "unknown"
                   12531: 
                   12532:  (This routine calls clean_filename() to remove any dangerous
                   12533:  characters from the filename, and then calls finuserfileupload() to
                   12534:  complete the transaction)
                   12535: 
                   12536:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12537:  and /adm/notfound.html if unsuccessful
                   12538: 
                   12539: =item *
                   12540: 
                   12541: clean_filename(): routine for cleaing a filename up for storage in
                   12542:                  userfile space, argument is:
                   12543: 
                   12544:  filename - proposed filename
                   12545: 
                   12546: returns: the new clean filename
                   12547: 
                   12548: =item *
                   12549: 
1.1090    raeburn  12550: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12551: userspace, probably shouldn't be called directly
                   12552: 
                   12553:   docuname: username or courseid of destination for the file
                   12554:   docudom: domain of user/course of destination for the file
                   12555:   formname: same as for userfileupload()
1.1090    raeburn  12556:   fname: filename (including subdirectories) for the file
                   12557:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12558:   allfiles: reference to hash used to store objects found by parser
                   12559:   codebase: reference to hash used for codebases of java objects found by parser
                   12560:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12561:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12562:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12563:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12564:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12565:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12566:   mimetype: reference to scalar to accommodate mime type determined
                   12567:             from File::MMagic if $parser = parse.
1.608     albertel 12568: 
                   12569:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12570:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12571:  was 'overwrite').
                   12572:  
1.608     albertel 12573: 
                   12574: =item *
                   12575: 
                   12576: renameuserfile(): renames an existing userfile to a new name
                   12577: 
                   12578:   Args:
                   12579:    docuname: username or courseid of destination for the file
                   12580:    docudom: domain of user/course of destination for the file
                   12581:    old: current file name (including any subdirs under userfiles)
                   12582:    new: desired file name (including any subdirs under userfiles)
                   12583: 
                   12584: =item *
                   12585: 
                   12586: mkdiruserfile(): creates a directory is a userfiles dir
                   12587: 
                   12588:   Args:
                   12589:    docuname: username or courseid of destination for the file
                   12590:    docudom: domain of user/course of destination for the file
                   12591:    dir: dir to create (including any subdirs under userfiles)
                   12592: 
                   12593: =item *
                   12594: 
                   12595: removeuserfile(): removes a file that exists in userfiles
                   12596: 
                   12597:   Args:
                   12598:    docuname: username or courseid of destination for the file
                   12599:    docudom: domain of user/course of destination for the file
                   12600:    fname: filname to delete (including any subdirs under userfiles)
                   12601: 
                   12602: =item *
                   12603: 
                   12604: removeuploadedurl(): convience function for removeuserfile()
                   12605: 
                   12606:   Args:
                   12607:    url:  a full /uploaded/... url to delete
                   12608: 
1.747     albertel 12609: =item * 
                   12610: 
                   12611: get_portfile_permissions():
                   12612:   Args:
                   12613:     domain: domain of user or course contain the portfolio files
                   12614:     user: name of user or num of course contain the portfolio files
                   12615:   Returns:
                   12616:     hashref of a dump of the proper file_permissions.db
                   12617:    
                   12618: 
                   12619: =item * 
                   12620: 
                   12621: get_access_controls():
                   12622: 
                   12623: Args:
                   12624:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12625:   group: (optional) the group you want the files associated with
                   12626:   file: (optional) the file you want access info on
                   12627: 
                   12628: Returns:
1.749     raeburn  12629:     a hash (keys are file names) of hashes containing
                   12630:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12631:         values are XML containing access control settings (see below) 
1.747     albertel 12632: 
                   12633: Internal notes:
                   12634: 
1.749     raeburn  12635:  access controls are stored in file_permissions.db as key=value pairs.
                   12636:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12637:         where scope -> public,guest,course,group,domains or users.
                   12638:               end -> UNIX time for end of access (0 -> no end date)
                   12639:               start -> UNIX time for start of access
                   12640: 
                   12641:     value -> XML description of access control
                   12642:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12643:             <start></start>
                   12644:             <end></end>
                   12645: 
                   12646:             <password></password>  for scope type = guest
                   12647: 
                   12648:             <domain></domain>     for scope type = course or group
                   12649:             <number></number>
                   12650:             <roles id="">
                   12651:              <role></role>
                   12652:              <access></access>
                   12653:              <section></section>
                   12654:              <group></group>
                   12655:             </roles>
                   12656: 
                   12657:             <dom></dom>         for scope type = domains
                   12658: 
                   12659:             <users>             for scope type = users
                   12660:              <user>
                   12661:               <uname></uname>
                   12662:               <udom></udom>
                   12663:              </user>
                   12664:             </users>
                   12665:            </scope> 
                   12666:               
                   12667:  Access data is also aggregated for each file in an additional key=value pair:
                   12668:  key -> path to file/file_name\0accesscontrol 
                   12669:  value -> reference to hash
                   12670:           hash contains key = value pairs
                   12671:           where key = uniqueID:scope_end_start
                   12672:                 value = UNIX time record was last updated
                   12673: 
                   12674:           Used to improve speed of look-ups of access controls for each file.  
                   12675:  
                   12676:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12677: 
                   12678: modify_access_controls():
                   12679: 
                   12680: Modifies access controls for a portfolio file
                   12681: Args
                   12682: 1. file name
                   12683: 2. reference to hash of required changes,
                   12684: 3. domain
                   12685: 4. username
                   12686:   where domain,username are the domain of the portfolio owner 
                   12687:   (either a user or a course) 
                   12688: 
                   12689: Returns:
                   12690: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12691: 2. result of deletions ('ok' or 'error', with error message).
                   12692: 3. reference to hash of any new or updated access controls.
                   12693: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12694:    key = integer (inbound ID)
                   12695:    value = uniqueID  
1.747     albertel 12696: 
1.608     albertel 12697: =back
                   12698: 
1.243     albertel 12699: =head2 HTTP Helper Routines
                   12700: 
                   12701: =over 4
                   12702: 
1.191     harris41 12703: =item *
                   12704: 
                   12705: escape() : unpack non-word characters into CGI-compatible hex codes
                   12706: 
                   12707: =item *
                   12708: 
                   12709: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12710: 
1.243     albertel 12711: =back
                   12712: 
                   12713: =head1 PRIVATE SUBROUTINES
                   12714: 
                   12715: =head2 Underlying communication routines (Shouldn't call)
                   12716: 
                   12717: =over 4
                   12718: 
                   12719: =item *
                   12720: 
                   12721: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12722: 
                   12723: =item *
                   12724: 
                   12725: reply() : uses subreply to send a message to remote machine, logs all failures
                   12726: 
                   12727: =item *
                   12728: 
                   12729: critical() : passes a critical message to another server; if cannot
                   12730: get through then place message in connection buffer directory and
                   12731: returns con_delayed, if incapable of saving message, returns
                   12732: con_failed
                   12733: 
                   12734: =item *
                   12735: 
                   12736: reconlonc() : tries to reconnect lonc client processes.
                   12737: 
                   12738: =back
                   12739: 
                   12740: =head2 Resource Access Logging
                   12741: 
                   12742: =over 4
                   12743: 
                   12744: =item *
                   12745: 
                   12746: flushcourselogs() : flush (save) buffer logs and access logs
                   12747: 
                   12748: =item *
                   12749: 
                   12750: courselog($what) : save message for course in hash
                   12751: 
                   12752: =item *
                   12753: 
                   12754: courseacclog($what) : save message for course using &courselog().  Perform
                   12755: special processing for specific resource types (problems, exams, quizzes, etc).
                   12756: 
1.191     harris41 12757: =item *
                   12758: 
                   12759: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12760: as a PerlChildExitHandler
1.243     albertel 12761: 
                   12762: =back
                   12763: 
                   12764: =head2 Other
                   12765: 
                   12766: =over 4
                   12767: 
                   12768: =item *
                   12769: 
                   12770: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12771: 
                   12772: =back
                   12773: 
                   12774: =cut
1.877     foxr     12775: 

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