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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1125  ! raeburn     4: # $Id: lonnet.pm,v 1.1124 2011/08/02 03:11: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.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1117    foxr       98: 
1.1090    raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1106    raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1073    raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1073    raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   258:                     $ua->timeout(4);
1.1073    raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1081    raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1081    raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   274:                 $loncaparev = $1;
                    275:             }
1.993     raeburn   276:         }
1.1073    raeburn   277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   278:     }
                    279: }
                    280: 
1.1074    raeburn   281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    285:         if (defined($cached)) {
                    286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') { 
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
                    299:         }
                    300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
                    305:     }
                    306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    307: }
                    308: 
1.1121    raeburn   309: sub get_remote_globals {
                    310:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125  ! raeburn   311:     my ($result,%returnhash,%whatneeded);
        !           312:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   313:         foreach my $what (sort(keys(%{$whathash}))) {
                    314:             my $hashid = $lonhost.'-'.$what;
1.1125  ! raeburn   315:             my ($response,$cached);
1.1121    raeburn   316:             unless ($ignore_cache) {
1.1125  ! raeburn   317:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   318:             }
                    319:             if (defined($cached)) {
1.1125  ! raeburn   320:                 $returnhash{$what} = $response;
1.1121    raeburn   321:             } else {
1.1125  ! raeburn   322:                 $whatneeded{$what} = 1;
1.1121    raeburn   323:             }
                    324:         }
1.1125  ! raeburn   325:         if (keys(%whatneeded) == 0) {
        !           326:             $result = 'ok';
        !           327:         } else {
1.1121    raeburn   328:             my $requested = &freeze_escape(\%whatneeded);
                    329:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125  ! raeburn   330:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
        !           331:                 ($rep eq 'unknown_cmd')) {
        !           332:                 $result = $rep;
        !           333:             } else {
        !           334:                 $result = 'ok';
1.1121    raeburn   335:                 my @pairs=split(/\&/,$rep);
1.1125  ! raeburn   336:                 foreach my $item (@pairs) {
        !           337:                     my ($key,$value)=split(/=/,$item,2);
        !           338:                     my $what = &unescape($key);
        !           339:                     my $hashid = $lonhost.'-'.$what;
        !           340:                     $returnhash{$what}=&thaw_unescape($value);
        !           341:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   342:                 }
                    343:             }
                    344:         }
                    345:     }
1.1125  ! raeburn   346:     return ($result,\%returnhash);
1.1121    raeburn   347: }
                    348: 
1.1124    raeburn   349: sub remote_devalidate_cache {
                    350:     my ($lonhost,$name,$id) = @_;
                    351:     my $response = &reply('devalidatecache',&escape($name).':'.&escape($id),$lonhost);
                    352:     return $response;
                    353: }
                    354: 
1.1       albertel  355: # -------------------------------------------------- Non-critical communication
                    356: sub subreply {
                    357:     my ($cmd,$server)=@_;
1.838     albertel  358:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      359:     #
                    360:     #  With loncnew process trimming, there's a timing hole between lonc server
                    361:     #  process exit and the master server picking up the listen on the AF_UNIX
                    362:     #  socket.  In that time interval, a lock file will exist:
                    363: 
                    364:     my $lockfile=$peerfile.".lock";
                    365:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    366: 	sleep(1);
                    367:     }
                    368:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      369:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      370:     #
1.550     foxr      371:     #   We'll give the connection a few tries before abandoning it.  If
                    372:     #   connection is not possible, we'll con_lost back to the client.
                    373:     #   
                    374:     my $client;
                    375:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    376: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    377: 				      Type    => SOCK_STREAM,
                    378: 				      Timeout => 10);
1.869     albertel  379: 	if ($client) {
1.550     foxr      380: 	    last;		# Connected!
1.850     albertel  381: 	} else {
1.853     albertel  382: 	    &create_connection(&hostname($server),$server);
1.550     foxr      383: 	}
1.850     albertel  384:         sleep(1);		# Try again later if failed connection.
1.550     foxr      385:     }
                    386:     my $answer;
                    387:     if ($client) {
1.704     albertel  388: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      389: 	$answer=<$client>;
                    390: 	if (!$answer) { $answer="con_lost"; }
                    391: 	chomp($answer);
                    392:     } else {
                    393: 	$answer = 'con_lost';	# Failed connection.
                    394:     }
1.1       albertel  395:     return $answer;
                    396: }
                    397: 
                    398: sub reply {
                    399:     my ($cmd,$server)=@_;
1.838     albertel  400:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  401:     my $answer=subreply($cmd,$server);
1.65      www       402:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  403:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       404:                 " $cmd to $server returned $answer</font>");
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: # ----------------------------------------------------------- Send USR1 to lonc
                    410: 
                    411: sub reconlonc {
1.891     albertel  412:     my ($lonid) = @_;
                    413:     my $hostname = &hostname($lonid);
                    414:     if ($lonid) {
                    415: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    416: 	if ($hostname && -e $peerfile) {
                    417: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    418: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    419: 					     Type    => SOCK_STREAM,
                    420: 					     Timeout => 10);
                    421: 	    if ($client) {
                    422: 		print $client ("reset_retries\n");
                    423: 		my $answer=<$client>;
                    424: 		#reset just this one.
                    425: 	    }
                    426: 	}
                    427: 	return;
                    428:     }
                    429: 
1.836     www       430:     &logthis("Trying to reconnect lonc");
1.1       albertel  431:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  432:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  433: 	my $loncpid=<$fh>;
                    434:         chomp($loncpid);
                    435:         if (kill 0 => $loncpid) {
                    436: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    437:             kill USR1 => $loncpid;
                    438:             sleep 1;
1.836     www       439:          } else {
1.12      www       440: 	    &logthis(
1.672     albertel  441:                "<font color=\"blue\">WARNING:".
1.12      www       442:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  443:         }
                    444:     } else {
1.836     www       445: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  446:     }
                    447: }
                    448: 
                    449: # ------------------------------------------------------ Critical communication
1.12      www       450: 
1.1       albertel  451: sub critical {
                    452:     my ($cmd,$server)=@_;
1.838     albertel  453:     unless (&hostname($server)) {
1.672     albertel  454:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       455:                " Critical message to unknown server ($server)</font>");
                    456:         return 'no_such_host';
                    457:     }
1.1       albertel  458:     my $answer=reply($cmd,$server);
                    459:     if ($answer eq 'con_lost') {
                    460: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  461: 	my $answer=reply($cmd,$server);
1.1       albertel  462:         if ($answer eq 'con_lost') {
                    463:             my $now=time;
                    464:             my $middlename=$cmd;
1.5       www       465:             $middlename=substr($middlename,0,16);
1.1       albertel  466:             $middlename=~s/\W//g;
                    467:             my $dfilename=
1.305     www       468:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    469:             $dumpcount++;
1.1       albertel  470:             {
1.448     albertel  471: 		my $dfh;
                    472: 		if (open($dfh,">$dfilename")) {
                    473: 		    print $dfh "$cmd\n"; 
                    474: 		    close($dfh);
                    475: 		}
1.1       albertel  476:             }
                    477:             sleep 2;
                    478:             my $wcmd='';
                    479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,"<$dfilename")) {
                    482: 		    $wcmd=<$dfh>; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             chomp($wcmd);
1.7       www       487:             if ($wcmd eq $cmd) {
1.672     albertel  488: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       489:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  490:                 &logperm("D:$server:$cmd");
                    491: 	        return 'con_delayed';
                    492:             } else {
1.672     albertel  493:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       494:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  495:                 &logperm("F:$server:$cmd");
                    496:                 return 'con_failed';
                    497:             }
                    498:         }
                    499:     }
                    500:     return $answer;
1.405     albertel  501: }
                    502: 
1.755     albertel  503: # ------------------------------------------- check if return value is an error
                    504: 
                    505: sub error {
                    506:     my ($result) = @_;
1.756     albertel  507:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  508: 	if ($2 == 2) { return undef; }
                    509: 	return $1;
                    510:     }
                    511:     return undef;
                    512: }
                    513: 
1.783     albertel  514: sub convert_and_load_session_env {
                    515:     my ($lonidsdir,$handle)=@_;
                    516:     my @profile;
                    517:     {
1.917     albertel  518: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    519: 	if (!$opened) {
1.915     albertel  520: 	    return 0;
                    521: 	}
1.783     albertel  522: 	flock($idf,LOCK_SH);
                    523: 	@profile=<$idf>;
                    524: 	close($idf);
                    525:     }
                    526:     my %temp_env;
                    527:     foreach my $line (@profile) {
1.786     albertel  528: 	if ($line !~ m/=/) {
                    529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	chomp($line);
                    532: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    533: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    534:     }
                    535:     unlink("$lonidsdir/$handle.id");
                    536:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    537: 	    0640)) {
                    538: 	%disk_env = %temp_env;
                    539: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    540: 	untie(%disk_env);
                    541:     }
1.786     albertel  542:     return 1;
1.783     albertel  543: }
                    544: 
1.374     www       545: # ------------------------------------------- Transfer profile into environment
1.780     albertel  546: my $env_loaded;
                    547: sub transfer_profile_to_env {
1.788     albertel  548:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    549:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       550: 
1.720     albertel  551:     if (!defined($lonidsdir)) {
                    552: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    553:     }
                    554:     if (!defined($handle)) {
                    555:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    556:     }
                    557: 
1.786     albertel  558:     my $convert;
                    559:     {
1.917     albertel  560:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561: 	if (!$opened) {
1.915     albertel  562: 	    return;
                    563: 	}
1.786     albertel  564: 	flock($idf,LOCK_SH);
                    565: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 		&GDBM_READER(),0640)) {
                    567: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    568: 	    untie(%disk_env);
                    569: 	} else {
                    570: 	    $convert = 1;
                    571: 	}
                    572:     }
                    573:     if ($convert) {
                    574: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    575: 	    &logthis("Failed to load session, or convert session.");
                    576: 	}
1.374     www       577:     }
1.783     albertel  578: 
1.786     albertel  579:     my %remove;
1.783     albertel  580:     while ( my $envname = each(%env) ) {
1.433     matthew   581:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    582:             if ($time < time-300) {
1.783     albertel  583:                 $remove{$key}++;
1.433     matthew   584:             }
                    585:         }
                    586:     }
1.783     albertel  587: 
1.619     albertel  588:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  589:     $env_loaded=1;
1.783     albertel  590:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   591:         &delenv($expired_key);
1.374     www       592:     }
1.1       albertel  593: }
                    594: 
1.916     albertel  595: # ---------------------------------------------------- Check for valid session 
                    596: sub check_for_valid_session {
                    597:     my ($r) = @_;
                    598:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    599:     my $lonid=$cookies{'lonID'};
                    600:     return undef if (!$lonid);
                    601: 
                    602:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    603:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    604:     return undef if (!-e "$lonidsdir/$handle.id");
                    605: 
1.917     albertel  606:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    607:     return undef if (!$opened);
1.916     albertel  608: 
                    609:     flock($idf,LOCK_SH);
                    610:     my %disk_env;
                    611:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    612: 	    &GDBM_READER(),0640)) {
                    613: 	return undef;	
                    614:     }
                    615: 
                    616:     if (!defined($disk_env{'user.name'})
                    617: 	|| !defined($disk_env{'user.domain'})) {
                    618: 	return undef;
                    619:     }
                    620:     return $handle;
                    621: }
                    622: 
1.830     albertel  623: sub timed_flock {
                    624:     my ($file,$lock_type) = @_;
                    625:     my $failed=0;
                    626:     eval {
                    627: 	local $SIG{__DIE__}='DEFAULT';
                    628: 	local $SIG{ALRM}=sub {
                    629: 	    $failed=1;
                    630: 	    die("failed lock");
                    631: 	};
                    632: 	alarm(13);
                    633: 	flock($file,$lock_type);
                    634: 	alarm(0);
                    635:     };
                    636:     if ($failed) {
                    637: 	return undef;
                    638:     } else {
                    639: 	return 1;
                    640:     }
                    641: }
                    642: 
1.5       www       643: # ---------------------------------------------------------- Append Environment
                    644: 
                    645: sub appenv {
1.949     raeburn   646:     my ($newenv,$roles) = @_;
                    647:     if (ref($newenv) eq 'HASH') {
                    648:         foreach my $key (keys(%{$newenv})) {
                    649:             my $refused = 0;
                    650: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    651:                 $refused = 1;
                    652:                 if (ref($roles) eq 'ARRAY') {
                    653:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    654:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    655:                         $refused = 0;
                    656:                     }
                    657:                 }
                    658:             }
                    659:             if ($refused) {
                    660:                 &logthis("<font color=\"blue\">WARNING: ".
                    661:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    662:                          .'</font>');
                    663: 	        delete($newenv->{$key});
                    664:             } else {
                    665:                 $env{$key}=$newenv->{$key};
                    666:             }
                    667:         }
                    668:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    669:         if ($opened
                    670: 	    && &timed_flock($env_file,LOCK_EX)
                    671: 	    &&
                    672: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    673: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    674: 	    while (my ($key,$value) = each(%{$newenv})) {
                    675: 	        $disk_env{$key} = $value;
                    676: 	    }
                    677: 	    untie(%disk_env);
1.35      www       678:         }
1.191     harris41  679:     }
1.56      www       680:     return 'ok';
                    681: }
                    682: # ----------------------------------------------------- Delete from Environment
                    683: 
                    684: sub delenv {
1.1104    raeburn   685:     my ($delthis,$regexp,$roles) = @_;
                    686:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    687:         my $refused = 1;
                    688:         if (ref($roles) eq 'ARRAY') {
                    689:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    690:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    691:                 $refused = 0;
                    692:             }
                    693:         }
                    694:         if ($refused) {
                    695:             &logthis("<font color=\"blue\">WARNING: ".
                    696:                      "Attempt to delete from environment ".$delthis);
                    697:             return 'error';
                    698:         }
1.56      www       699:     }
1.917     albertel  700:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:     if ($opened
1.915     albertel  702: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  703: 	&&
                    704: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  706: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   707: 	    if ($regexp) {
                    708:                 if ($key=~/^$delthis/) {
                    709:                     delete($env{$key});
                    710:                     delete($disk_env{$key});
                    711:                 } 
                    712:             } else {
                    713:                 if ($key=~/^\Q$delthis\E/) {
                    714: 		    delete($env{$key});
                    715: 		    delete($disk_env{$key});
                    716: 	        }
                    717:             }
1.448     albertel  718: 	}
1.783     albertel  719: 	untie(%disk_env);
1.5       www       720:     }
                    721:     return 'ok';
1.369     albertel  722: }
                    723: 
1.790     albertel  724: sub get_env_multiple {
                    725:     my ($name) = @_;
                    726:     my @values;
                    727:     if (defined($env{$name})) {
                    728:         # exists is it an array
                    729:         if (ref($env{$name})) {
                    730:             @values=@{ $env{$name} };
                    731:         } else {
                    732:             $values[0]=$env{$name};
                    733:         }
                    734:     }
                    735:     return(@values);
                    736: }
                    737: 
1.958     www       738: # ------------------------------------------------------------------- Locking
                    739: 
                    740: sub set_lock {
                    741:     my ($text)=@_;
                    742:     $locknum++;
                    743:     my $id=$$.'-'.$locknum;
                    744:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    745:              'session.lock.'.$id => $text});
                    746:     return $id;
                    747: }
                    748: 
                    749: sub get_locks {
                    750:     my $num=0;
                    751:     my %texts=();
                    752:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    753:        if ($lock=~/\w/) {
                    754:           $num++;
                    755:           $texts{$lock}=$env{'session.lock.'.$lock};
                    756:        }
                    757:    }
                    758:    return ($num,%texts);
                    759: }
                    760: 
                    761: sub remove_lock {
                    762:     my ($id)=@_;
                    763:     my $newlocks='';
                    764:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    765:        if (($lock=~/\w/) && ($lock ne $id)) {
                    766:           $newlocks.=','.$lock;
                    767:        }
                    768:     }
                    769:     &appenv({'session.locks' => $newlocks});
                    770:     &delenv('session.lock.'.$id);
                    771: }
                    772: 
                    773: sub remove_all_locks {
                    774:     my $activelocks=$env{'session.locks'};
                    775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    776:        if ($lock=~/\w/) {
                    777:           &remove_lock($lock);
                    778:        }
                    779:     }
                    780: }
                    781: 
                    782: 
1.369     albertel  783: # ------------------------------------------ Find out current server userload
                    784: sub userload {
                    785:     my $numusers=0;
                    786:     {
                    787: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    788: 	my $filename;
                    789: 	my $curtime=time;
                    790: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  791: 	    next if ($filename eq '.' || $filename eq '..');
                    792: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  793: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  794: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  795: 	}
                    796: 	closedir(LONIDS);
                    797:     }
                    798:     my $userloadpercent=0;
                    799:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    800:     if ($maxuserload) {
1.371     albertel  801: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  802:     }
1.372     albertel  803:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  804:     return $userloadpercent;
1.283     www       805: }
                    806: 
1.1       albertel  807: # ------------------------------ Find server with least workload from spare.tab
1.11      www       808: 
1.1       albertel  809: sub spareserver {
1.1083    raeburn   810:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  811:     my $spare_server;
1.370     albertel  812:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  813:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    814:                                                      :  $userloadpercent;
1.1083    raeburn   815:     my ($uint_dom,$remotesessions);
                    816:     if (($udom ne '') && (&domain($udom) ne '')) {
                    817:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    818:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    819:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    820:         $remotesessions = $udomdefaults{'remotesessions'};
                    821:     }
1.1123    raeburn   822:     my $spareshash = &this_host_spares($udom);
                    823:     if (ref($spareshash) eq 'HASH') {
                    824:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    825:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    826:                 if ($uint_dom) {
                    827:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    828:                                                  $try_server));
                    829:                 }
                    830: 	        ($spare_server, $lowest_load) =
                    831: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    832:             }
1.1083    raeburn   833:         }
1.784     albertel  834: 
1.1123    raeburn   835:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    836: 
                    837:         if (!$found_server) {
                    838:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    839: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    840:                     if ($uint_dom) {
                    841:                         next unless (&spare_can_host($udom,$uint_dom,
                    842:                                                      $remotesessions,$try_server));
                    843:                     }
                    844: 	            ($spare_server, $lowest_load) =
                    845: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    846:                 }
                    847: 	    }
                    848:         }
1.784     albertel  849:     }
                    850: 
                    851:     if (!$want_server_name) {
1.968     raeburn   852:         my $protocol = 'http';
                    853:         if ($protocol{$spare_server} eq 'https') {
                    854:             $protocol = $protocol{$spare_server};
                    855:         }
1.1001    raeburn   856:         if (defined($spare_server)) {
                    857:             my $hostname = &hostname($spare_server);
1.1083    raeburn   858:             if (defined($hostname)) {
1.1001    raeburn   859: 	        $spare_server = $protocol.'://'.$hostname;
                    860:             }
                    861:         }
1.784     albertel  862:     }
                    863:     return $spare_server;
                    864: }
                    865: 
                    866: sub compare_server_load {
                    867:     my ($try_server, $spare_server, $lowest_load) = @_;
                    868: 
                    869:     my $loadans     = &reply('load',    $try_server);
                    870:     my $userloadans = &reply('userload',$try_server);
                    871: 
                    872:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   873: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  874:     }
                    875: 
                    876:     my $load;
                    877:     if ($loadans =~ /\d/) {
                    878: 	if ($userloadans =~ /\d/) {
                    879: 	    #both are numbers, pick the bigger one
                    880: 	    $load = ($loadans > $userloadans) ? $loadans 
                    881: 		                              : $userloadans;
1.411     albertel  882: 	} else {
1.784     albertel  883: 	    $load = $loadans;
1.411     albertel  884: 	}
1.784     albertel  885:     } else {
                    886: 	$load = $userloadans;
                    887:     }
                    888: 
                    889:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    890: 	$spare_server = $try_server;
                    891: 	$lowest_load  = $load;
1.370     albertel  892:     }
1.784     albertel  893:     return ($spare_server,$lowest_load);
1.202     matthew   894: }
1.914     albertel  895: 
                    896: # --------------------------- ask offload servers if user already has a session
                    897: sub find_existing_session {
                    898:     my ($udom,$uname) = @_;
1.1123    raeburn   899:     my $spareshash = &this_host_spares($udom);
                    900:     if (ref($spareshash) eq 'HASH') {
                    901:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    902:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    903:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    904:             }
                    905:         }
                    906:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    907:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    908:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    909:             }
                    910:         }
1.914     albertel  911:     }
                    912:     return;
                    913: }
                    914: 
                    915: # -------------------------------- ask if server already has a session for user
                    916: sub has_user_session {
                    917:     my ($lonid,$udom,$uname) = @_;
                    918:     my $result = &reply(join(':','userhassession',
                    919: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    920:     return 1 if ($result eq 'ok');
                    921: 
                    922:     return 0;
                    923: }
                    924: 
1.1076    raeburn   925: # --------- determine least loaded server in a user's domain which allows login
                    926: 
                    927: sub choose_server {
1.1115    raeburn   928:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   929:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   930:     my %servers = &get_servers($udom);
1.1076    raeburn   931:     my $lowest_load = 30000;
1.1116    raeburn   932:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   933:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   934:         my $loginvia;
                    935:         if ($checkloginvia) {
                    936:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   937:             if ($loginvia) {
                    938:                 my ($server,$path) = split(/:/,$loginvia);
                    939:                 ($login_host, $lowest_load) =
                    940:                     &compare_server_load($server, $login_host, $lowest_load);
                    941:                 if ($login_host eq $server) {
                    942:                     $portal_path = $path;
                    943:                 }
                    944:             } else {
                    945:                 ($login_host, $lowest_load) =
                    946:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    947:                 if ($login_host eq $lonhost) {
                    948:                     $portal_path = '';
                    949:                 }
                    950:             }
                    951:         } else {
1.1076    raeburn   952:             ($login_host, $lowest_load) =
1.1116    raeburn   953:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   954:         }
                    955:     }
                    956:     if ($login_host ne '') {
1.1116    raeburn   957:         $hostname = &hostname($login_host);
1.1076    raeburn   958:     }
1.1116    raeburn   959:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   960: }
                    961: 
1.202     matthew   962: # --------------------------------------------- Try to change a user's password
                    963: 
                    964: sub changepass {
1.799     raeburn   965:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   966:     $currentpass = &escape($currentpass);
                    967:     $newpass     = &escape($newpass);
1.1030    raeburn   968:     my $lonhost = $perlvar{'lonHostID'};
                    969:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   970: 		       $server);
                    971:     if (! $answer) {
                    972: 	&logthis("No reply on password change request to $server ".
                    973: 		 "by $uname in domain $udom.");
                    974:     } elsif ($answer =~ "^ok") {
                    975:         &logthis("$uname in $udom successfully changed their password ".
                    976: 		 "on $server.");
                    977:     } elsif ($answer =~ "^pwchange_failure") {
                    978: 	&logthis("$uname in $udom was unable to change their password ".
                    979: 		 "on $server.  The action was blocked by either lcpasswd ".
                    980: 		 "or pwchange");
                    981:     } elsif ($answer =~ "^non_authorized") {
                    982:         &logthis("$uname in $udom did not get their password correct when ".
                    983: 		 "attempting to change it on $server.");
                    984:     } elsif ($answer =~ "^auth_mode_error") {
                    985:         &logthis("$uname in $udom attempted to change their password despite ".
                    986: 		 "not being locally or internally authenticated on $server.");
                    987:     } elsif ($answer =~ "^unknown_user") {
                    988:         &logthis("$uname in $udom attempted to change their password ".
                    989: 		 "on $server but were unable to because $server is not ".
                    990: 		 "their home server.");
                    991:     } elsif ($answer =~ "^refused") {
                    992: 	&logthis("$server refused to change $uname in $udom password because ".
                    993: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   994:     } elsif ($answer =~ "invalid_client") {
                    995:         &logthis("$server refused to change $uname in $udom password because ".
                    996:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   997:     }
                    998:     return $answer;
1.1       albertel  999: }
                   1000: 
1.169     harris41 1001: # ----------------------- Try to determine user's current authentication scheme
                   1002: 
                   1003: sub queryauthenticate {
                   1004:     my ($uname,$udom)=@_;
1.456     albertel 1005:     my $uhome=&homeserver($uname,$udom);
                   1006:     if (!$uhome) {
                   1007: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1008: 	return 'no_host';
                   1009:     }
                   1010:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1011:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1012: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1013:     }
1.456     albertel 1014:     return $answer;
1.169     harris41 1015: }
                   1016: 
1.1       albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1018: 
1.1       albertel 1019: sub authenticate {
1.1073    raeburn  1020:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1021:     $upass=&escape($upass);
                   1022:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1023:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1024:     my $newhome;
1.836     www      1025:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1026: # Maybe the machine was offline and only re-appeared again recently?
                   1027:         &reconlonc();
                   1028: # One more
1.952     raeburn  1029: 	$uhome=&homeserver($uname,$udom,1);
                   1030:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1031:             if (defined(&domain($udom,'primary'))) {
                   1032:                 $newhome=&domain($udom,'primary');
                   1033:             }
                   1034:             if ($newhome ne '') {
                   1035:                 $uhome = $newhome;
                   1036:             }
                   1037:         }
1.836     www      1038: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1039: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1040: 	    return 'no_host';
                   1041:         }
1.1       albertel 1042:     }
1.1073    raeburn  1043:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1044:     if ($answer eq 'authorized') {
1.952     raeburn  1045:         if ($newhome) {
                   1046:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1047:             return 'no_account_on_host'; 
                   1048:         } else {
                   1049:             &logthis("User $uname at $udom authorized by $uhome");
                   1050:             return $uhome;
                   1051:         }
1.471     albertel 1052:     }
                   1053:     if ($answer eq 'non_authorized') {
                   1054: 	&logthis("User $uname at $udom rejected by $uhome");
                   1055: 	return 'no_host'; 
1.9       www      1056:     }
1.471     albertel 1057:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1058:     return 'no_host';
                   1059: }
                   1060: 
1.1073    raeburn  1061: sub can_host_session {
1.1074    raeburn  1062:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1063:     my $canhost = 1;
1.1074    raeburn  1064:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1065:     if (ref($remotesessions) eq 'HASH') {
                   1066:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1067:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1068:                 $canhost = 0;
                   1069:             } else {
                   1070:                 $canhost = 1;
                   1071:             }
                   1072:         }
                   1073:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1074:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1075:                 $canhost = 1;
                   1076:             } else {
                   1077:                 $canhost = 0;
                   1078:             }
                   1079:         }
                   1080:         if ($canhost) {
                   1081:             if ($remotesessions->{'version'} ne '') {
                   1082:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1083:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1084:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1085:                         my $major = $1;
                   1086:                         my $minor = $2;
                   1087:                         if (($major < $reqmajor ) ||
                   1088:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1089:                             $canhost = 0;
                   1090:                         }
                   1091:                     } else {
                   1092:                         $canhost = 0;
                   1093:                     }
                   1094:                 }
                   1095:             }
                   1096:         }
                   1097:     }
                   1098:     if ($canhost) {
                   1099:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1100:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1101:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1102:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1103:                 if (($uint_dom ne '') && 
                   1104:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1105:                     $canhost = 0;
                   1106:                 } else {
                   1107:                     $canhost = 1;
                   1108:                 }
                   1109:             }
                   1110:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1111:                 if (($uint_dom ne '') && 
                   1112:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1113:                     $canhost = 1;
                   1114:                 } else {
                   1115:                     $canhost = 0;
                   1116:                 }
                   1117:             }
                   1118:         }
                   1119:     }
                   1120:     return $canhost;
                   1121: }
                   1122: 
1.1083    raeburn  1123: sub spare_can_host {
                   1124:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1125:     my $canhost=1;
                   1126:     my @intdoms;
                   1127:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1128:     if (ref($internet_names) eq 'ARRAY') {
                   1129:         @intdoms = @{$internet_names};
                   1130:     }
                   1131:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1132:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1133:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1134:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1135:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1136:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1137:                                      $remotesessions,
                   1138:                                      $defdomdefaults{'hostedsessions'});
                   1139:     }
                   1140:     return $canhost;
                   1141: }
                   1142: 
1.1123    raeburn  1143: sub this_host_spares {
                   1144:     my ($dom) = @_;
                   1145:     my $cachetime = 60*60*24;
                   1146:     my @hosts = &current_machine_ids();
                   1147:     foreach my $lonhost (@hosts) {
                   1148:         if (&host_domain($lonhost) eq $dom) {
                   1149:             my ($result,$cached)=&is_cached_new('spares',$dom);
                   1150:             if (defined($cached)) {
                   1151:                 return $result;
                   1152:             } else {
                   1153:                 my %domconfig =
                   1154:                     &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
                   1155:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1156:                     if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1157:                         if (ref($domconfig{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
                   1158:                             return &do_cache_new('spares',$dom,$domconfig{'usersessions'}{'spares'}{$lonhost},$cachetime);
                   1159:                         }
                   1160:                     }
                   1161:                 }
                   1162:             }
                   1163:             last;
                   1164:         }
                   1165:     }
                   1166:     my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   1167:     my ($result,$cached)=&is_cached_new('spares',$serverhomedom);
                   1168:     if (defined($cached)) {
                   1169:         return $result;
                   1170:     } else {
                   1171:         my %homedomconfig =
                   1172:             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
                   1173:         if (ref($homedomconfig{'usersessions'}) eq 'HASH') {
                   1174:             if (ref($homedomconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1175:                 if (ref($homedomconfig{'usersessions'}{'spares'}{$perlvar{'lonHostID'}}) eq 'HASH') {
                   1176:                     return &do_cache_new('spares',$serverhomedom,$homedomconfig{'usersessions'}{'spares'}{$perlvar{'lonHostID'}},$cachetime);
                   1177:                 }
                   1178:             }
                   1179:         }
                   1180:     }
                   1181:     return \%spareid;
                   1182: }
                   1183: 
1.1       albertel 1184: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1185: 
1.599     albertel 1186: my %homecache;
1.1       albertel 1187: sub homeserver {
1.230     stredwic 1188:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1189:     my $index="$uname:$udom";
1.426     albertel 1190: 
1.599     albertel 1191:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1192: 
                   1193:     my %servers = &get_servers($udom,'library');
                   1194:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1195:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1196: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1197: 
                   1198: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1199: 	if ($answer eq 'found') {
                   1200: 	    delete($badServerCache{$tryserver}); 
                   1201: 	    return $homecache{$index}=$tryserver;
                   1202: 	} elsif ($answer eq 'no_host') {
                   1203: 	    $badServerCache{$tryserver}=1;
                   1204: 	}
1.1       albertel 1205:     }    
                   1206:     return 'no_host';
1.70      www      1207: }
                   1208: 
                   1209: # ------------------------------------- Find the usernames behind a list of IDs
                   1210: 
                   1211: sub idget {
                   1212:     my ($udom,@ids)=@_;
                   1213:     my %returnhash=();
                   1214:     
1.841     albertel 1215:     my %servers = &get_servers($udom,'library');
                   1216:     foreach my $tryserver (keys(%servers)) {
                   1217: 	my $idlist=join('&',@ids);
                   1218: 	$idlist=~tr/A-Z/a-z/; 
                   1219: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1220: 	my @answer=();
                   1221: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1222: 	    @answer=split(/\&/,$reply);
                   1223: 	}                    ;
                   1224: 	my $i;
                   1225: 	for ($i=0;$i<=$#ids;$i++) {
                   1226: 	    if ($answer[$i]) {
                   1227: 		$returnhash{$ids[$i]}=$answer[$i];
                   1228: 	    } 
                   1229: 	}
                   1230:     } 
1.70      www      1231:     return %returnhash;
                   1232: }
                   1233: 
                   1234: # ------------------------------------- Find the IDs behind a list of usernames
                   1235: 
                   1236: sub idrget {
                   1237:     my ($udom,@unames)=@_;
                   1238:     my %returnhash=();
1.800     albertel 1239:     foreach my $uname (@unames) {
                   1240:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1241:     }
1.70      www      1242:     return %returnhash;
                   1243: }
                   1244: 
                   1245: # ------------------------------- Store away a list of names and associated IDs
                   1246: 
                   1247: sub idput {
                   1248:     my ($udom,%ids)=@_;
                   1249:     my %servers=();
1.800     albertel 1250:     foreach my $uname (keys(%ids)) {
                   1251: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1252:         my $uhom=&homeserver($uname,$udom);
1.70      www      1253:         if ($uhom ne 'no_host') {
1.800     albertel 1254:             my $id=&escape($ids{$uname});
1.70      www      1255:             $id=~tr/A-Z/a-z/;
1.800     albertel 1256:             my $esc_unam=&escape($uname);
1.70      www      1257: 	    if ($servers{$uhom}) {
1.800     albertel 1258: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1259:             } else {
1.800     albertel 1260:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1261:             }
                   1262:         }
1.191     harris41 1263:     }
1.800     albertel 1264:     foreach my $server (keys(%servers)) {
                   1265:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1266:     }
1.344     www      1267: }
                   1268: 
1.1023    raeburn  1269: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1270: sub dump_dom {
1.1023    raeburn  1271:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1272:     if (!$udom) {
                   1273:         $udom=$env{'user.domain'};
                   1274:     }
                   1275:     my %returnhash;
1.1023    raeburn  1276:     if ($udom) {
                   1277:         my $uname = &get_domainconfiguser($udom);
                   1278:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1279:     }
                   1280:     return %returnhash;
                   1281: }
                   1282: 
1.1023    raeburn  1283: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1284: 
                   1285: sub get_dom {
1.860     raeburn  1286:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1287:     my $items='';
                   1288:     foreach my $item (@$storearr) {
                   1289:         $items.=&escape($item).'&';
                   1290:     }
                   1291:     $items=~s/\&$//;
1.860     raeburn  1292:     if (!$udom) {
                   1293:         $udom=$env{'user.domain'};
                   1294:         if (defined(&domain($udom,'primary'))) {
                   1295:             $uhome=&domain($udom,'primary');
                   1296:         } else {
1.874     albertel 1297:             undef($uhome);
1.860     raeburn  1298:         }
                   1299:     } else {
                   1300:         if (!$uhome) {
                   1301:             if (defined(&domain($udom,'primary'))) {
                   1302:                 $uhome=&domain($udom,'primary');
                   1303:             }
                   1304:         }
                   1305:     }
                   1306:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1307:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1308:         my %returnhash;
1.875     albertel 1309:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1310:             return %returnhash;
                   1311:         }
1.806     raeburn  1312:         my @pairs=split(/\&/,$rep);
                   1313:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1314:             return @pairs;
                   1315:         }
                   1316:         my $i=0;
                   1317:         foreach my $item (@$storearr) {
                   1318:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1319:             $i++;
                   1320:         }
                   1321:         return %returnhash;
                   1322:     } else {
1.880     banghart 1323:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1324:     }
                   1325: }
                   1326: 
                   1327: # -------------------------------------------- put items in domain db files 
                   1328: 
                   1329: sub put_dom {
1.860     raeburn  1330:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1331:     if (!$udom) {
                   1332:         $udom=$env{'user.domain'};
                   1333:         if (defined(&domain($udom,'primary'))) {
                   1334:             $uhome=&domain($udom,'primary');
                   1335:         } else {
1.874     albertel 1336:             undef($uhome);
1.860     raeburn  1337:         }
                   1338:     } else {
                   1339:         if (!$uhome) {
                   1340:             if (defined(&domain($udom,'primary'))) {
                   1341:                 $uhome=&domain($udom,'primary');
                   1342:             }
                   1343:         }
                   1344:     } 
                   1345:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1346:         my $items='';
                   1347:         foreach my $item (keys(%$storehash)) {
                   1348:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1349:         }
                   1350:         $items=~s/\&$//;
                   1351:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1352:     } else {
1.860     raeburn  1353:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1354:     }
                   1355: }
                   1356: 
1.1023    raeburn  1357: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1358: sub newput_dom {
1.1023    raeburn  1359:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1360:     my $result;
                   1361:     if (!$udom) {
                   1362:         $udom=$env{'user.domain'};
                   1363:     }
1.1023    raeburn  1364:     if ($udom) {
                   1365:         my $uname = &get_domainconfiguser($udom);
                   1366:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1367:     }
                   1368:     return $result;
                   1369: }
                   1370: 
1.1023    raeburn  1371: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1372: sub del_dom {
1.1023    raeburn  1373:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1374:     if (ref($storearr) eq 'ARRAY') {
                   1375:         if (!$udom) {
                   1376:             $udom=$env{'user.domain'};
                   1377:         }
1.1023    raeburn  1378:         if ($udom) {
                   1379:             my $uname = &get_domainconfiguser($udom); 
                   1380:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1381:         }
                   1382:     }
                   1383: }
                   1384: 
1.1023    raeburn  1385: # ----------------------------------construct domainconfig user for a domain 
                   1386: sub get_domainconfiguser {
                   1387:     my ($udom) = @_;
                   1388:     return $udom.'-domainconfig';
                   1389: }
                   1390: 
1.837     raeburn  1391: sub retrieve_inst_usertypes {
                   1392:     my ($udom) = @_;
                   1393:     my (%returnhash,@order);
1.989     raeburn  1394:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1395:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1396:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1397:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1398:         @order = @{$domdefs{'inststatusorder'}};
                   1399:     } else {
                   1400:         if (defined(&domain($udom,'primary'))) {
                   1401:             my $uhome=&domain($udom,'primary');
                   1402:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1403:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1404:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1405:                 return (\%returnhash,\@order);
                   1406:             }
                   1407:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1408:             my @pairs=split(/\&/,$hashitems);
                   1409:             foreach my $item (@pairs) {
                   1410:                 my ($key,$value)=split(/=/,$item,2);
                   1411:                 $key = &unescape($key);
                   1412:                 next if ($key =~ /^error: 2 /);
                   1413:                 $returnhash{$key}=&thaw_unescape($value);
                   1414:             }
                   1415:             my @esc_order = split(/\&/,$orderitems);
                   1416:             foreach my $item (@esc_order) {
                   1417:                 push(@order,&unescape($item));
                   1418:             }
                   1419:         } else {
                   1420:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1421:         }
                   1422:     }
                   1423:     return (\%returnhash,\@order);
                   1424: }
                   1425: 
1.868     raeburn  1426: sub is_domainimage {
                   1427:     my ($url) = @_;
                   1428:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1429:         if (&domain($1) ne '') {
                   1430:             return '1';
                   1431:         }
                   1432:     }
                   1433:     return;
                   1434: }
                   1435: 
1.899     raeburn  1436: sub inst_directory_query {
                   1437:     my ($srch) = @_;
                   1438:     my $udom = $srch->{'srchdomain'};
                   1439:     my %results;
                   1440:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1441:     my $outcome;
1.899     raeburn  1442:     if ($homeserver ne '') {
1.904     albertel 1443: 	my $queryid=&reply("querysend:instdirsearch:".
                   1444: 			   &escape($srch->{'srchby'}).':'.
                   1445: 			   &escape($srch->{'srchterm'}).':'.
                   1446: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1447: 	my $host=&hostname($homeserver);
                   1448: 	if ($queryid !~/^\Q$host\E\_/) {
                   1449: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1450: 	    return;
                   1451: 	}
                   1452: 	my $response = &get_query_reply($queryid);
                   1453: 	my $maxtries = 5;
                   1454: 	my $tries = 1;
                   1455: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1456: 	    $response = &get_query_reply($queryid);
                   1457: 	    $tries ++;
                   1458: 	}
                   1459: 
                   1460:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1461:             if ($response eq 'unavailable') {
                   1462:                 $outcome = $response;
                   1463:             } else {
                   1464:                 $outcome = 'ok';
                   1465:                 my @matches = split(/\n/,$response);
                   1466:                 foreach my $match (@matches) {
                   1467:                     my ($key,$value) = split(/=/,$match);
                   1468:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1469:                 }
1.899     raeburn  1470:             }
                   1471:         }
                   1472:     }
1.909     raeburn  1473:     return ($outcome,%results);
1.899     raeburn  1474: }
                   1475: 
                   1476: sub usersearch {
                   1477:     my ($srch) = @_;
                   1478:     my $dom = $srch->{'srchdomain'};
                   1479:     my %results;
                   1480:     my %libserv = &all_library();
                   1481:     my $query = 'usersearch';
                   1482:     foreach my $tryserver (keys(%libserv)) {
                   1483:         if (&host_domain($tryserver) eq $dom) {
                   1484:             my $host=&hostname($tryserver);
                   1485:             my $queryid=
1.911     raeburn  1486:                 &reply("querysend:".&escape($query).':'.
                   1487:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1488:                        &escape($srch->{'srchtype'}).':'.
                   1489:                        &escape($srch->{'srchterm'}),$tryserver);
                   1490:             if ($queryid !~/^\Q$host\E\_/) {
                   1491:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1492:                 next;
1.899     raeburn  1493:             }
                   1494:             my $reply = &get_query_reply($queryid);
                   1495:             my $maxtries = 1;
                   1496:             my $tries = 1;
                   1497:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1498:                 $reply = &get_query_reply($queryid);
                   1499:                 $tries ++;
                   1500:             }
                   1501:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1502:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1503:             } else {
1.911     raeburn  1504:                 my @matches;
                   1505:                 if ($reply =~ /\n/) {
                   1506:                     @matches = split(/\n/,$reply);
                   1507:                 } else {
                   1508:                     @matches = split(/\&/,$reply);
                   1509:                 }
1.899     raeburn  1510:                 foreach my $match (@matches) {
                   1511:                     my ($uname,$udom,%userhash);
1.911     raeburn  1512:                     foreach my $entry (split(/:/,$match)) {
                   1513:                         my ($key,$value) =
                   1514:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1515:                         $userhash{$key} = $value;
                   1516:                         if ($key eq 'username') {
                   1517:                             $uname = $value;
                   1518:                         } elsif ($key eq 'domain') {
                   1519:                             $udom = $value;
1.911     raeburn  1520:                         }
1.899     raeburn  1521:                     }
                   1522:                     $results{$uname.':'.$udom} = \%userhash;
                   1523:                 }
                   1524:             }
                   1525:         }
                   1526:     }
                   1527:     return %results;
                   1528: }
                   1529: 
1.912     raeburn  1530: sub get_instuser {
                   1531:     my ($udom,$uname,$id) = @_;
                   1532:     my $homeserver = &domain($udom,'primary');
                   1533:     my ($outcome,%results);
                   1534:     if ($homeserver ne '') {
                   1535:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1536:                            &escape($id).':'.&escape($udom),$homeserver);
                   1537:         my $host=&hostname($homeserver);
                   1538:         if ($queryid !~/^\Q$host\E\_/) {
                   1539:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1540:             return;
                   1541:         }
                   1542:         my $response = &get_query_reply($queryid);
                   1543:         my $maxtries = 5;
                   1544:         my $tries = 1;
                   1545:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1546:             $response = &get_query_reply($queryid);
                   1547:             $tries ++;
                   1548:         }
                   1549:         if (!&error($response) && $response ne 'refused') {
                   1550:             if ($response eq 'unavailable') {
                   1551:                 $outcome = $response;
                   1552:             } else {
                   1553:                 $outcome = 'ok';
                   1554:                 my @matches = split(/\n/,$response);
                   1555:                 foreach my $match (@matches) {
                   1556:                     my ($key,$value) = split(/=/,$match);
                   1557:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1558:                 }
                   1559:             }
                   1560:         }
                   1561:     }
                   1562:     my %userinfo;
                   1563:     if (ref($results{$uname}) eq 'HASH') {
                   1564:         %userinfo = %{$results{$uname}};
                   1565:     } 
                   1566:     return ($outcome,%userinfo);
                   1567: }
                   1568: 
                   1569: sub inst_rulecheck {
1.923     raeburn  1570:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1571:     my %returnhash;
                   1572:     if ($udom ne '') {
                   1573:         if (ref($rules) eq 'ARRAY') {
                   1574:             @{$rules} = map {&escape($_);} (@{$rules});
                   1575:             my $rulestr = join(':',@{$rules});
                   1576:             my $homeserver=&domain($udom,'primary');
                   1577:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1578:                 my $response;
                   1579:                 if ($item eq 'username') {                
                   1580:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1581:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1582:                                               $homeserver));
1.923     raeburn  1583:                 } elsif ($item eq 'id') {
                   1584:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1585:                                               ':'.&escape($id).':'.$rulestr,
                   1586:                                               $homeserver));
1.945     raeburn  1587:                 } elsif ($item eq 'selfcreate') {
                   1588:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1589:                                                &escape($udom).':'.&escape($uname).
                   1590:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1591:                 }
1.912     raeburn  1592:                 if ($response ne 'refused') {
                   1593:                     my @pairs=split(/\&/,$response);
                   1594:                     foreach my $item (@pairs) {
                   1595:                         my ($key,$value)=split(/=/,$item,2);
                   1596:                         $key = &unescape($key);
                   1597:                         next if ($key =~ /^error: 2 /);
                   1598:                         $returnhash{$key}=&thaw_unescape($value);
                   1599:                     }
                   1600:                 }
                   1601:             }
                   1602:         }
                   1603:     }
                   1604:     return %returnhash;
                   1605: }
                   1606: 
                   1607: sub inst_userrules {
1.923     raeburn  1608:     my ($udom,$check) = @_;
1.912     raeburn  1609:     my (%ruleshash,@ruleorder);
                   1610:     if ($udom ne '') {
                   1611:         my $homeserver=&domain($udom,'primary');
                   1612:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1613:             my $response;
                   1614:             if ($check eq 'id') {
                   1615:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1616:                                  $homeserver);
1.943     raeburn  1617:             } elsif ($check eq 'email') {
                   1618:                 $response=&reply('instemailrules:'.&escape($udom),
                   1619:                                  $homeserver);
1.923     raeburn  1620:             } else {
                   1621:                 $response=&reply('instuserrules:'.&escape($udom),
                   1622:                                  $homeserver);
                   1623:             }
1.912     raeburn  1624:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1625:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1626:                 ($response ne 'no_such_host')) {
                   1627:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1628:                 my @pairs=split(/\&/,$hashitems);
                   1629:                 foreach my $item (@pairs) {
                   1630:                     my ($key,$value)=split(/=/,$item,2);
                   1631:                     $key = &unescape($key);
                   1632:                     next if ($key =~ /^error: 2 /);
                   1633:                     $ruleshash{$key}=&thaw_unescape($value);
                   1634:                 }
                   1635:                 my @esc_order = split(/\&/,$orderitems);
                   1636:                 foreach my $item (@esc_order) {
                   1637:                     push(@ruleorder,&unescape($item));
                   1638:                 }
                   1639:             }
                   1640:         }
                   1641:     }
                   1642:     return (\%ruleshash,\@ruleorder);
                   1643: }
                   1644: 
1.976     raeburn  1645: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1646: 
                   1647: sub get_domain_defaults {
                   1648:     my ($domain) = @_;
                   1649:     my $cachetime = 60*60*24;
                   1650:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1651:     if (defined($cached)) {
                   1652:         if (ref($result) eq 'HASH') {
                   1653:             return %{$result};
                   1654:         }
                   1655:     }
                   1656:     my %domdefaults;
                   1657:     my %domconfig =
1.989     raeburn  1658:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1659:                                   'requestcourses','inststatus',
1.1073    raeburn  1660:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1661:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1662:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1663:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1664:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1665:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1666:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1667:     } else {
                   1668:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1669:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1670:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1671:     }
1.976     raeburn  1672:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1673:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1674:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1675:         } else {
                   1676:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1677:         } 
                   1678:         my @usertools = ('aboutme','blog','portfolio');
                   1679:         foreach my $item (@usertools) {
                   1680:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1681:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1682:             }
                   1683:         }
                   1684:     }
1.985     raeburn  1685:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1686:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1687:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1688:         }
                   1689:     }
1.989     raeburn  1690:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1691:         foreach my $item ('inststatustypes','inststatusorder') {
                   1692:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1693:         }
                   1694:     }
1.1047    raeburn  1695:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1696:         foreach my $item ('canuse_pdfforms') {
                   1697:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1698:         }
                   1699:     }
1.1073    raeburn  1700:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1701:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1702:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1703:         }
                   1704:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1705:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1706:         }
                   1707:     }
1.943     raeburn  1708:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1709:                                   $cachetime);
                   1710:     return %domdefaults;
                   1711: }
                   1712: 
1.344     www      1713: # --------------------------------------------------- Assign a key to a student
                   1714: 
                   1715: sub assign_access_key {
1.364     www      1716: #
                   1717: # a valid key looks like uname:udom#comments
                   1718: # comments are being appended
                   1719: #
1.498     www      1720:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1721:     $kdom=
1.620     albertel 1722:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1723:     $knum=
1.620     albertel 1724:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1725:     $cdom=
1.620     albertel 1726:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1727:     $cnum=
1.620     albertel 1728:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1729:     $udom=$env{'user.name'} unless (defined($udom));
                   1730:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1731:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1732:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1733:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1734:                                                   # assigned to this person
                   1735:                                                   # - this should not happen,
1.345     www      1736:                                                   # unless something went wrong
                   1737:                                                   # the first time around
                   1738: # ready to assign
1.364     www      1739:         $logentry=$1.'; '.$logentry;
1.496     www      1740:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1741:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1742: # key now belongs to user
1.346     www      1743: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1744:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1745:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1746:                 return 'ok';
                   1747:             } else {
                   1748:                 return 
                   1749:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1750: 	    }
                   1751:         } else {
                   1752:             return 'error: Could not assign key, try again later.';
                   1753:         }
1.364     www      1754:     } elsif (!$existing{$ckey}) {
1.345     www      1755: # the key does not exist
                   1756: 	return 'error: The key does not exist';
                   1757:     } else {
                   1758: # the key is somebody else's
                   1759: 	return 'error: The key is already in use';
                   1760:     }
1.344     www      1761: }
                   1762: 
1.364     www      1763: # ------------------------------------------ put an additional comment on a key
                   1764: 
                   1765: sub comment_access_key {
                   1766: #
                   1767: # a valid key looks like uname:udom#comments
                   1768: # comments are being appended
                   1769: #
                   1770:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1771:     $cdom=
1.620     albertel 1772:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1773:     $cnum=
1.620     albertel 1774:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1775:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1776:     if ($existing{$ckey}) {
                   1777:         $existing{$ckey}.='; '.$logentry;
                   1778: # ready to assign
1.367     www      1779:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1780:                                                  $cdom,$cnum) eq 'ok') {
                   1781: 	    return 'ok';
                   1782:         } else {
                   1783: 	    return 'error: Count not store comment.';
                   1784:         }
                   1785:     } else {
                   1786: # the key does not exist
                   1787: 	return 'error: The key does not exist';
                   1788:     }
                   1789: }
                   1790: 
1.344     www      1791: # ------------------------------------------------------ Generate a set of keys
                   1792: 
                   1793: sub generate_access_keys {
1.364     www      1794:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1795:     $cdom=
1.620     albertel 1796:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1797:     $cnum=
1.620     albertel 1798:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1799:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1800:     unless (($cdom) && ($cnum)) { return 0; }
                   1801:     if ($number>10000) { return 0; }
                   1802:     sleep(2); # make sure don't get same seed twice
                   1803:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1804:     my $total=0;
                   1805:     for (my $i=1;$i<=$number;$i++) {
                   1806:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1807:                   sprintf("%lx",int(100000*rand)).'-'.
                   1808:                   sprintf("%lx",int(100000*rand));
                   1809:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1810:        $newkey=~s/0/h/g; # and also 0 and O
                   1811:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1812:        if ($existing{$newkey}) {
                   1813:            $i--;
                   1814:        } else {
1.364     www      1815: 	  if (&put('accesskeys',
                   1816:               { $newkey => '# generated '.localtime().
1.620     albertel 1817:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1818:                            '; '.$logentry },
                   1819: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1820:               $total++;
                   1821: 	  }
                   1822:        }
                   1823:     }
1.620     albertel 1824:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1825:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1826:     return $total;
                   1827: }
                   1828: 
                   1829: # ------------------------------------------------------- Validate an accesskey
                   1830: 
                   1831: sub validate_access_key {
                   1832:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1833:     $cdom=
1.620     albertel 1834:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1835:     $cnum=
1.620     albertel 1836:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1837:     $udom=$env{'user.domain'} unless (defined($udom));
                   1838:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1839:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1840:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1841: }
                   1842: 
                   1843: # ------------------------------------- Find the section of student in a course
1.652     albertel 1844: sub devalidate_getsection_cache {
                   1845:     my ($udom,$unam,$courseid)=@_;
                   1846:     my $hashid="$udom:$unam:$courseid";
                   1847:     &devalidate_cache_new('getsection',$hashid);
                   1848: }
1.298     matthew  1849: 
1.815     albertel 1850: sub courseid_to_courseurl {
                   1851:     my ($courseid) = @_;
                   1852:     #already url style courseid
                   1853:     return $courseid if ($courseid =~ m{^/});
                   1854: 
                   1855:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1856: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1857: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1858: 	return "/$cdom/$cnum";
                   1859:     }
                   1860: 
                   1861:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1862:     if (exists($courseinfo{'num'})) {
                   1863: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1864:     }
                   1865: 
                   1866:     return undef;
                   1867: }
                   1868: 
1.298     matthew  1869: sub getsection {
                   1870:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1871:     my $cachetime=1800;
1.551     albertel 1872: 
                   1873:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1874:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1875:     if (defined($cached)) { return $result; }
                   1876: 
1.298     matthew  1877:     my %Pending; 
                   1878:     my %Expired;
                   1879:     #
                   1880:     # Each role can either have not started yet (pending), be active, 
                   1881:     #    or have expired.
                   1882:     #
                   1883:     # If there is an active role, we are done.
                   1884:     #
                   1885:     # If there is more than one role which has not started yet, 
                   1886:     #     choose the one which will start sooner
                   1887:     # If there is one role which has not started yet, return it.
                   1888:     #
                   1889:     # If there is more than one expired role, choose the one which ended last.
                   1890:     # If there is a role which has expired, return it.
                   1891:     #
1.815     albertel 1892:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1893:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1894:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1895:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1896:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1897:         my $section=$1;
                   1898:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1899:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1900:         my $now=time;
1.548     albertel 1901:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1902:             $Expired{$end}=$section;
                   1903:             next;
                   1904:         }
1.548     albertel 1905:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1906:             $Pending{$start}=$section;
                   1907:             next;
                   1908:         }
1.599     albertel 1909:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1910:     }
                   1911:     #
                   1912:     # Presumedly there will be few matching roles from the above
                   1913:     # loop and the sorting time will be negligible.
                   1914:     if (scalar(keys(%Pending))) {
                   1915:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1916:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1917:     } 
                   1918:     if (scalar(keys(%Expired))) {
                   1919:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1920:         my $time = pop(@sorted);
1.599     albertel 1921:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1922:     }
1.599     albertel 1923:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1924: }
1.70      www      1925: 
1.599     albertel 1926: sub save_cache {
                   1927:     &purge_remembered();
1.722     albertel 1928:     #&Apache::loncommon::validate_page();
1.620     albertel 1929:     undef(%env);
1.780     albertel 1930:     undef($env_loaded);
1.599     albertel 1931: }
1.452     albertel 1932: 
1.599     albertel 1933: my $to_remember=-1;
                   1934: my %remembered;
                   1935: my %accessed;
                   1936: my $kicks=0;
                   1937: my $hits=0;
1.849     albertel 1938: sub make_key {
                   1939:     my ($name,$id) = @_;
1.872     albertel 1940:     if (length($id) > 65 
                   1941: 	&& length(&escape($id)) > 200) {
                   1942: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1943:     }
1.849     albertel 1944:     return &escape($name.':'.$id);
                   1945: }
                   1946: 
1.599     albertel 1947: sub devalidate_cache_new {
                   1948:     my ($name,$id,$debug) = @_;
                   1949:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1950:     $id=&make_key($name,$id);
1.599     albertel 1951:     $memcache->delete($id);
                   1952:     delete($remembered{$id});
                   1953:     delete($accessed{$id});
                   1954: }
                   1955: 
                   1956: sub is_cached_new {
                   1957:     my ($name,$id,$debug) = @_;
1.849     albertel 1958:     $id=&make_key($name,$id);
1.599     albertel 1959:     if (exists($remembered{$id})) {
                   1960: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1961: 	$accessed{$id}=[&gettimeofday()];
                   1962: 	$hits++;
                   1963: 	return ($remembered{$id},1);
                   1964:     }
                   1965:     my $value = $memcache->get($id);
                   1966:     if (!(defined($value))) {
                   1967: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1968: 	return (undef,undef);
1.416     albertel 1969:     }
1.599     albertel 1970:     if ($value eq '__undef__') {
                   1971: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1972: 	$value=undef;
                   1973:     }
                   1974:     &make_room($id,$value,$debug);
                   1975:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1976:     return ($value,1);
                   1977: }
                   1978: 
                   1979: sub do_cache_new {
                   1980:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1981:     $id=&make_key($name,$id);
1.599     albertel 1982:     my $setvalue=$value;
                   1983:     if (!defined($setvalue)) {
                   1984: 	$setvalue='__undef__';
                   1985:     }
1.623     albertel 1986:     if (!defined($time) ) {
                   1987: 	$time=600;
                   1988:     }
1.599     albertel 1989:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1990:     my $result = $memcache->set($id,$setvalue,$time);
                   1991:     if (! $result) {
1.872     albertel 1992: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1993: 	$memcache->disconnect_all();
1.872     albertel 1994:     }
1.600     albertel 1995:     # need to make a copy of $value
1.919     albertel 1996:     &make_room($id,$value,$debug);
1.599     albertel 1997:     return $value;
                   1998: }
                   1999: 
                   2000: sub make_room {
                   2001:     my ($id,$value,$debug)=@_;
1.919     albertel 2002: 
                   2003:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2004:                                     : $value;
1.599     albertel 2005:     if ($to_remember<0) { return; }
                   2006:     $accessed{$id}=[&gettimeofday()];
                   2007:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2008:     my $to_kick;
                   2009:     my $max_time=0;
                   2010:     foreach my $other (keys(%accessed)) {
                   2011: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2012: 	    $to_kick=$other;
                   2013: 	    $max_time=&tv_interval($accessed{$other});
                   2014: 	}
                   2015:     }
                   2016:     delete($remembered{$to_kick});
                   2017:     delete($accessed{$to_kick});
                   2018:     $kicks++;
                   2019:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2020:     return;
                   2021: }
                   2022: 
1.599     albertel 2023: sub purge_remembered {
1.604     albertel 2024:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2025:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2026:     undef(%remembered);
                   2027:     undef(%accessed);
1.428     albertel 2028: }
1.70      www      2029: # ------------------------------------- Read an entry from a user's environment
                   2030: 
                   2031: sub userenvironment {
                   2032:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2033:     my $items;
                   2034:     foreach my $item (@what) {
                   2035:         $items.=&escape($item).'&';
                   2036:     }
                   2037:     $items=~s/\&$//;
1.70      www      2038:     my %returnhash=();
1.1009    raeburn  2039:     my $uhome = &homeserver($unam,$udom);
                   2040:     unless ($uhome eq 'no_host') {
                   2041:         my @answer=split(/\&/, 
                   2042:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2043:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2044:             return %returnhash;
                   2045:         }
1.1009    raeburn  2046:         my $i;
                   2047:         for ($i=0;$i<=$#what;$i++) {
                   2048: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2049:         }
1.70      www      2050:     }
                   2051:     return %returnhash;
1.1       albertel 2052: }
                   2053: 
1.617     albertel 2054: # ---------------------------------------------------------- Get a studentphoto
                   2055: sub studentphoto {
                   2056:     my ($udom,$unam,$ext) = @_;
                   2057:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2058:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2059:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2060:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2061:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2062:             } else {
                   2063:                 my ($result,$perm_reqd)=
1.707     albertel 2064: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2065:                 if ($result eq 'ok') {
                   2066:                     if (!($perm_reqd eq 'yes')) {
                   2067:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2068:                     }
                   2069:                 }
                   2070:             }
                   2071:         }
                   2072:     } else {
                   2073:         my ($result,$perm_reqd) = 
1.707     albertel 2074: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2075:         if ($result eq 'ok') {
                   2076:             if (!($perm_reqd eq 'yes')) {
                   2077:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2078:             }
                   2079:         }
                   2080:     }
                   2081:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2082: }
                   2083: 
                   2084: sub retrievestudentphoto {
                   2085:     my ($udom,$unam,$ext,$type) = @_;
                   2086:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2087:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2088:     if ($ret eq 'ok') {
                   2089:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2090:         if ($type eq 'thumbnail') {
                   2091:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2092:         }
                   2093:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2094:         return $tokenurl;
                   2095:     } else {
                   2096:         if ($type eq 'thumbnail') {
                   2097:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2098:         } else { 
                   2099:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2100:         }
1.617     albertel 2101:     }
                   2102: }
                   2103: 
1.263     www      2104: # -------------------------------------------------------------------- New chat
                   2105: 
                   2106: sub chatsend {
1.724     raeburn  2107:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2108:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2109:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2110:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2111:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2112: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2113: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2114: }
                   2115: 
                   2116: # ------------------------------------------ Find current version of a resource
                   2117: 
                   2118: sub getversion {
                   2119:     my $fname=&clutter(shift);
                   2120:     unless ($fname=~/^\/res\//) { return -1; }
                   2121:     return &currentversion(&filelocation('',$fname));
                   2122: }
                   2123: 
                   2124: sub currentversion {
                   2125:     my $fname=shift;
                   2126:     my $author=$fname;
                   2127:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2128:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2129:     my $home=&homeserver($uname,$udom);
1.292     www      2130:     if ($home eq 'no_host') { 
                   2131:         return -1; 
                   2132:     }
1.1112    www      2133:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2134:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2135: 	return -1;
                   2136:     }
1.1112    www      2137:     return $answer;
1.263     www      2138: }
                   2139: 
1.1111    www      2140: #
                   2141: # Return special version number of resource if set by override, empty otherwise
                   2142: #
                   2143: sub usedversion {
                   2144:     my $fname=shift;
                   2145:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2146:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2147:     if ($urlversion) { return $urlversion; }
                   2148:     return '';
                   2149: }
                   2150: 
1.1       albertel 2151: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2152: 
1.1       albertel 2153: sub subscribe {
                   2154:     my $fname=shift;
1.761     raeburn  2155:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2156:     $fname=~s/[\n\r]//g;
1.1       albertel 2157:     my $author=$fname;
                   2158:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2159:     my ($udom,$uname)=split(/\//,$author);
                   2160:     my $home=homeserver($uname,$udom);
1.335     albertel 2161:     if ($home eq 'no_host') {
                   2162:         return 'not_found';
1.1       albertel 2163:     }
                   2164:     my $answer=reply("sub:$fname",$home);
1.64      www      2165:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2166: 	$answer.=' by '.$home;
                   2167:     }
1.1       albertel 2168:     return $answer;
                   2169: }
                   2170:     
1.8       www      2171: # -------------------------------------------------------------- Replicate file
                   2172: 
                   2173: sub repcopy {
                   2174:     my $filename=shift;
1.23      www      2175:     $filename=~s/\/+/\//g;
1.607     raeburn  2176:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2177:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2178:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2179: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2180: 	return &repcopy_userfile($filename);
                   2181:     }
1.532     albertel 2182:     $filename=~s/[\n\r]//g;
1.8       www      2183:     my $transname="$filename.in.transfer";
1.828     www      2184: # FIXME: this should flock
1.607     raeburn  2185:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2186:     my $remoteurl=subscribe($filename);
1.64      www      2187:     if ($remoteurl =~ /^con_lost by/) {
                   2188: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2189:            return 'unavailable';
1.8       www      2190:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2191: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2192: 	   return 'not_found';
1.64      www      2193:     } elsif ($remoteurl =~ /^rejected by/) {
                   2194: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2195:            return 'forbidden';
1.20      www      2196:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2197:            return 'ok';
1.8       www      2198:     } else {
1.290     www      2199:         my $author=$filename;
                   2200:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2201:         my ($udom,$uname)=split(/\//,$author);
                   2202:         my $home=homeserver($uname,$udom);
                   2203:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2204:            my @parts=split(/\//,$filename);
                   2205:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2206:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2207:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2208: 	       return 'bad_request';
1.8       www      2209:            }
                   2210:            my $count;
                   2211:            for ($count=5;$count<$#parts;$count++) {
                   2212:                $path.="/$parts[$count]";
                   2213:                if ((-e $path)!=1) {
                   2214: 		   mkdir($path,0777);
                   2215:                }
                   2216:            }
                   2217:            my $ua=new LWP::UserAgent;
                   2218:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2219:            my $response=$ua->request($request,$transname);
                   2220:            if ($response->is_error()) {
                   2221: 	       unlink($transname);
                   2222:                my $message=$response->status_line;
1.672     albertel 2223:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2224:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2225:                return 'unavailable';
1.8       www      2226:            } else {
1.16      www      2227: 	       if ($remoteurl!~/\.meta$/) {
                   2228:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2229:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2230:                   if ($mresponse->is_error()) {
                   2231: 		      unlink($filename.'.meta');
                   2232:                       &logthis(
1.672     albertel 2233:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2234:                   }
                   2235: 	       }
1.8       www      2236:                rename($transname,$filename);
1.607     raeburn  2237:                return 'ok';
1.8       www      2238:            }
1.290     www      2239:        }
1.8       www      2240:     }
1.330     www      2241: }
                   2242: 
                   2243: # ------------------------------------------------ Get server side include body
                   2244: sub ssi_body {
1.381     albertel 2245:     my ($filelink,%form)=@_;
1.606     matthew  2246:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2247:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2248:     }
1.953     www      2249:     my $output='';
                   2250:     my $response;
1.980     raeburn  2251:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2252:        ($output,$response)=&externalssi($filelink);
1.953     www      2253:     } else {
1.1004    droeschl 2254:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2255:        $filelink .= 'inhibitmenu=yes';
1.953     www      2256:        ($output,$response)=&ssi($filelink,%form);
                   2257:     }
1.778     albertel 2258:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2259:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2260:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2261:     if (wantarray) {
                   2262:         return ($output, $response);
                   2263:     } else {
                   2264:         return $output;
                   2265:     }
1.8       www      2266: }
                   2267: 
1.15      www      2268: # --------------------------------------------------------- Server Side Include
                   2269: 
1.782     albertel 2270: sub absolute_url {
                   2271:     my ($host_name) = @_;
                   2272:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2273:     if ($host_name eq '') {
                   2274: 	$host_name = $ENV{'SERVER_NAME'};
                   2275:     }
                   2276:     return $protocol.$host_name;
                   2277: }
                   2278: 
1.942     foxr     2279: #
                   2280: #   Server side include.
                   2281: # Parameters:
                   2282: #  fn     Possibly encrypted resource name/id.
                   2283: #  form   Hash that describes how the rendering should be done
                   2284: #         and other things.
1.944     foxr     2285: # Returns:
1.950     raeburn  2286: #   Scalar context: The content of the response.
                   2287: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2288: #     
1.15      www      2289: sub ssi {
                   2290: 
1.944     foxr     2291:     my ($fn,%form)=@_;
1.15      www      2292:     my $ua=new LWP::UserAgent;
1.23      www      2293:     my $request;
1.711     albertel 2294: 
                   2295:     $form{'no_update_last_known'}=1;
1.895     albertel 2296:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2297:     if (%form) {
1.782     albertel 2298:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2299:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2300:     } else {
1.782     albertel 2301:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2302:     }
                   2303: 
1.15      www      2304:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2305:     my $response=$ua->request($request);
                   2306: 
1.944     foxr     2307:     if (wantarray) {
                   2308: 	return ($response->content, $response);
                   2309:     } else {
                   2310: 	return $response->content;
1.942     foxr     2311:     }
1.324     www      2312: }
                   2313: 
                   2314: sub externalssi {
                   2315:     my ($url)=@_;
                   2316:     my $ua=new LWP::UserAgent;
                   2317:     my $request=new HTTP::Request('GET',$url);
                   2318:     my $response=$ua->request($request);
1.954     raeburn  2319:     if (wantarray) {
                   2320:         return ($response->content, $response);
                   2321:     } else {
                   2322:         return $response->content;
                   2323:     }
1.15      www      2324: }
1.254     www      2325: 
1.492     albertel 2326: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2327: 
                   2328: sub allowuploaded {
                   2329:     my ($srcurl,$url)=@_;
                   2330:     $url=&clutter(&declutter($url));
                   2331:     my $dir=$url;
                   2332:     $dir=~s/\/[^\/]+$//;
                   2333:     my %httpref=();
                   2334:     my $httpurl=&hreflocation('',$url);
                   2335:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2336:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2337: }
1.477     raeburn  2338: 
1.478     albertel 2339: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2340: # input: action, courseID, current domain, intended
1.637     raeburn  2341: #        path to file, source of file, instruction to parse file for objects,
                   2342: #        ref to hash for embedded objects,
                   2343: #        ref to hash for codebase of java objects.
1.1095    raeburn  2344: #        reference to scalar to accommodate mime type determined
                   2345: #          from File::MMagic if $parser = parse.
1.637     raeburn  2346: #
1.485     raeburn  2347: # output: url to file (if action was uploaddoc), 
                   2348: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2349: #
1.478     albertel 2350: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2351: # course.
1.477     raeburn  2352: #
1.478     albertel 2353: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2354: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2355: #          course's home server.
1.477     raeburn  2356: #
1.478     albertel 2357: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2358: #          be copied from $source (current location) to 
                   2359: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2360: #         and will then be copied to
                   2361: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2362: #         course's home server.
1.485     raeburn  2363: #
1.481     raeburn  2364: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2365: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2366: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2367: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2368: #         in course's home server.
1.637     raeburn  2369: #
1.477     raeburn  2370: 
                   2371: sub process_coursefile {
1.1095    raeburn  2372:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2373:         $mimetype)=@_;
1.477     raeburn  2374:     my $fetchresult;
1.638     albertel 2375:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2376:     if ($action eq 'propagate') {
1.638     albertel 2377:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2378: 			     $home);
1.481     raeburn  2379:     } else {
1.477     raeburn  2380:         my $fpath = '';
                   2381:         my $fname = $file;
1.478     albertel 2382:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2383:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2384:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2385:         if ($action eq 'copy') {
                   2386:             if ($source eq '') {
                   2387:                 $fetchresult = 'no source file';
                   2388:                 return $fetchresult;
                   2389:             } else {
                   2390:                 my $destination = $filepath.'/'.$fname;
                   2391:                 rename($source,$destination);
                   2392:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2393:                                  $home);
1.481     raeburn  2394:             }
                   2395:         } elsif ($action eq 'uploaddoc') {
                   2396:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2397:             print $fh $env{'form.'.$source};
1.481     raeburn  2398:             close($fh);
1.637     raeburn  2399:             if ($parser eq 'parse') {
1.1024    raeburn  2400:                 my $mm = new File::MMagic;
1.1095    raeburn  2401:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2402:                 if ($type eq 'text/html') {
1.1024    raeburn  2403:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2404:                     unless ($parse_result eq 'ok') {
                   2405:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2406:                     }
1.637     raeburn  2407:                 }
1.1095    raeburn  2408:                 if (ref($mimetype)) {
                   2409:                     $$mimetype = $type;
                   2410:                 } 
1.637     raeburn  2411:             }
1.477     raeburn  2412:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2413:                                  $home);
1.481     raeburn  2414:             if ($fetchresult eq 'ok') {
                   2415:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2416:             } else {
                   2417:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2418:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2419:                 return '/adm/notfound.html';
                   2420:             }
1.477     raeburn  2421:         }
                   2422:     }
1.485     raeburn  2423:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2424:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2425:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2426:     }
                   2427:     return $fetchresult;
                   2428: }
                   2429: 
1.637     raeburn  2430: sub build_filepath {
                   2431:     my ($fpath) = @_;
                   2432:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2433:     unless ($fpath eq '') {
                   2434:         my @parts=split('/',$fpath);
                   2435:         foreach my $part (@parts) {
                   2436:             $filepath.= '/'.$part;
                   2437:             if ((-e $filepath)!=1) {
                   2438:                 mkdir($filepath,0777);
                   2439:             }
                   2440:         }
                   2441:     }
                   2442:     return $filepath;
                   2443: }
                   2444: 
                   2445: sub store_edited_file {
1.638     albertel 2446:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2447:     my $file = $primary_url;
                   2448:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2449:     my $fpath = '';
                   2450:     my $fname = $file;
                   2451:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2452:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2453:     my $filepath = &build_filepath($fpath);
                   2454:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2455:     print $fh $content;
                   2456:     close($fh);
1.638     albertel 2457:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2458:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2459: 			  $home);
1.637     raeburn  2460:     if ($$fetchresult eq 'ok') {
                   2461:         return '/uploaded/'.$fpath.'/'.$fname;
                   2462:     } else {
1.638     albertel 2463:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2464: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2465:         return '/adm/notfound.html';
                   2466:     }
                   2467: }
                   2468: 
1.531     albertel 2469: sub clean_filename {
1.831     albertel 2470:     my ($fname,$args)=@_;
1.315     www      2471: # Replace Windows backslashes by forward slashes
1.257     www      2472:     $fname=~s/\\/\//g;
1.831     albertel 2473:     if (!$args->{'keep_path'}) {
                   2474:         # Get rid of everything but the actual filename
                   2475: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2476:     }
1.315     www      2477: # Replace spaces by underscores
                   2478:     $fname=~s/\s+/\_/g;
                   2479: # Replace all other weird characters by nothing
1.831     albertel 2480:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2481: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2482: # numbers
                   2483:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2484:     return $fname;
                   2485: }
1.1051    raeburn  2486: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2487: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2488: # image with the same aspect ratio as the original, but with dimensions which do 
                   2489: # not exceed $resizewidth and $resizeheight.
                   2490:  
1.984     neumanie 2491: sub resizeImage {
1.1051    raeburn  2492:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2493:     my $ima = Image::Magick->new;
                   2494:     my $resized;
                   2495:     if (-e $img_path) {
                   2496:         $ima->Read($img_path);
                   2497:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2498:             my $width = $ima->Get('width');
                   2499:             my $height = $ima->Get('height');
                   2500:             if ($width > $resizewidth) {
                   2501: 	        my $factor = $width/$resizewidth;
                   2502:                 my $newheight = $height/$factor;
                   2503:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2504:                 $resized = 1;
                   2505:             }
                   2506:         }
                   2507:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2508:             my $width = $ima->Get('width');
                   2509:             my $height = $ima->Get('height');
                   2510:             if ($height > $resizeheight) {
                   2511:                 my $factor = $height/$resizeheight;
                   2512:                 my $newwidth = $width/$factor;
                   2513:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2514:                 $resized = 1;
                   2515:             }
                   2516:         }
                   2517:         if ($resized) {
                   2518:             $ima->Write($img_path);
                   2519:         }
                   2520:     }
                   2521:     return;
1.977     amueller 2522: }
                   2523: 
1.608     albertel 2524: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2525: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2526: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2527: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2528: #                                    canceloverwrite, or ''. 
                   2529: #                   if 'coursedoc': upload to the current course
                   2530: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2531: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2532: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2533: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2534: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2535: #        $allfiles - reference to hash for embedded objects
                   2536: #        $codebase - reference to hash for codebase of java objects
                   2537: #        $desuname - username for permanent storage of uploaded file
                   2538: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2539: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2540: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2541: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2542: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2543: #        $mimetype - reference to scalar to accommodate mime type determined
                   2544: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2545: # 
1.686     albertel 2546: # output: url of file in userspace, or error: <message> 
                   2547: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2548: 
1.531     albertel 2549: sub userfileupload {
1.1090    raeburn  2550:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2551:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2552:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2553:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2554:     $fname=&clean_filename($fname);
1.1090    raeburn  2555:     # See if there is anything left
1.257     www      2556:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2557:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2558:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2559:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2560:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2561:         my $now = time;
1.1090    raeburn  2562:         my $filepath;
1.1095    raeburn  2563:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2564:              $filepath = 'tmp/helprequests/'.$now;
                   2565:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2566:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2567:                          '_'.$env{'user.domain'}.'/pending';
                   2568:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2569:             my ($docuname,$docudom);
                   2570:             if ($destudom) {
                   2571:                 $docudom = $destudom;
                   2572:             } else {
                   2573:                 $docudom = $env{'user.domain'};
                   2574:             }
                   2575:             if ($destuname) {
                   2576:                 $docuname = $destuname;
                   2577:             } else {
                   2578:                 $docuname = $env{'user.name'};
                   2579:             }
                   2580:             if (exists($env{'form.group'})) {
                   2581:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2582:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2583:             }
                   2584:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2585:             if ($context eq 'canceloverwrite') {
                   2586:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2587:                 if (-e  $tempfile) {
                   2588:                     my @info = stat($tempfile);
                   2589:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2590:                         unlink($tempfile);
                   2591:                     }
                   2592:                 }
                   2593:                 return;
1.523     raeburn  2594:             }
                   2595:         }
1.1090    raeburn  2596:         # Create the directory if not present
1.741     raeburn  2597:         my @parts=split(/\//,$filepath);
                   2598:         my $fullpath = $perlvar{'lonDaemons'};
                   2599:         for (my $i=0;$i<@parts;$i++) {
                   2600:             $fullpath .= '/'.$parts[$i];
                   2601:             if ((-e $fullpath)!=1) {
                   2602:                 mkdir($fullpath,0777);
                   2603:             }
                   2604:         }
                   2605:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2606:         print $fh $env{'form.'.$formname};
                   2607:         close($fh);
1.1090    raeburn  2608:         if ($context eq 'existingfile') {
                   2609:             my @info = stat($fullpath.'/'.$fname);
                   2610:             return ($fullpath.'/'.$fname,$info[9]);
                   2611:         } else {
                   2612:             return $fullpath.'/'.$fname;
                   2613:         }
1.523     raeburn  2614:     }
1.995     raeburn  2615:     if ($subdir eq 'scantron') {
                   2616:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2617:     } else {
1.995     raeburn  2618:         $fname="$subdir/$fname";
                   2619:     }
1.1090    raeburn  2620:     if ($context eq 'coursedoc') {
1.638     albertel 2621: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2622: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2623:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2624:             return &finishuserfileupload($docuname,$docudom,
                   2625: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2626: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2627:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2628:         } else {
1.620     albertel 2629:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2630:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2631: 				       $fname,$formname,$parser,
1.1095    raeburn  2632: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2633:         }
1.719     banghart 2634:     } elsif (defined($destuname)) {
                   2635:         my $docuname=$destuname;
                   2636:         my $docudom=$destudom;
1.860     raeburn  2637: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2638: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2639:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2640:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2641:     } else {
1.638     albertel 2642:         my $docuname=$env{'user.name'};
                   2643:         my $docudom=$env{'user.domain'};
1.714     raeburn  2644:         if (exists($env{'form.group'})) {
                   2645:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2646:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2647:         }
1.860     raeburn  2648: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2649: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2650:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2651:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2652:     }
1.271     www      2653: }
                   2654: 
                   2655: sub finishuserfileupload {
1.860     raeburn  2656:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2657:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2658:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2659:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2660:   
1.860     raeburn  2661:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2662:     $file=$fname;
                   2663:     if ($fname=~m|/|) {
                   2664:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2665: 	$path.=$fnamepath.'/';
                   2666:     }
1.259     www      2667:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2668:     my $count;
                   2669:     for ($count=4;$count<=$#parts;$count++) {
                   2670:         $filepath.="/$parts[$count]";
                   2671:         if ((-e $filepath)!=1) {
                   2672: 	    mkdir($filepath,0777);
                   2673:         }
                   2674:     }
1.984     neumanie 2675: 
1.258     www      2676: # Save the file
                   2677:     {
1.701     albertel 2678: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2679: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2680: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2681: 	    return '/adm/notfound.html';
                   2682: 	}
1.1090    raeburn  2683:         if ($context eq 'overwrite') {
1.1117    foxr     2684:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2685:             my $target = $filepath.'/'.$file;
                   2686:             if (-e $source) {
                   2687:                 my @info = stat($source);
                   2688:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2689:                     unless (&File::Copy::move($source,$target)) {
                   2690:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2691:                         return "Moving from $source failed";
                   2692:                     }
                   2693:                 } else {
                   2694:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2695:                 }
                   2696:             } else {
                   2697:                 return "Temporary file: $source missing";
                   2698:             }
                   2699:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2700: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2701: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2702: 	    return '/adm/notfound.html';
                   2703: 	}
1.570     albertel 2704: 	close(FH);
1.1051    raeburn  2705:         if ($resizewidth && $resizeheight) {
                   2706:             my $mm = new File::MMagic;
                   2707:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2708:             if ($mime_type =~ m{^image/}) {
                   2709: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2710:             }  
1.977     amueller 2711: 	}
1.258     www      2712:     }
1.637     raeburn  2713:     if ($parser eq 'parse') {
1.1024    raeburn  2714:         my $mm = new File::MMagic;
1.1095    raeburn  2715:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2716:         if ($type eq 'text/html') {
1.1024    raeburn  2717:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2718:                                                        $allfiles,$codebase);
                   2719:             unless ($parse_result eq 'ok') {
                   2720:                 &logthis('Failed to parse '.$filepath.$file.
                   2721: 	   	         ' for embedded media: '.$parse_result); 
                   2722:             }
1.637     raeburn  2723:         }
1.1095    raeburn  2724:         if (ref($mimetype)) {
                   2725:             $$mimetype = $type;
                   2726:         }
1.637     raeburn  2727:     }
1.860     raeburn  2728:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2729:         my $input = $filepath.'/'.$file;
                   2730:         my $output = $filepath.'/'.'tn-'.$file;
                   2731:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2732:         system("convert -sample $thumbsize $input $output");
                   2733:         if (-e $filepath.'/'.'tn-'.$file) {
                   2734:             $fetchthumb  = 1; 
                   2735:         }
                   2736:     }
1.858     raeburn  2737:  
1.259     www      2738: # Notify homeserver to grep it
                   2739: #
1.984     neumanie 2740:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2741:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2742:     if ($fetchresult eq 'ok') {
1.860     raeburn  2743:         if ($fetchthumb) {
                   2744:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2745:             if ($thumbresult ne 'ok') {
                   2746:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2747:                          $docuhome.': '.$thumbresult);
                   2748:             }
                   2749:         }
1.259     www      2750: #
1.258     www      2751: # Return the URL to it
1.494     albertel 2752:         return '/uploaded/'.$path.$file;
1.263     www      2753:     } else {
1.494     albertel 2754:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2755: 		 ': '.$fetchresult);
1.263     www      2756:         return '/adm/notfound.html';
1.858     raeburn  2757:     }
1.493     albertel 2758: }
                   2759: 
1.637     raeburn  2760: sub extract_embedded_items {
1.961     raeburn  2761:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2762:     my @state = ();
                   2763:     my %javafiles = (
                   2764:                       codebase => '',
                   2765:                       code => '',
                   2766:                       archive => ''
                   2767:                     );
                   2768:     my %mediafiles = (
                   2769:                       src => '',
                   2770:                       movie => '',
                   2771:                      );
1.648     raeburn  2772:     my $p;
                   2773:     if ($content) {
                   2774:         $p = HTML::LCParser->new($content);
                   2775:     } else {
1.961     raeburn  2776:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2777:     }
1.641     albertel 2778:     while (my $t=$p->get_token()) {
1.640     albertel 2779: 	if ($t->[0] eq 'S') {
                   2780: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2781: 	    push(@state, $tagname);
1.648     raeburn  2782:             if (lc($tagname) eq 'allow') {
                   2783:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2784:             }
1.640     albertel 2785: 	    if (lc($tagname) eq 'img') {
                   2786: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2787: 	    }
1.886     albertel 2788: 	    if (lc($tagname) eq 'a') {
                   2789: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2790: 	    }
1.645     raeburn  2791:             if (lc($tagname) eq 'script') {
                   2792:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2793:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2794:                 } else {
                   2795:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2796:                 }
                   2797:             }
                   2798:             if (lc($tagname) eq 'link') {
                   2799:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2800:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2801:                 }
                   2802:             }
1.640     albertel 2803: 	    if (lc($tagname) eq 'object' ||
                   2804: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2805: 		foreach my $item (keys(%javafiles)) {
                   2806: 		    $javafiles{$item} = '';
                   2807: 		}
                   2808: 	    }
                   2809: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2810: 		my $name = lc($attr->{'name'});
                   2811: 		foreach my $item (keys(%javafiles)) {
                   2812: 		    if ($name eq $item) {
                   2813: 			$javafiles{$item} = $attr->{'value'};
                   2814: 			last;
                   2815: 		    }
                   2816: 		}
                   2817: 		foreach my $item (keys(%mediafiles)) {
                   2818: 		    if ($name eq $item) {
                   2819: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2820: 			last;
                   2821: 		    }
                   2822: 		}
                   2823: 	    }
                   2824: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2825: 		foreach my $item (keys(%javafiles)) {
                   2826: 		    if ($attr->{$item}) {
                   2827: 			$javafiles{$item} = $attr->{$item};
                   2828: 			last;
                   2829: 		    }
                   2830: 		}
                   2831: 		foreach my $item (keys(%mediafiles)) {
                   2832: 		    if ($attr->{$item}) {
                   2833: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2834: 			last;
                   2835: 		    }
                   2836: 		}
                   2837: 	    }
                   2838: 	} elsif ($t->[0] eq 'E') {
                   2839: 	    my ($tagname) = ($t->[1]);
                   2840: 	    if ($javafiles{'codebase'} ne '') {
                   2841: 		$javafiles{'codebase'} .= '/';
                   2842: 	    }  
                   2843: 	    if (lc($tagname) eq 'applet' ||
                   2844: 		lc($tagname) eq 'object' ||
                   2845: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2846: 		) {
                   2847: 		foreach my $item (keys(%javafiles)) {
                   2848: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2849: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2850: 			&add_filetype($allfiles,$file,$item);
                   2851: 		    }
                   2852: 		}
                   2853: 	    } 
                   2854: 	    pop @state;
                   2855: 	}
                   2856:     }
1.637     raeburn  2857:     return 'ok';
                   2858: }
                   2859: 
1.639     albertel 2860: sub add_filetype {
                   2861:     my ($allfiles,$file,$type)=@_;
                   2862:     if (exists($allfiles->{$file})) {
                   2863: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2864: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2865: 	}
                   2866:     } else {
                   2867: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2868:     }
                   2869: }
                   2870: 
1.493     albertel 2871: sub removeuploadedurl {
1.984     neumanie 2872:     my ($url)=@_;	
                   2873:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2874:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2875: }
                   2876: 
                   2877: sub removeuserfile {
                   2878:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2879:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2880:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2881:     if ($result eq 'ok') {	
1.798     raeburn  2882:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2883:             my $metafile = $fname.'.meta';
                   2884:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2885: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2886:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2887:             my $sqlresult = 
1.823     albertel 2888:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2889:                                         'portfolio_metadata',$group,
                   2890:                                         'delete');
1.798     raeburn  2891:         }
                   2892:     }
                   2893:     return $result;
1.257     www      2894: }
1.15      www      2895: 
1.530     albertel 2896: sub mkdiruserfile {
                   2897:     my ($docuname,$docudom,$dir)=@_;
                   2898:     my $home=&homeserver($docuname,$docudom);
                   2899:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2900: }
                   2901: 
1.531     albertel 2902: sub renameuserfile {
                   2903:     my ($docuname,$docudom,$old,$new)=@_;
                   2904:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2905:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2906:                         &escape("$old").':'.&escape("$new"),$home);
                   2907:     if ($result eq 'ok') {
                   2908:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2909:             my $oldmeta = $old.'.meta';
                   2910:             my $newmeta = $new.'.meta';
                   2911:             my $metaresult = 
                   2912:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2913: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2914:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2915:             my $sqlresult = 
1.823     albertel 2916:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2917:                                         'portfolio_metadata',$group,
                   2918:                                         'delete');
1.798     raeburn  2919:         }
                   2920:     }
                   2921:     return $result;
1.531     albertel 2922: }
                   2923: 
1.14      www      2924: # ------------------------------------------------------------------------- Log
                   2925: 
                   2926: sub log {
                   2927:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2928:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2929: }
                   2930: 
                   2931: # ------------------------------------------------------------------ Course Log
1.352     www      2932: #
                   2933: # This routine flushes several buffers of non-mission-critical nature
                   2934: #
1.157     www      2935: 
                   2936: sub flushcourselogs {
1.352     www      2937:     &logthis('Flushing log buffers');
                   2938: #
                   2939: # course logs
                   2940: # This is a log of all transactions in a course, which can be used
                   2941: # for data mining purposes
                   2942: #
                   2943: # It also collects the courseid database, which lists last transaction
                   2944: # times and course titles for all courseids
                   2945: #
                   2946:     my %courseidbuffer=();
1.921     raeburn  2947:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2948:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2949: 		          &escape($courselogs{$crsid}),
                   2950: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2951: 	    delete $courselogs{$crsid};
                   2952:         } else {
                   2953:             &logthis('Failed to flush log buffer for '.$crsid);
                   2954:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2955:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2956:                         " exceeded maximum size, deleting.</font>");
                   2957:                delete $courselogs{$crsid};
                   2958:             }
1.352     www      2959:         }
1.920     raeburn  2960:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2961:             'description' => $coursedescrbuf{$crsid},
                   2962:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2963:             'type'        => $coursetypebuf{$crsid},
                   2964:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2965:         };
1.191     harris41 2966:     }
1.352     www      2967: #
                   2968: # Write course id database (reverse lookup) to homeserver of courses 
                   2969: # Is used in pickcourse
                   2970: #
1.840     albertel 2971:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2972:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2973:                                     $courseidbuffer{$crs_home},
                   2974:                                     $crs_home,'timeonly');
1.352     www      2975:     }
                   2976: #
                   2977: # File accesses
                   2978: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2979: #
1.449     matthew  2980:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2981:         if ($entry =~ /___count$/) {
                   2982:             my ($dom,$name);
1.807     albertel 2983:             ($dom,$name,undef)=
1.811     albertel 2984: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2985:             if (! defined($dom) || $dom eq '' || 
                   2986:                 ! defined($name) || $name eq '') {
1.620     albertel 2987:                 my $cid = $env{'request.course.id'};
                   2988:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2989:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2990:             }
1.450     matthew  2991:             my $value = $accesshash{$entry};
                   2992:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2993:             my %temphash=($url => $value);
1.449     matthew  2994:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2995:             if ($result eq 'ok') {
                   2996:                 delete $accesshash{$entry};
                   2997:             } elsif ($result eq 'unknown_cmd') {
                   2998:                 # Target server has old code running on it.
1.450     matthew  2999:                 my %temphash=($entry => $value);
1.449     matthew  3000:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3001:                     delete $accesshash{$entry};
                   3002:                 }
                   3003:             }
                   3004:         } else {
1.811     albertel 3005:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3006:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3007:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3008:                 delete $accesshash{$entry};
                   3009:             }
1.185     www      3010:         }
1.191     harris41 3011:     }
1.352     www      3012: #
                   3013: # Roles
                   3014: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3015: #
1.800     albertel 3016:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3017:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3018: 	    split(/\:/,$entry);
                   3019:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3020:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3021:                 $rudom,$runame) eq 'ok') {
                   3022: 	    delete $userrolehash{$entry};
                   3023:         }
                   3024:     }
1.662     raeburn  3025: #
                   3026: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3027: #
                   3028:     my %domrolebuffer = ();
1.1000    raeburn  3029:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3030:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3031:         if ($domrolebuffer{$rudom}) {
                   3032:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3033:                       '='.&escape($domainrolehash{$entry});
                   3034:         } else {
                   3035:             $domrolebuffer{$rudom}.=&escape($entry).
                   3036:                       '='.&escape($domainrolehash{$entry});
                   3037:         }
                   3038:         delete $domainrolehash{$entry};
                   3039:     }
                   3040:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3041: 	my %servers = &get_servers($dom,'library');
                   3042: 	foreach my $tryserver (keys(%servers)) {
                   3043: 	    unless (&reply('domroleput:'.$dom.':'.
                   3044: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3045: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3046: 	    }
1.662     raeburn  3047:         }
                   3048:     }
1.186     www      3049:     $dumpcount++;
1.157     www      3050: }
                   3051: 
                   3052: sub courselog {
                   3053:     my $what=shift;
1.158     www      3054:     $what=time.':'.$what;
1.620     albertel 3055:     unless ($env{'request.course.id'}) { return ''; }
                   3056:     $coursedombuf{$env{'request.course.id'}}=
                   3057:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3058:     $coursenumbuf{$env{'request.course.id'}}=
                   3059:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3060:     $coursehombuf{$env{'request.course.id'}}=
                   3061:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3062:     $coursedescrbuf{$env{'request.course.id'}}=
                   3063:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3064:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3065:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3066:     $courseownerbuf{$env{'request.course.id'}}=
                   3067:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3068:     $coursetypebuf{$env{'request.course.id'}}=
                   3069:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3070:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3071: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3072:     } else {
1.620     albertel 3073: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3074:     }
1.620     albertel 3075:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3076: 	&flushcourselogs();
                   3077:     }
1.158     www      3078: }
                   3079: 
                   3080: sub courseacclog {
                   3081:     my $fnsymb=shift;
1.620     albertel 3082:     unless ($env{'request.course.id'}) { return ''; }
                   3083:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3084:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3085:         $what.=':POST';
1.583     matthew  3086:         # FIXME: Probably ought to escape things....
1.800     albertel 3087: 	foreach my $key (keys(%env)) {
                   3088:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3089:                 my $formitem = $1;
                   3090:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3091:                     $what.=':'.$formitem.'='.$env{$key};
                   3092:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3093:                     $what.=':'.$formitem.'='.$env{$key};
                   3094:                 }
1.158     www      3095:             }
1.191     harris41 3096:         }
1.583     matthew  3097:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3098:         # FIXME: We should not be depending on a form parameter that someone
                   3099:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3100:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3101:             $what.= ':POST';
                   3102:             # FIXME: Probably ought to escape things....
                   3103:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3104:                                  'crsdiscuss') {
1.620     albertel 3105:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3106:             }
                   3107:         }
1.158     www      3108:     }
                   3109:     &courselog($what);
1.149     www      3110: }
                   3111: 
1.185     www      3112: sub countacc {
                   3113:     my $url=&declutter(shift);
1.458     matthew  3114:     return if (! defined($url) || $url eq '');
1.620     albertel 3115:     unless ($env{'request.course.id'}) { return ''; }
                   3116:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3117:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3118:     $accesshash{$key}++;
1.185     www      3119: }
1.349     www      3120: 
1.361     www      3121: sub linklog {
                   3122:     my ($from,$to)=@_;
                   3123:     $from=&declutter($from);
                   3124:     $to=&declutter($to);
                   3125:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3126:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3127: }
                   3128:   
1.349     www      3129: sub userrolelog {
                   3130:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3131:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3132:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3133:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3134:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3135:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3136:        $userrolehash
                   3137:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3138:                     =$tend.':'.$tstart;
1.662     raeburn  3139:     }
1.898     albertel 3140:     if (($env{'request.role'} =~ /dc\./) &&
                   3141: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3142: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3143: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3144:          ($trole=~/^co/))) {
1.898     albertel 3145:        $userrolehash
                   3146:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3147:                     =$tend.':'.$tstart;
                   3148:     }
1.662     raeburn  3149:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3150:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3151:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3152:         ($trole=~/^sc/)) {
                   3153:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3154:        $domainrolehash
                   3155:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3156:                     = $tend.':'.$tstart;
                   3157:     }
1.351     www      3158: }
                   3159: 
1.957     raeburn  3160: sub courserolelog {
                   3161:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3162:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3163:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3164:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3165:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3166:         ($trole eq 'co')) {
1.957     raeburn  3167:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3168:             my $cdom = $1;
                   3169:             my $cnum = $2;
                   3170:             my $sec = $3;
                   3171:             my $namespace = 'rolelog';
                   3172:             my %storehash = (
                   3173:                                role    => $trole,
                   3174:                                start   => $tstart,
                   3175:                                end     => $tend,
                   3176:                                selfenroll => $selfenroll,
                   3177:                                context    => $context,
                   3178:                             );
                   3179:             if ($trole eq 'gr') {
                   3180:                 $namespace = 'groupslog';
                   3181:                 $storehash{'group'} = $sec;
                   3182:             } else {
                   3183:                 $storehash{'section'} = $sec;
                   3184:             }
                   3185:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3186:             if (($trole ne 'st') || ($sec ne '')) {
                   3187:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3188:             }
1.957     raeburn  3189:         }
                   3190:     }
                   3191:     return;
                   3192: }
                   3193: 
1.351     www      3194: sub get_course_adv_roles {
1.948     raeburn  3195:     my ($cid,$codes) = @_;
1.620     albertel 3196:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3197:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3198:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3199:     my %nothide=();
1.800     albertel 3200:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3201:         if ($user !~ /:/) {
                   3202: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3203:         } else {
                   3204:             $nothide{$user}=1;
                   3205:         }
1.470     www      3206:     }
1.351     www      3207:     my %returnhash=();
                   3208:     my %dumphash=
                   3209:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3210:     my $now=time;
1.997     raeburn  3211:     my %privileged;
1.1000    raeburn  3212:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3213: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3214:         if (($tstart) && ($tstart<0)) { next; }
                   3215:         if (($tend) && ($tend<$now)) { next; }
                   3216:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3217:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3218: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3219:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3220:             my %dompersonnel =
1.998     raeburn  3221:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3222:             $privileged{$domain} = {};
                   3223:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3224:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3225:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3226:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3227:                         $privileged{$udom}{$uname} = 1;
                   3228:                     }
                   3229:                 }
                   3230:             }
                   3231:         }
                   3232:         if ((exists($privileged{$domain}{$username})) && 
                   3233:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3234: 	if ($role eq 'cr') { next; }
1.948     raeburn  3235:         if ($codes) {
                   3236:             if ($section) { $role .= ':'.$section; }
                   3237:             if ($returnhash{$role}) {
                   3238:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3239:             } else {
                   3240:                 $returnhash{$role}=$username.':'.$domain;
                   3241:             }
1.351     www      3242:         } else {
1.988     raeburn  3243:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3244:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3245:             if ($returnhash{$key}) {
                   3246: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3247:             } else {
                   3248:                 $returnhash{$key}=$username.':'.$domain;
                   3249:             }
1.351     www      3250:         }
1.948     raeburn  3251:     }
1.400     www      3252:     return %returnhash;
                   3253: }
                   3254: 
                   3255: sub get_my_roles {
1.937     raeburn  3256:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3257:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3258:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3259:     my (%dumphash,%nothide);
1.1086    raeburn  3260:     if ($context eq 'userroles') {
                   3261:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3262:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3263:     } else {
                   3264:         %dumphash=
1.400     www      3265:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3266:         if ($hidepriv) {
                   3267:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3268:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3269:                 if ($user !~ /:/) {
                   3270:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3271:                 } else {
                   3272:                     $nothide{$user} = 1;
                   3273:                 }
                   3274:             }
                   3275:         }
1.858     raeburn  3276:     }
1.400     www      3277:     my %returnhash=();
                   3278:     my $now=time;
1.999     raeburn  3279:     my %privileged;
1.800     albertel 3280:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3281:         my ($role,$tend,$tstart);
                   3282:         if ($context eq 'userroles') {
                   3283: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3284:         } else {
                   3285:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3286:         }
1.400     www      3287:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3288:         my $status = 'active';
1.939     raeburn  3289:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3290:             $status = 'previous';
                   3291:         } 
                   3292:         if (($tstart) && ($now<$tstart)) {
                   3293:             $status = 'future';
                   3294:         }
                   3295:         if (ref($types) eq 'ARRAY') {
                   3296:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3297:                 next;
                   3298:             } 
                   3299:         } else {
                   3300:             if ($status ne 'active') {
                   3301:                 next;
                   3302:             }
                   3303:         }
1.867     raeburn  3304:         my ($rolecode,$username,$domain,$section,$area);
                   3305:         if ($context eq 'userroles') {
                   3306:             ($area,$rolecode) = split(/_/,$entry);
                   3307:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3308:         } else {
                   3309:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3310:         }
1.832     raeburn  3311:         if (ref($roledoms) eq 'ARRAY') {
                   3312:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3313:                 next;
                   3314:             }
                   3315:         }
                   3316:         if (ref($roles) eq 'ARRAY') {
                   3317:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3318:                 if ($role =~ /^cr\//) {
                   3319:                     if (!grep(/^cr$/,@{$roles})) {
                   3320:                         next;
                   3321:                     }
1.1104    raeburn  3322:                 } elsif ($role =~ /^gr\//) {
                   3323:                     if (!grep(/^gr$/,@{$roles})) {
                   3324:                         next;
                   3325:                     }
1.922     raeburn  3326:                 } else {
                   3327:                     next;
                   3328:                 }
1.832     raeburn  3329:             }
1.867     raeburn  3330:         }
1.937     raeburn  3331:         if ($hidepriv) {
1.999     raeburn  3332:             if ($context eq 'userroles') {
                   3333:                 if ((&privileged($username,$domain)) &&
                   3334:                     (!$nothide{$username.':'.$domain})) {
                   3335:                     next;
                   3336:                 }
                   3337:             } else {
                   3338:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3339:                     my %dompersonnel =
                   3340:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3341:                     $privileged{$domain} = {};
                   3342:                     if (keys(%dompersonnel)) {
                   3343:                         foreach my $server (keys(%dompersonnel)) {
                   3344:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3345:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3346:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3347:                                     $privileged{$udom}{$uname} = $trole;
                   3348:                                 }
                   3349:                             }
                   3350:                         }
                   3351:                     }
                   3352:                 }
                   3353:                 if (exists($privileged{$domain}{$username})) {
                   3354:                     if (!$nothide{$username.':'.$domain}) {
                   3355:                         next;
                   3356:                     }
                   3357:                 }
1.937     raeburn  3358:             }
                   3359:         }
1.933     raeburn  3360:         if ($withsec) {
                   3361:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3362:                 $tstart.':'.$tend;
                   3363:         } else {
                   3364:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3365:         }
1.832     raeburn  3366:     }
1.373     www      3367:     return %returnhash;
1.399     www      3368: }
                   3369: 
                   3370: # ----------------------------------------------------- Frontpage Announcements
                   3371: #
                   3372: #
                   3373: 
                   3374: sub postannounce {
                   3375:     my ($server,$text)=@_;
1.844     albertel 3376:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3377:     unless ($text=~/\w/) { $text=''; }
                   3378:     return &reply('setannounce:'.&escape($text),$server);
                   3379: }
                   3380: 
                   3381: sub getannounce {
1.448     albertel 3382: 
                   3383:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3384: 	my $announcement='';
1.800     albertel 3385: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3386: 	close($fh);
1.399     www      3387: 	if ($announcement=~/\w/) { 
                   3388: 	    return 
                   3389:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3390:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3391: 	} else {
                   3392: 	    return '';
                   3393: 	}
                   3394:     } else {
                   3395: 	return '';
                   3396:     }
1.351     www      3397: }
1.353     www      3398: 
                   3399: # ---------------------------------------------------------- Course ID routines
                   3400: # Deal with domain's nohist_courseid.db files
                   3401: #
                   3402: 
                   3403: sub courseidput {
1.921     raeburn  3404:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3405:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3406:     my $outcome;
                   3407:     if ($caller eq 'timeonly') {
                   3408:         my $cids = '';
                   3409:         foreach my $item (keys(%$storehash)) {
                   3410:             $cids.=&escape($item).'&';
                   3411:         }
                   3412:         $cids=~s/\&$//;
                   3413:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3414:                           $coursehome);       
                   3415:     } else {
                   3416:         my $items = '';
                   3417:         foreach my $item (keys(%$storehash)) {
                   3418:             $items.= &escape($item).'='.
                   3419:                      &freeze_escape($$storehash{$item}).'&';
                   3420:         }
                   3421:         $items=~s/\&$//;
                   3422:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3423:                           $coursehome);
1.918     raeburn  3424:     }
                   3425:     if ($outcome eq 'unknown_cmd') {
                   3426:         my $what;
                   3427:         foreach my $cid (keys(%$storehash)) {
                   3428:             $what .= &escape($cid).'=';
1.921     raeburn  3429:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3430:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3431:             }
                   3432:             $what =~ s/\:$/&/;
                   3433:         }
                   3434:         $what =~ s/\&$//;  
                   3435:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3436:     } else {
                   3437:         return $outcome;
                   3438:     }
1.353     www      3439: }
                   3440: 
                   3441: sub courseiddump {
1.921     raeburn  3442:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3443:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3444:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3445:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3446:     my $as_hash = 1;
                   3447:     my %returnhash;
                   3448:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3449:     my %libserv = &all_library();
                   3450:     foreach my $tryserver (keys(%libserv)) {
                   3451:         if ( (  $hostidflag == 1 
                   3452: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3453: 	     || (!defined($hostidflag)) ) {
                   3454: 
1.918     raeburn  3455: 	    if (($domfilter eq '') ||
                   3456: 		(&host_domain($tryserver) eq $domfilter)) {
                   3457:                 my $rep = 
                   3458:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3459:                          $sincefilter.':'.&escape($descfilter).':'.
                   3460:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3461:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3462:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3463:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3464:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3465:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3466:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3467:                          &escape($creationcontext).':'.$domcloner,
                   3468:                          $tryserver);
1.918     raeburn  3469:                 my @pairs=split(/\&/,$rep);
                   3470:                 foreach my $item (@pairs) {
                   3471:                     my ($key,$value)=split(/\=/,$item,2);
                   3472:                     $key = &unescape($key);
                   3473:                     next if ($key =~ /^error: 2 /);
                   3474:                     my $result = &thaw_unescape($value);
                   3475:                     if (ref($result) eq 'HASH') {
                   3476:                         $returnhash{$key}=$result;
                   3477:                     } else {
1.921     raeburn  3478:                         my @responses = split(/:/,$value);
                   3479:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3480:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3481:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3482:                         }
1.1008    raeburn  3483:                     }
1.353     www      3484:                 }
                   3485:             }
                   3486:         }
                   3487:     }
                   3488:     return %returnhash;
                   3489: }
                   3490: 
1.1055    raeburn  3491: sub courselastaccess {
                   3492:     my ($cdom,$cnum,$hostidref) = @_;
                   3493:     my %returnhash;
                   3494:     if ($cdom && $cnum) {
                   3495:         my $chome = &homeserver($cnum,$cdom);
                   3496:         if ($chome ne 'no_host') {
                   3497:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3498:             &extract_lastaccess(\%returnhash,$rep);
                   3499:         }
                   3500:     } else {
                   3501:         if (!$cdom) { $cdom=''; }
                   3502:         my %libserv = &all_library();
                   3503:         foreach my $tryserver (keys(%libserv)) {
                   3504:             if (ref($hostidref) eq 'ARRAY') {
                   3505:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3506:             } 
                   3507:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3508:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3509:                 &extract_lastaccess(\%returnhash,$rep);
                   3510:             }
                   3511:         }
                   3512:     }
                   3513:     return %returnhash;
                   3514: }
                   3515: 
                   3516: sub extract_lastaccess {
                   3517:     my ($returnhash,$rep) = @_;
                   3518:     if (ref($returnhash) eq 'HASH') {
                   3519:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3520:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3521:                  $rep eq '') {
                   3522:             my @pairs=split(/\&/,$rep);
                   3523:             foreach my $item (@pairs) {
                   3524:                 my ($key,$value)=split(/\=/,$item,2);
                   3525:                 $key = &unescape($key);
                   3526:                 next if ($key =~ /^error: 2 /);
                   3527:                 $returnhash->{$key} = &thaw_unescape($value);
                   3528:             }
                   3529:         }
                   3530:     }
                   3531:     return;
                   3532: }
                   3533: 
1.658     raeburn  3534: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3535: 
                   3536: sub dcmailput {
1.685     raeburn  3537:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3538:     my $status = &Apache::lonnet::critical(
1.740     www      3539:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3540:        &escape($message),$server);
1.662     raeburn  3541:     return $status;
                   3542: }
                   3543: 
1.658     raeburn  3544: sub dcmaildump {
                   3545:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3546:     my %returnhash=();
1.846     albertel 3547: 
                   3548:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3549:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3550:                                                          &escape($enddate).':';
                   3551: 	my @esc_senders=map { &escape($_)} @$senders;
                   3552: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3553: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3554:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3555:             if (($key) && ($value)) {
                   3556:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3557:             }
                   3558:         }
                   3559:     }
                   3560:     return %returnhash;
                   3561: }
1.662     raeburn  3562: # ---------------------------------------------------------- Domain roles
                   3563: 
                   3564: sub get_domain_roles {
                   3565:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3566:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3567:         $startdate = '.';
                   3568:     }
1.1018    raeburn  3569:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3570:         $enddate = '.';
                   3571:     }
1.922     raeburn  3572:     my $rolelist;
                   3573:     if (ref($roles) eq 'ARRAY') {
                   3574:         $rolelist = join(':',@{$roles});
                   3575:     }
1.662     raeburn  3576:     my %personnel = ();
1.841     albertel 3577: 
                   3578:     my %servers = &get_servers($dom,'library');
                   3579:     foreach my $tryserver (keys(%servers)) {
                   3580: 	%{$personnel{$tryserver}}=();
                   3581: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3582: 					    &escape($startdate).':'.
                   3583: 					    &escape($enddate).':'.
                   3584: 					    &escape($rolelist), $tryserver))) {
                   3585: 	    my ($key,$value) = split(/\=/,$line,2);
                   3586: 	    if (($key) && ($value)) {
                   3587: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3588: 	    }
                   3589: 	}
1.662     raeburn  3590:     }
                   3591:     return %personnel;
                   3592: }
1.658     raeburn  3593: 
1.1057    www      3594: # ----------------------------------------------------------- Interval timing 
1.149     www      3595: 
1.504     albertel 3596: sub get_first_access {
                   3597:     my ($type,$argsymb)=@_;
1.790     albertel 3598:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3599:     if ($argsymb) { $symb=$argsymb; }
                   3600:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3601:     if ($type eq 'course') {
                   3602: 	$res='course';
                   3603:     } elsif ($type eq 'map') {
1.588     albertel 3604: 	$res=&symbread($map);
                   3605:     } else {
                   3606: 	$res=$symb;
                   3607:     }
                   3608:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3609:     return $times{"$courseid\0$res"};
1.504     albertel 3610: }
                   3611: 
                   3612: sub set_first_access {
                   3613:     my ($type)=@_;
1.790     albertel 3614:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3615:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3616:     if ($type eq 'course') {
                   3617: 	$res='course';
                   3618:     } elsif ($type eq 'map') {
1.588     albertel 3619: 	$res=&symbread($map);
                   3620:     } else {
                   3621: 	$res=$symb;
                   3622:     }
                   3623:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3624:     if (!$firstaccess) {
1.588     albertel 3625: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3626:     }
                   3627:     return 'already_set';
1.504     albertel 3628: }
                   3629: 
1.110     www      3630: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3631: 
                   3632: sub expirespread {
                   3633:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3634:     my $cid=$env{'request.course.id'}; 
1.110     www      3635:     if ($cid) {
                   3636:        my $now=time;
                   3637:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3638:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3639:                             $env{'course.'.$cid.'.num'}.
1.110     www      3640: 	        	    ':nohist_expirationdates:'.
                   3641:                             &escape($key).'='.$now,
1.620     albertel 3642:                             $env{'course.'.$cid.'.home'})
1.110     www      3643:     }
                   3644:     return 'ok';
1.14      www      3645: }
                   3646: 
1.109     www      3647: # ----------------------------------------------------- Devalidate Spreadsheets
                   3648: 
                   3649: sub devalidate {
1.325     www      3650:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3651:     my $cid=$env{'request.course.id'}; 
1.109     www      3652:     if ($cid) {
1.391     matthew  3653:         # delete the stored spreadsheets for
                   3654:         # - the student level sheet of this user in course's homespace
                   3655:         # - the assessment level sheet for this resource 
                   3656:         #   for this user in user's homespace
1.553     albertel 3657: 	# - current conditional state info
1.325     www      3658: 	my $key=$uname.':'.$udom.':';
1.109     www      3659:         my $status=
1.299     matthew  3660: 	    &del('nohist_calculatedsheets',
1.391     matthew  3661: 		 [$key.'studentcalc:'],
1.620     albertel 3662: 		 $env{'course.'.$cid.'.domain'},
                   3663: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3664: 		.' '.
                   3665: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3666: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3667:         unless ($status eq 'ok ok') {
                   3668:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3669:                     $uname.' at '.$udom.' for '.
1.109     www      3670: 		    $symb.': '.$status);
1.133     albertel 3671:         }
1.553     albertel 3672: 	&delenv('user.state.'.$cid);
1.109     www      3673:     }
                   3674: }
                   3675: 
1.265     albertel 3676: sub get_scalar {
                   3677:     my ($string,$end) = @_;
                   3678:     my $value;
                   3679:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3680: 	$value = $1;
                   3681:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3682: 	$value = $1;
                   3683:     }
                   3684:     return &unescape($value);
                   3685: }
                   3686: 
                   3687: sub array2str {
                   3688:   my (@array) = @_;
                   3689:   my $result=&arrayref2str(\@array);
                   3690:   $result=~s/^__ARRAY_REF__//;
                   3691:   $result=~s/__END_ARRAY_REF__$//;
                   3692:   return $result;
                   3693: }
                   3694: 
1.204     albertel 3695: sub arrayref2str {
                   3696:   my ($arrayref) = @_;
1.265     albertel 3697:   my $result='__ARRAY_REF__';
1.204     albertel 3698:   foreach my $elem (@$arrayref) {
1.265     albertel 3699:     if(ref($elem) eq 'ARRAY') {
                   3700:       $result.=&arrayref2str($elem).'&';
                   3701:     } elsif(ref($elem) eq 'HASH') {
                   3702:       $result.=&hashref2str($elem).'&';
                   3703:     } elsif(ref($elem)) {
                   3704:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3705:     } else {
                   3706:       $result.=&escape($elem).'&';
                   3707:     }
                   3708:   }
                   3709:   $result=~s/\&$//;
1.265     albertel 3710:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3711:   return $result;
                   3712: }
                   3713: 
1.168     albertel 3714: sub hash2str {
1.204     albertel 3715:   my (%hash) = @_;
                   3716:   my $result=&hashref2str(\%hash);
1.265     albertel 3717:   $result=~s/^__HASH_REF__//;
                   3718:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3719:   return $result;
                   3720: }
                   3721: 
                   3722: sub hashref2str {
                   3723:   my ($hashref)=@_;
1.265     albertel 3724:   my $result='__HASH_REF__';
1.800     albertel 3725:   foreach my $key (sort(keys(%$hashref))) {
                   3726:     if (ref($key) eq 'ARRAY') {
                   3727:       $result.=&arrayref2str($key).'=';
                   3728:     } elsif (ref($key) eq 'HASH') {
                   3729:       $result.=&hashref2str($key).'=';
                   3730:     } elsif (ref($key)) {
1.265     albertel 3731:       $result.='=';
1.800     albertel 3732:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3733:     } else {
1.800     albertel 3734: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3735:     }
                   3736: 
1.800     albertel 3737:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3738:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3739:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3740:       $result.=&hashref2str($hashref->{$key}).'&';
                   3741:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3742:        $result.='&';
1.800     albertel 3743:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3744:     } else {
1.800     albertel 3745:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3746:     }
                   3747:   }
1.168     albertel 3748:   $result=~s/\&$//;
1.265     albertel 3749:   $result .= '__END_HASH_REF__';
1.168     albertel 3750:   return $result;
                   3751: }
                   3752: 
                   3753: sub str2hash {
1.265     albertel 3754:     my ($string)=@_;
                   3755:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3756:     return %$hash;
                   3757: }
                   3758: 
                   3759: sub str2hashref {
1.168     albertel 3760:   my ($string) = @_;
1.265     albertel 3761: 
                   3762:   my %hash;
                   3763: 
                   3764:   if($string !~ /^__HASH_REF__/) {
                   3765:       if (! ($string eq '' || !defined($string))) {
                   3766: 	  $hash{'error'}='Not hash reference';
                   3767:       }
                   3768:       return (\%hash, $string);
                   3769:   }
                   3770: 
                   3771:   $string =~ s/^__HASH_REF__//;
                   3772: 
                   3773:   while($string !~ /^__END_HASH_REF__/) {
                   3774:       #key
                   3775:       my $key='';
                   3776:       if($string =~ /^__HASH_REF__/) {
                   3777:           ($key, $string)=&str2hashref($string);
                   3778:           if(defined($key->{'error'})) {
                   3779:               $hash{'error'}='Bad data';
                   3780:               return (\%hash, $string);
                   3781:           }
                   3782:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3783:           ($key, $string)=&str2arrayref($string);
                   3784:           if($key->[0] eq 'Array reference error') {
                   3785:               $hash{'error'}='Bad data';
                   3786:               return (\%hash, $string);
                   3787:           }
                   3788:       } else {
                   3789:           $string =~ s/^(.*?)=//;
1.267     albertel 3790: 	  $key=&unescape($1);
1.265     albertel 3791:       }
                   3792:       $string =~ s/^=//;
                   3793: 
                   3794:       #value
                   3795:       my $value='';
                   3796:       if($string =~ /^__HASH_REF__/) {
                   3797:           ($value, $string)=&str2hashref($string);
                   3798:           if(defined($value->{'error'})) {
                   3799:               $hash{'error'}='Bad data';
                   3800:               return (\%hash, $string);
                   3801:           }
                   3802:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3803:           ($value, $string)=&str2arrayref($string);
                   3804:           if($value->[0] eq 'Array reference error') {
                   3805:               $hash{'error'}='Bad data';
                   3806:               return (\%hash, $string);
                   3807:           }
                   3808:       } else {
                   3809: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3810:       }
                   3811:       $string =~ s/^&//;
                   3812: 
                   3813:       $hash{$key}=$value;
1.204     albertel 3814:   }
1.265     albertel 3815: 
                   3816:   $string =~ s/^__END_HASH_REF__//;
                   3817: 
                   3818:   return (\%hash, $string);
1.204     albertel 3819: }
                   3820: 
                   3821: sub str2array {
1.265     albertel 3822:     my ($string)=@_;
                   3823:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3824:     return @$array;
                   3825: }
                   3826: 
                   3827: sub str2arrayref {
1.204     albertel 3828:   my ($string) = @_;
1.265     albertel 3829:   my @array;
                   3830: 
                   3831:   if($string !~ /^__ARRAY_REF__/) {
                   3832:       if (! ($string eq '' || !defined($string))) {
                   3833: 	  $array[0]='Array reference error';
                   3834:       }
                   3835:       return (\@array, $string);
                   3836:   }
                   3837: 
                   3838:   $string =~ s/^__ARRAY_REF__//;
                   3839: 
                   3840:   while($string !~ /^__END_ARRAY_REF__/) {
                   3841:       my $value='';
                   3842:       if($string =~ /^__HASH_REF__/) {
                   3843:           ($value, $string)=&str2hashref($string);
                   3844:           if(defined($value->{'error'})) {
                   3845:               $array[0] ='Array reference error';
                   3846:               return (\@array, $string);
                   3847:           }
                   3848:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3849:           ($value, $string)=&str2arrayref($string);
                   3850:           if($value->[0] eq 'Array reference error') {
                   3851:               $array[0] ='Array reference error';
                   3852:               return (\@array, $string);
                   3853:           }
                   3854:       } else {
                   3855: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3856:       }
                   3857:       $string =~ s/^&//;
                   3858: 
                   3859:       push(@array, $value);
1.191     harris41 3860:   }
1.265     albertel 3861: 
                   3862:   $string =~ s/^__END_ARRAY_REF__//;
                   3863: 
                   3864:   return (\@array, $string);
1.168     albertel 3865: }
                   3866: 
1.167     albertel 3867: # -------------------------------------------------------------------Temp Store
                   3868: 
1.168     albertel 3869: sub tmpreset {
                   3870:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3871:   if (!$symb) {
                   3872:     $symb=&symbread();
1.620     albertel 3873:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3874:   }
                   3875:   $symb=escape($symb);
                   3876: 
1.620     albertel 3877:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3878:   $namespace=~s/\//\_/g;
                   3879:   $namespace=~s/\W//g;
                   3880: 
1.620     albertel 3881:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3882:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3883:   if ($domain eq 'public' && $stuname eq 'public') {
                   3884:       $stuname=$ENV{'REMOTE_ADDR'};
                   3885:   }
1.1117    foxr     3886:   my $path=LONCAPA::tempdir();
1.168     albertel 3887:   my %hash;
                   3888:   if (tie(%hash,'GDBM_File',
                   3889: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3890: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3891:     foreach my $key (keys(%hash)) {
1.180     albertel 3892:       if ($key=~ /:$symb/) {
1.168     albertel 3893: 	delete($hash{$key});
                   3894:       }
                   3895:     }
                   3896:   }
                   3897: }
                   3898: 
1.167     albertel 3899: sub tmpstore {
1.168     albertel 3900:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3901: 
                   3902:   if (!$symb) {
                   3903:     $symb=&symbread();
1.620     albertel 3904:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3905:   }
                   3906:   $symb=escape($symb);
                   3907: 
                   3908:   if (!$namespace) {
                   3909:     # I don't think we would ever want to store this for a course.
                   3910:     # it seems this will only be used if we don't have a course.
1.620     albertel 3911:     #$namespace=$env{'request.course.id'};
1.168     albertel 3912:     #if (!$namespace) {
1.620     albertel 3913:       $namespace=$env{'request.state'};
1.168     albertel 3914:     #}
                   3915:   }
                   3916:   $namespace=~s/\//\_/g;
                   3917:   $namespace=~s/\W//g;
1.620     albertel 3918:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3919:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3920:   if ($domain eq 'public' && $stuname eq 'public') {
                   3921:       $stuname=$ENV{'REMOTE_ADDR'};
                   3922:   }
1.168     albertel 3923:   my $now=time;
                   3924:   my %hash;
1.1117    foxr     3925:   my $path=LONCAPA::tempdir();
1.168     albertel 3926:   if (tie(%hash,'GDBM_File',
                   3927: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3928: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3929:     $hash{"version:$symb"}++;
                   3930:     my $version=$hash{"version:$symb"};
                   3931:     my $allkeys=''; 
                   3932:     foreach my $key (keys(%$storehash)) {
                   3933:       $allkeys.=$key.':';
1.591     albertel 3934:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3935:     }
                   3936:     $hash{"$version:$symb:timestamp"}=$now;
                   3937:     $allkeys.='timestamp';
                   3938:     $hash{"$version:keys:$symb"}=$allkeys;
                   3939:     if (untie(%hash)) {
                   3940:       return 'ok';
                   3941:     } else {
                   3942:       return "error:$!";
                   3943:     }
                   3944:   } else {
                   3945:     return "error:$!";
                   3946:   }
                   3947: }
1.167     albertel 3948: 
1.168     albertel 3949: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3950: 
1.168     albertel 3951: sub tmprestore {
                   3952:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3953: 
1.168     albertel 3954:   if (!$symb) {
                   3955:     $symb=&symbread();
1.620     albertel 3956:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3957:   }
                   3958:   $symb=escape($symb);
                   3959: 
1.620     albertel 3960:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3961: 
1.620     albertel 3962:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3963:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3964:   if ($domain eq 'public' && $stuname eq 'public') {
                   3965:       $stuname=$ENV{'REMOTE_ADDR'};
                   3966:   }
1.168     albertel 3967:   my %returnhash;
                   3968:   $namespace=~s/\//\_/g;
                   3969:   $namespace=~s/\W//g;
                   3970:   my %hash;
1.1117    foxr     3971:   my $path=LONCAPA::tempdir();
1.168     albertel 3972:   if (tie(%hash,'GDBM_File',
                   3973: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3974: 	  &GDBM_READER(),0640)) {
1.168     albertel 3975:     my $version=$hash{"version:$symb"};
                   3976:     $returnhash{'version'}=$version;
                   3977:     my $scope;
                   3978:     for ($scope=1;$scope<=$version;$scope++) {
                   3979:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3980:       my @keys=split(/:/,$vkeys);
                   3981:       my $key;
                   3982:       $returnhash{"$scope:keys"}=$vkeys;
                   3983:       foreach $key (@keys) {
1.591     albertel 3984: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3985: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3986:       }
                   3987:     }
1.168     albertel 3988:     if (!(untie(%hash))) {
                   3989:       return "error:$!";
                   3990:     }
                   3991:   } else {
                   3992:     return "error:$!";
                   3993:   }
                   3994:   return %returnhash;
1.167     albertel 3995: }
                   3996: 
1.9       www      3997: # ----------------------------------------------------------------------- Store
                   3998: 
                   3999: sub store {
1.124     www      4000:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4001:     my $home='';
                   4002: 
1.168     albertel 4003:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4004: 
1.213     www      4005:     $symb=&symbclean($symb);
1.122     albertel 4006:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4007: 
1.620     albertel 4008:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4009:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4010: 
                   4011:     &devalidate($symb,$stuname,$domain);
1.109     www      4012: 
                   4013:     $symb=escape($symb);
1.187     www      4014:     if (!$namespace) { 
1.620     albertel 4015:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4016:           return ''; 
                   4017:        } 
                   4018:     }
1.620     albertel 4019:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4020: 
                   4021:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4022:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4023: 
1.12      www      4024:     my $namevalue='';
1.800     albertel 4025:     foreach my $key (keys(%$storehash)) {
                   4026:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4027:     }
1.12      www      4028:     $namevalue=~s/\&$//;
1.187     www      4029:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4030:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4031: }
                   4032: 
1.47      www      4033: # -------------------------------------------------------------- Critical Store
                   4034: 
                   4035: sub cstore {
1.124     www      4036:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4037:     my $home='';
                   4038: 
1.168     albertel 4039:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4040: 
1.213     www      4041:     $symb=&symbclean($symb);
1.122     albertel 4042:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4043: 
1.620     albertel 4044:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4045:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4046: 
                   4047:     &devalidate($symb,$stuname,$domain);
1.109     www      4048: 
                   4049:     $symb=escape($symb);
1.187     www      4050:     if (!$namespace) { 
1.620     albertel 4051:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4052:           return ''; 
                   4053:        } 
                   4054:     }
1.620     albertel 4055:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4056: 
                   4057:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4058:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4059: 
1.47      www      4060:     my $namevalue='';
1.800     albertel 4061:     foreach my $key (keys(%$storehash)) {
                   4062:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4063:     }
1.47      www      4064:     $namevalue=~s/\&$//;
1.187     www      4065:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4066:     return critical
                   4067:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4068: }
                   4069: 
1.9       www      4070: # --------------------------------------------------------------------- Restore
                   4071: 
                   4072: sub restore {
1.124     www      4073:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4074:     my $home='';
                   4075: 
1.168     albertel 4076:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4077: 
1.122     albertel 4078:     if (!$symb) {
                   4079:       unless ($symb=escape(&symbread())) { return ''; }
                   4080:     } else {
1.213     www      4081:       $symb=&escape(&symbclean($symb));
1.122     albertel 4082:     }
1.188     www      4083:     if (!$namespace) { 
1.620     albertel 4084:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4085:           return ''; 
                   4086:        } 
                   4087:     }
1.620     albertel 4088:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4089:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4090:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4091:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4092: 
1.12      www      4093:     my %returnhash=();
1.800     albertel 4094:     foreach my $line (split(/\&/,$answer)) {
                   4095: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4096:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4097:     }
1.75      www      4098:     my $version;
                   4099:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4100:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4101:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4102:        }
1.75      www      4103:     }
1.13      www      4104:     return %returnhash;
1.34      www      4105: }
                   4106: 
                   4107: # ---------------------------------------------------------- Course Description
1.1118    foxr     4108: #
                   4109: #  
1.34      www      4110: 
                   4111: sub coursedescription {
1.731     albertel 4112:     my ($courseid,$args)=@_;
1.34      www      4113:     $courseid=~s/^\///;
1.49      www      4114:     $courseid=~s/\_/\//g;
1.34      www      4115:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4116:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4117:     my $normalid=$cdomain.'_'.$cnum;
                   4118:     # need to always cache even if we get errors otherwise we keep 
                   4119:     # trying and trying and trying to get the course description.
                   4120:     my %envhash=();
                   4121:     my %returnhash=();
1.731     albertel 4122:     
                   4123:     my $expiretime=600;
                   4124:     if ($env{'request.course.id'} eq $normalid) {
                   4125: 	$expiretime=120;
                   4126:     }
                   4127: 
                   4128:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4129:     if (!$args->{'freshen_cache'}
                   4130: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4131: 	foreach my $key (keys(%env)) {
                   4132: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4133: 	    my ($setting) = $1;
                   4134: 	    $returnhash{$setting} = $env{$key};
                   4135: 	}
                   4136: 	return %returnhash;
                   4137:     }
                   4138: 
1.1118    foxr     4139:     # get the data again
                   4140: 
1.731     albertel 4141:     if (!$args->{'one_time'}) {
                   4142: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4143:     }
1.811     albertel 4144: 
1.34      www      4145:     if ($chome ne 'no_host') {
1.302     albertel 4146:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4147:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4148: 	   my $username = $env{'user.name'}; # Defult username
                   4149: 	   if(defined $args->{'user'}) {
                   4150: 	       $username = $args->{'user'};
                   4151: 	   }
1.129     albertel 4152:            $returnhash{'home'}= $chome;
                   4153: 	   $returnhash{'domain'} = $cdomain;
                   4154: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4155:            if (!defined($returnhash{'type'})) {
                   4156:                $returnhash{'type'} = 'Course';
                   4157:            }
1.130     albertel 4158:            while (my ($name,$value) = each %returnhash) {
1.53      www      4159:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4160:            }
1.270     www      4161:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4162:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4163: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4164:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4165:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4166:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4167:        }
                   4168:     }
1.731     albertel 4169:     if (!$args->{'one_time'}) {
1.949     raeburn  4170: 	&appenv(\%envhash);
1.731     albertel 4171:     }
1.302     albertel 4172:     return %returnhash;
1.461     www      4173: }
                   4174: 
1.1080    raeburn  4175: sub update_released_required {
                   4176:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4177:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4178:         $cid = $env{'request.course.id'};
                   4179:         $cdom = $env{'course.'.$cid.'.domain'};
                   4180:         $cnum = $env{'course.'.$cid.'.num'};
                   4181:         $chome = $env{'course.'.$cid.'.home'};
                   4182:     }
                   4183:     if ($needsrelease) {
                   4184:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4185:         my $needsupdate;
                   4186:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4187:             $needsupdate = 1;
                   4188:         } else {
                   4189:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4190:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4191:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4192:                 $needsupdate = 1;
                   4193:             }
                   4194:         }
                   4195:         if ($needsupdate) {
                   4196:             my %needshash = (
                   4197:                              'internal.releaserequired' => $needsrelease,
                   4198:                             );
                   4199:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4200:             if ($putresult eq 'ok') {
                   4201:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4202:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4203:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4204:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4205:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4206:                 }
                   4207:             }
                   4208:         }
                   4209:     }
                   4210:     return;
                   4211: }
                   4212: 
1.461     www      4213: # -------------------------------------------------See if a user is privileged
                   4214: 
                   4215: sub privileged {
                   4216:     my ($username,$domain)=@_;
                   4217:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4218: 			&homeserver($username,$domain));
1.1033    raeburn  4219:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4220:         ($rolesdump =~ /^error:/)) {
                   4221:         return 0;
                   4222:     }
1.461     www      4223:     my $now=time;
                   4224:     if ($rolesdump ne '') {
1.800     albertel 4225:         foreach my $entry (split(/&/,$rolesdump)) {
                   4226: 	    if ($entry!~/^rolesdef_/) {
                   4227: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4228: 		$area=~s/\_\w\w$//;
                   4229: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4230: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4231: 		    my $active=1;
                   4232: 		    if ($tend) {
                   4233: 			if ($tend<$now) { $active=0; }
                   4234: 		    }
                   4235: 		    if ($tstart) {
                   4236: 			if ($tstart>$now) { $active=0; }
                   4237: 		    }
                   4238: 		    if ($active) { return 1; }
                   4239: 		}
                   4240: 	    }
                   4241: 	}
                   4242:     }
                   4243:     return 0;
1.9       www      4244: }
1.1       albertel 4245: 
1.103     harris41 4246: # -------------------------------------------------------- Get user privileges
1.11      www      4247: 
                   4248: sub rolesinit {
                   4249:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4250:     my $now=time;
                   4251:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4252:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4253:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4254:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4255:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4256:         return \%userroles;
                   4257:     }
1.11      www      4258:     my %allroles=();
1.678     raeburn  4259:     my %allgroups=();   
1.11      www      4260: 
                   4261:     if ($rolesdump ne '') {
1.800     albertel 4262:         foreach my $entry (split(/&/,$rolesdump)) {
                   4263: 	  if ($entry!~/^rolesdef_/) {
                   4264:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4265: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4266:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4267: 	    if ($role=~/^cr/) { 
1.807     albertel 4268: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4269: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4270: 		    ($tend,$tstart)=split('_',$trest);
                   4271: 		} else {
                   4272: 		    $trole=$role;
                   4273: 		}
1.678     raeburn  4274:             } elsif ($role =~ m|^gr/|) {
                   4275:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4276:                 next if ($tstart eq '-1');
1.678     raeburn  4277:                 ($trole,$group_privs) = split(/\//,$trole);
                   4278:                 $group_privs = &unescape($group_privs);
1.587     albertel 4279: 	    } else {
                   4280: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4281: 	    }
1.743     albertel 4282: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4283: 					 $username);
                   4284: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4285:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4286:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4287:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4288: 		my $spec=$trole.'.'.$area;
                   4289: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4290: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4291:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4292:                 } elsif ($trole eq 'gr') {
                   4293:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4294: 		} else {
1.567     raeburn  4295:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4296: 		}
1.12      www      4297:             }
1.662     raeburn  4298:           }
1.191     harris41 4299:         }
1.743     albertel 4300:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4301:         $userroles{'user.adv'}    = $adv;
                   4302: 	$userroles{'user.author'} = $author;
1.620     albertel 4303:         $env{'user.adv'}=$adv;
1.11      www      4304:     }
1.743     albertel 4305:     return \%userroles;  
1.11      www      4306: }
                   4307: 
1.567     raeburn  4308: sub set_arearole {
                   4309:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4310: # log the associated role with the area
                   4311:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4312:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4313: }
                   4314: 
                   4315: sub custom_roleprivs {
                   4316:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4317:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4318:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4319:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4320:         my ($rdummy,$roledef)=
                   4321:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4322:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4323:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4324:             if (defined($syspriv)) {
1.1043    raeburn  4325:                 if ($trest =~ /^$match_community$/) {
                   4326:                     $syspriv =~ s/bre\&S//; 
                   4327:                 }
1.567     raeburn  4328:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4329:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4330:             }
                   4331:             if ($tdomain ne '') {
                   4332:                 if (defined($dompriv)) {
                   4333:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4334:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4335:                 }
                   4336:                 if (($trest ne '') && (defined($coursepriv))) {
                   4337:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4338:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4339:                 }
                   4340:             }
                   4341:         }
                   4342:     }
                   4343: }
                   4344: 
1.678     raeburn  4345: sub group_roleprivs {
                   4346:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4347:     my $access = 1;
                   4348:     my $now = time;
                   4349:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4350:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4351:     if ($access) {
1.811     albertel 4352:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4353:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4354:     }
                   4355: }
1.567     raeburn  4356: 
                   4357: sub standard_roleprivs {
                   4358:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4359:     if (defined($pr{$trole.':s'})) {
                   4360:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4361:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4362:     }
                   4363:     if ($tdomain ne '') {
                   4364:         if (defined($pr{$trole.':d'})) {
                   4365:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4366:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4367:         }
                   4368:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4369:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4370:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4371:         }
                   4372:     }
                   4373: }
                   4374: 
                   4375: sub set_userprivs {
1.1064    raeburn  4376:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4377:     my $author=0;
                   4378:     my $adv=0;
1.678     raeburn  4379:     my %grouproles = ();
                   4380:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4381:         my @groupkeys; 
1.1000    raeburn  4382:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4383:             push(@groupkeys,$role);
                   4384:         }
                   4385:         if (ref($groups_roles) eq 'HASH') {
                   4386:             foreach my $key (keys(%{$groups_roles})) {
                   4387:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4388:                     push(@groupkeys,$key);
                   4389:                 }
                   4390:             }
                   4391:         }
                   4392:         if (@groupkeys > 0) {
                   4393:             foreach my $role (@groupkeys) {
                   4394:                 my ($trole,$area,$sec,$extendedarea);
                   4395:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4396:                     $trole = $1;
                   4397:                     $area = $2;
                   4398:                     $sec = $3;
                   4399:                     $extendedarea = $area.$sec;
                   4400:                     if (exists($$allgroups{$area})) {
                   4401:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4402:                             my $spec = $trole.'.'.$extendedarea;
                   4403:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4404:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4405:                         }
1.678     raeburn  4406:                     }
                   4407:                 }
                   4408:             }
                   4409:         }
                   4410:     }
1.800     albertel 4411:     foreach my $group (keys(%grouproles)) {
                   4412:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4413:     }
1.800     albertel 4414:     foreach my $role (keys(%{$allroles})) {
                   4415:         my %thesepriv;
1.941     raeburn  4416:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4417:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4418:             if ($item ne '') {
                   4419:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4420:                 if ($restrictions eq '') {
                   4421:                     $thesepriv{$privilege}='F';
                   4422:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4423:                     $thesepriv{$privilege}.=$restrictions;
                   4424:                 }
                   4425:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4426:             }
                   4427:         }
                   4428:         my $thesestr='';
1.1104    raeburn  4429:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4430: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4431: 	}
                   4432:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4433:     }
                   4434:     return ($author,$adv);
                   4435: }
                   4436: 
1.994     raeburn  4437: sub role_status {
1.1104    raeburn  4438:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4439:     my @pwhere = ();
                   4440:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4441:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4442:         unless (!defined($$role) || $$role eq '') {
                   4443:             $$where=join('.',@pwhere);
                   4444:             $$trolecode=$$role.'.'.$$where;
                   4445:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4446:             $$tstatus='is';
1.1104    raeburn  4447:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4448:                 $$tstatus='future';
1.1034    raeburn  4449:                 if ($$tstart<$now) {
                   4450:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4451:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4452:                             my (%allroles,%allgroups,$group_privs,
                   4453:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4454:                             my %userroles = (
                   4455:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4456:                             );
1.1064    raeburn  4457:                             @rolecodes = ('cm'); 
1.1002    raeburn  4458:                             my $spec=$$role.'.'.$$where;
                   4459:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4460:                             if ($$role =~ /^cr\//) {
                   4461:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4462:                                 push(@rolecodes,'cr');
1.1002    raeburn  4463:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4464:                                 push(@rolecodes,$$role);
1.1002    raeburn  4465:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4466:                                                     $env{'user.name'});
1.1064    raeburn  4467:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4468:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4469:                                 $group_privs = &unescape($group_privs);
                   4470:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4471:                                 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  4472:                                 &get_groups_roles($tdomain,$trest,
                   4473:                                                   \%course_roles,\@rolecodes,
                   4474:                                                   \%groups_roles);
1.1002    raeburn  4475:                             } else {
1.1064    raeburn  4476:                                 push(@rolecodes,$$role);
1.1002    raeburn  4477:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4478:                             }
1.1064    raeburn  4479:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4480:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4481:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4482:                         }
                   4483:                     }
1.1034    raeburn  4484:                     $$tstatus = 'is';
1.1002    raeburn  4485:                 }
1.994     raeburn  4486:             }
                   4487:             if ($$tend) {
1.1104    raeburn  4488:                 if ($$tend<$update) {
1.994     raeburn  4489:                     $$tstatus='expired';
                   4490:                 } elsif ($$tend<$now) {
                   4491:                     $$tstatus='will_not';
                   4492:                 }
                   4493:             }
                   4494:         }
                   4495:     }
                   4496: }
                   4497: 
1.1104    raeburn  4498: sub get_groups_roles {
                   4499:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4500:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4501:                   (ref($rolecodes) eq 'ARRAY') && 
                   4502:                   (ref($groups_roles) eq 'HASH')); 
                   4503:     if (keys(%{$cdom_courseroles}) > 0) {
                   4504:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4505:         if ($cdom ne '' && $cnum ne '') {
                   4506:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4507:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4508:                     my $crsrole = $1;
                   4509:                     my $crssec = $2;
                   4510:                     if ($crsrole =~ /^cr/) {
                   4511:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4512:                             push(@{$rolecodes},'cr');
                   4513:                         }
                   4514:                     } else {
                   4515:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4516:                             push(@{$rolecodes},$crsrole);
                   4517:                         }
                   4518:                     }
                   4519:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4520:                     if ($crssec ne '') {
                   4521:                         $rolekey .= "/$crssec";
                   4522:                     }
                   4523:                     $rolekey .= './';
                   4524:                     $groups_roles->{$rolekey} = $rolecodes;
                   4525:                 }
                   4526:             }
                   4527:         }
                   4528:     }
                   4529:     return;
                   4530: }
                   4531: 
                   4532: sub delete_env_groupprivs {
                   4533:     my ($where,$courseroles,$possroles) = @_;
                   4534:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4535:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4536:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4537:         %{$courseroles->{$udom}} =
                   4538:             &get_my_roles('','','userroles',['active'],
                   4539:                           $possroles,[$udom],1);
                   4540:     }
                   4541:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4542:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4543:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4544:             my $area = '/'.$cdom.'/'.$cnum;
                   4545:             my $privkey = "user.priv.$crsrole.$area";
                   4546:             if ($crssec ne '') {
                   4547:                 $privkey .= '/'.$crssec;
                   4548:             }
                   4549:             $privkey .= ".$area/$group";
                   4550:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4551:         }
                   4552:     }
                   4553:     return;
                   4554: }
                   4555: 
1.994     raeburn  4556: sub check_adhoc_privs {
1.1104    raeburn  4557:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4558:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4559:     if ($env{$cckey}) {
                   4560:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4561:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4562:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4563:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4564:         }
                   4565:     } else {
1.1088    raeburn  4566:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4567:     }
                   4568: }
                   4569: 
                   4570: sub set_adhoc_privileges {
                   4571: # role can be cc or ca
1.1088    raeburn  4572:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4573:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4574:     my $spec = $role.'.'.$area;
                   4575:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4576:                                   $env{'user.name'});
                   4577:     my %ccrole = ();
                   4578:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4579:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4580:     &appenv(\%userroles,[$role,'cm']);
                   4581:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4582:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4583:         &appenv( {'request.role'        => $spec,
                   4584:                   'request.role.domain' => $dcdom,
                   4585:                   'request.course.sec'  => ''
                   4586:                  }
                   4587:                );
                   4588:         my $tadv=0;
                   4589:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4590:         &appenv({'request.role.adv'    => $tadv});
                   4591:     }
1.994     raeburn  4592: }
                   4593: 
1.12      www      4594: # --------------------------------------------------------------- get interface
                   4595: 
                   4596: sub get {
1.131     albertel 4597:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4598:    my $items='';
1.800     albertel 4599:    foreach my $item (@$storearr) {
                   4600:        $items.=&escape($item).'&';
1.191     harris41 4601:    }
1.12      www      4602:    $items=~s/\&$//;
1.620     albertel 4603:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4604:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4605:    my $uhome=&homeserver($uname,$udomain);
                   4606: 
1.133     albertel 4607:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4608:    my @pairs=split(/\&/,$rep);
1.273     albertel 4609:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4610:      return @pairs;
                   4611:    }
1.15      www      4612:    my %returnhash=();
1.42      www      4613:    my $i=0;
1.800     albertel 4614:    foreach my $item (@$storearr) {
                   4615:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4616:       $i++;
1.191     harris41 4617:    }
1.15      www      4618:    return %returnhash;
1.27      www      4619: }
                   4620: 
                   4621: # --------------------------------------------------------------- del interface
                   4622: 
                   4623: sub del {
1.133     albertel 4624:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4625:    my $items='';
1.800     albertel 4626:    foreach my $item (@$storearr) {
                   4627:        $items.=&escape($item).'&';
1.191     harris41 4628:    }
1.984     neumanie 4629: 
1.27      www      4630:    $items=~s/\&$//;
1.620     albertel 4631:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4632:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4633:    my $uhome=&homeserver($uname,$udomain);
                   4634:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4635: }
                   4636: 
                   4637: # -------------------------------------------------------------- dump interface
                   4638: 
                   4639: sub dump {
1.1086    raeburn  4640:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4641:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4642:     if (!$uname) { $uname=$env{'user.name'}; }
                   4643:     my $uhome=&homeserver($uname,$udomain);
                   4644:     if ($regexp) {
                   4645: 	$regexp=&escape($regexp);
                   4646:     } else {
                   4647: 	$regexp='.';
                   4648:     }
1.1086    raeburn  4649:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4650:     my @pairs=split(/\&/,$rep);
                   4651:     my %returnhash=();
1.1098    foxr     4652:     if (!($rep =~ /^error/ )) {
                   4653: 	foreach my $item (@pairs) {
                   4654: 	    my ($key,$value)=split(/=/,$item,2);
                   4655: 	    $key = &unescape($key);
                   4656: 	    next if ($key =~ /^error: 2 /);
                   4657: 	    $returnhash{$key}=&thaw_unescape($value);
                   4658: 	}
1.755     albertel 4659:     }
                   4660:     return %returnhash;
1.407     www      4661: }
                   4662: 
1.1098    foxr     4663: 
1.717     albertel 4664: # --------------------------------------------------------- dumpstore interface
                   4665: 
                   4666: sub dumpstore {
                   4667:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4668:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4669:    if (!$uname) { $uname=$env{'user.name'}; }
                   4670:    my $uhome=&homeserver($uname,$udomain);
                   4671:    if ($regexp) {
                   4672:        $regexp=&escape($regexp);
                   4673:    } else {
                   4674:        $regexp='.';
                   4675:    }
                   4676:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4677:    my @pairs=split(/\&/,$rep);
                   4678:    my %returnhash=();
                   4679:    foreach my $item (@pairs) {
                   4680:        my ($key,$value)=split(/=/,$item,2);
                   4681:        next if ($key =~ /^error: 2 /);
                   4682:        $returnhash{$key}=&thaw_unescape($value);
                   4683:    }
                   4684:    return %returnhash;
1.717     albertel 4685: }
                   4686: 
1.407     www      4687: # -------------------------------------------------------------- keys interface
                   4688: 
                   4689: sub getkeys {
                   4690:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4691:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4692:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4693:    my $uhome=&homeserver($uname,$udomain);
                   4694:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4695:    my @keyarray=();
1.800     albertel 4696:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4697:       next if ($key =~ /^error: 2 /);
1.800     albertel 4698:       push(@keyarray,&unescape($key));
1.407     www      4699:    }
                   4700:    return @keyarray;
1.318     matthew  4701: }
                   4702: 
1.319     matthew  4703: # --------------------------------------------------------------- currentdump
                   4704: sub currentdump {
1.328     matthew  4705:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4706:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4707:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4708:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4709:    my $uhome = &homeserver($sname,$sdom);
                   4710:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4711:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4712:    #
1.318     matthew  4713:    my %returnhash=();
1.319     matthew  4714:    #
                   4715:    if ($rep eq "unknown_cmd") { 
                   4716:        # an old lond will not know currentdump
                   4717:        # Do a dump and make it look like a currentdump
1.822     albertel 4718:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4719:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4720:        my %hash = @tmp;
                   4721:        @tmp=();
1.424     matthew  4722:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4723:    } else {
                   4724:        my @pairs=split(/\&/,$rep);
1.800     albertel 4725:        foreach my $pair (@pairs) {
                   4726:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4727:            my ($symb,$param) = split(/:/,$key);
                   4728:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4729:                                                         &thaw_unescape($value);
1.319     matthew  4730:        }
1.191     harris41 4731:    }
1.12      www      4732:    return %returnhash;
1.424     matthew  4733: }
                   4734: 
                   4735: sub convert_dump_to_currentdump{
                   4736:     my %hash = %{shift()};
                   4737:     my %returnhash;
                   4738:     # Code ripped from lond, essentially.  The only difference
                   4739:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4740:     # we might run in to problems with parameter names =~ /^v\./
                   4741:     while (my ($key,$value) = each(%hash)) {
                   4742:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4743: 	$symb  = &unescape($symb);
                   4744: 	$param = &unescape($param);
1.424     matthew  4745:         next if ($v eq 'version' || $symb eq 'keys');
                   4746:         next if (exists($returnhash{$symb}) &&
                   4747:                  exists($returnhash{$symb}->{$param}) &&
                   4748:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4749:         $returnhash{$symb}->{$param}=$value;
                   4750:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4751:     }
                   4752:     #
                   4753:     # Remove all of the keys in the hashes which keep track of
                   4754:     # the version of the parameter.
                   4755:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4756:         # use a foreach because we are going to delete from the hash.
                   4757:         foreach my $key (keys(%$param_hash)) {
                   4758:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4759:         }
                   4760:     }
                   4761:     return \%returnhash;
1.12      www      4762: }
                   4763: 
1.627     albertel 4764: # ------------------------------------------------------ critical inc interface
                   4765: 
                   4766: sub cinc {
                   4767:     return &inc(@_,'critical');
                   4768: }
                   4769: 
1.449     matthew  4770: # --------------------------------------------------------------- inc interface
                   4771: 
                   4772: sub inc {
1.627     albertel 4773:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4774:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4775:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4776:     my $uhome=&homeserver($uname,$udomain);
                   4777:     my $items='';
                   4778:     if (! ref($store)) {
                   4779:         # got a single value, so use that instead
                   4780:         $items = &escape($store).'=&';
                   4781:     } elsif (ref($store) eq 'SCALAR') {
                   4782:         $items = &escape($$store).'=&';        
                   4783:     } elsif (ref($store) eq 'ARRAY') {
                   4784:         $items = join('=&',map {&escape($_);} @{$store});
                   4785:     } elsif (ref($store) eq 'HASH') {
                   4786:         while (my($key,$value) = each(%{$store})) {
                   4787:             $items.= &escape($key).'='.&escape($value).'&';
                   4788:         }
                   4789:     }
                   4790:     $items=~s/\&$//;
1.627     albertel 4791:     if ($critical) {
                   4792: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4793:     } else {
                   4794: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4795:     }
1.449     matthew  4796: }
                   4797: 
1.12      www      4798: # --------------------------------------------------------------- put interface
                   4799: 
                   4800: sub put {
1.134     albertel 4801:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4803:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4804:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4805:    my $items='';
1.800     albertel 4806:    foreach my $item (keys(%$storehash)) {
                   4807:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4808:    }
1.12      www      4809:    $items=~s/\&$//;
1.134     albertel 4810:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4811: }
                   4812: 
1.631     albertel 4813: # ------------------------------------------------------------ newput interface
                   4814: 
                   4815: sub newput {
                   4816:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4817:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4818:    if (!$uname) { $uname=$env{'user.name'}; }
                   4819:    my $uhome=&homeserver($uname,$udomain);
                   4820:    my $items='';
                   4821:    foreach my $key (keys(%$storehash)) {
                   4822:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4823:    }
                   4824:    $items=~s/\&$//;
                   4825:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4826: }
                   4827: 
                   4828: # ---------------------------------------------------------  putstore interface
                   4829: 
1.524     raeburn  4830: sub putstore {
1.715     albertel 4831:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4832:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4833:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4834:    my $uhome=&homeserver($uname,$udomain);
                   4835:    my $items='';
1.715     albertel 4836:    foreach my $key (keys(%$storehash)) {
                   4837:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4838:    }
1.715     albertel 4839:    $items=~s/\&$//;
1.716     albertel 4840:    my $esc_symb=&escape($symb);
                   4841:    my $esc_v=&escape($version);
1.715     albertel 4842:    my $reply =
1.716     albertel 4843:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4844: 	      $uhome);
                   4845:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4846:        # gfall back to way things use to be done
1.715     albertel 4847:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4848: 			    $uname);
1.524     raeburn  4849:    }
1.715     albertel 4850:    return $reply;
                   4851: }
                   4852: 
                   4853: sub old_putstore {
1.716     albertel 4854:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4855:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4856:     if (!$uname) { $uname=$env{'user.name'}; }
                   4857:     my $uhome=&homeserver($uname,$udomain);
                   4858:     my %newstorehash;
1.800     albertel 4859:     foreach my $item (keys(%$storehash)) {
                   4860: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4861: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4862:     }
                   4863:     my $items='';
                   4864:     my %allitems = ();
1.800     albertel 4865:     foreach my $item (keys(%newstorehash)) {
                   4866: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4867: 	    my $key = $1.':keys:'.$2;
                   4868: 	    $allitems{$key} .= $3.':';
                   4869: 	}
1.800     albertel 4870: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4871:     }
1.800     albertel 4872:     foreach my $item (keys(%allitems)) {
                   4873: 	$allitems{$item} =~ s/\:$//;
                   4874: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4875:     }
                   4876:     $items=~s/\&$//;
                   4877:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4878: }
                   4879: 
1.47      www      4880: # ------------------------------------------------------ critical put interface
                   4881: 
                   4882: sub cput {
1.134     albertel 4883:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4884:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4885:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4886:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4887:    my $items='';
1.800     albertel 4888:    foreach my $item (keys(%$storehash)) {
                   4889:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4890:    }
1.47      www      4891:    $items=~s/\&$//;
1.134     albertel 4892:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4893: }
                   4894: 
                   4895: # -------------------------------------------------------------- eget interface
                   4896: 
                   4897: sub eget {
1.133     albertel 4898:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4899:    my $items='';
1.800     albertel 4900:    foreach my $item (@$storearr) {
                   4901:        $items.=&escape($item).'&';
1.191     harris41 4902:    }
1.12      www      4903:    $items=~s/\&$//;
1.620     albertel 4904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4905:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4906:    my $uhome=&homeserver($uname,$udomain);
                   4907:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4908:    my @pairs=split(/\&/,$rep);
                   4909:    my %returnhash=();
1.42      www      4910:    my $i=0;
1.800     albertel 4911:    foreach my $item (@$storearr) {
                   4912:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4913:       $i++;
1.191     harris41 4914:    }
1.12      www      4915:    return %returnhash;
                   4916: }
                   4917: 
1.667     albertel 4918: # ------------------------------------------------------------ tmpput interface
                   4919: sub tmpput {
1.802     raeburn  4920:     my ($storehash,$server,$context)=@_;
1.667     albertel 4921:     my $items='';
1.800     albertel 4922:     foreach my $item (keys(%$storehash)) {
                   4923: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4924:     }
                   4925:     $items=~s/\&$//;
1.802     raeburn  4926:     if (defined($context)) {
                   4927:         $items .= ':'.&escape($context);
                   4928:     }
1.667     albertel 4929:     return &reply("tmpput:$items",$server);
                   4930: }
                   4931: 
                   4932: # ------------------------------------------------------------ tmpget interface
                   4933: sub tmpget {
1.688     albertel 4934:     my ($token,$server)=@_;
                   4935:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4936:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4937:     my %returnhash;
                   4938:     foreach my $item (split(/\&/,$rep)) {
                   4939: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4940:         next if ($key =~ /^error: 2 /);
1.667     albertel 4941: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4942:     }
                   4943:     return %returnhash;
                   4944: }
                   4945: 
1.1113    raeburn  4946: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4947: sub tmpdel {
                   4948:     my ($token,$server)=@_;
                   4949:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4950:     return &reply("tmpdel:$token",$server);
                   4951: }
                   4952: 
1.765     albertel 4953: # -------------------------------------------------- portfolio access checking
                   4954: 
                   4955: sub portfolio_access {
1.766     albertel 4956:     my ($requrl) = @_;
1.765     albertel 4957:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4958:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4959:     if ($result) {
                   4960:         my %setters;
                   4961:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4962:             my ($startblock,$endblock) =
                   4963:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4964:             if ($startblock && $endblock) {
                   4965:                 return 'B';
                   4966:             }
                   4967:         } else {
                   4968:             my ($startblock,$endblock) =
                   4969:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4970:             if ($startblock && $endblock) {
                   4971:                 return 'B';
                   4972:             }
                   4973:         }
                   4974:     }
1.765     albertel 4975:     if ($result eq 'ok') {
1.766     albertel 4976:        return 'F';
1.765     albertel 4977:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4978:        return 'A';
1.765     albertel 4979:     }
1.766     albertel 4980:     return '';
1.765     albertel 4981: }
                   4982: 
                   4983: sub get_portfolio_access {
1.767     albertel 4984:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4985: 
                   4986:     if (!ref($access_hash)) {
                   4987: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4988: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4989: 						   $file_name);
                   4990: 	$access_hash = $access_controls{$file_name};
                   4991:     }
                   4992: 
1.765     albertel 4993:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4994:     my $now = time;
                   4995:     if (ref($access_hash) eq 'HASH') {
                   4996:         foreach my $key (keys(%{$access_hash})) {
                   4997:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4998:             if ($start > $now) {
                   4999:                 next;
                   5000:             }
                   5001:             if ($end && $end<$now) {
                   5002:                 next;
                   5003:             }
                   5004:             if ($scope eq 'public') {
                   5005:                 $public = $key;
                   5006:                 last;
                   5007:             } elsif ($scope eq 'guest') {
                   5008:                 $guest = $key;
                   5009:             } elsif ($scope eq 'domains') {
                   5010:                 push(@domains,$key);
                   5011:             } elsif ($scope eq 'users') {
                   5012:                 push(@users,$key);
                   5013:             } elsif ($scope eq 'course') {
                   5014:                 push(@courses,$key);
                   5015:             } elsif ($scope eq 'group') {
                   5016:                 push(@groups,$key);
                   5017:             }
                   5018:         }
                   5019:         if ($public) {
                   5020:             return 'ok';
                   5021:         }
                   5022:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5023:             if ($guest) {
                   5024:                 return $guest;
                   5025:             }
                   5026:         } else {
                   5027:             if (@domains > 0) {
                   5028:                 foreach my $domkey (@domains) {
                   5029:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5030:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5031:                             return 'ok';
                   5032:                         }
                   5033:                     }
                   5034:                 }
                   5035:             }
                   5036:             if (@users > 0) {
                   5037:                 foreach my $userkey (@users) {
1.865     raeburn  5038:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5039:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5040:                             if (ref($item) eq 'HASH') {
                   5041:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5042:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5043:                                     return 'ok';
                   5044:                                 }
                   5045:                             }
                   5046:                         }
                   5047:                     } 
1.765     albertel 5048:                 }
                   5049:             }
                   5050:             my %roleshash;
                   5051:             my @courses_and_groups = @courses;
                   5052:             push(@courses_and_groups,@groups); 
                   5053:             if (@courses_and_groups > 0) {
                   5054:                 my (%allgroups,%allroles); 
                   5055:                 my ($start,$end,$role,$sec,$group);
                   5056:                 foreach my $envkey (%env) {
1.1060    raeburn  5057:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5058:                         my $cid = $2.'_'.$3; 
                   5059:                         if ($1 eq 'gr') {
                   5060:                             $group = $4;
                   5061:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5062:                         } else {
                   5063:                             if ($4 eq '') {
                   5064:                                 $sec = 'none';
                   5065:                             } else {
                   5066:                                 $sec = $4;
                   5067:                             }
                   5068:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5069:                         }
1.811     albertel 5070:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5071:                         my $cid = $2.'_'.$3;
                   5072:                         if ($4 eq '') {
                   5073:                             $sec = 'none';
                   5074:                         } else {
                   5075:                             $sec = $4;
                   5076:                         }
                   5077:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5078:                     }
                   5079:                 }
                   5080:                 if (keys(%allroles) == 0) {
                   5081:                     return;
                   5082:                 }
                   5083:                 foreach my $key (@courses_and_groups) {
                   5084:                     my %content = %{$$access_hash{$key}};
                   5085:                     my $cnum = $content{'number'};
                   5086:                     my $cdom = $content{'domain'};
                   5087:                     my $cid = $cdom.'_'.$cnum;
                   5088:                     if (!exists($allroles{$cid})) {
                   5089:                         next;
                   5090:                     }    
                   5091:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5092:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5093:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5094:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5095:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5096:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5097:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5098:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5099:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5100:                                         if (grep/^all$/,@sections) {
                   5101:                                             return 'ok';
                   5102:                                         } else {
                   5103:                                             if (grep/^$sec$/,@sections) {
                   5104:                                                 return 'ok';
                   5105:                                             }
                   5106:                                         }
                   5107:                                     }
                   5108:                                 }
                   5109:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5110:                                     if (grep/^none$/,@groups) {
                   5111:                                         return 'ok';
                   5112:                                     }
                   5113:                                 } else {
                   5114:                                     if (grep/^all$/,@groups) {
                   5115:                                         return 'ok';
                   5116:                                     } 
                   5117:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5118:                                         if (grep/^$group$/,@groups) {
                   5119:                                             return 'ok';
                   5120:                                         }
                   5121:                                     }
                   5122:                                 } 
                   5123:                             }
                   5124:                         }
                   5125:                     }
                   5126:                 }
                   5127:             }
                   5128:             if ($guest) {
                   5129:                 return $guest;
                   5130:             }
                   5131:         }
                   5132:     }
                   5133:     return;
                   5134: }
                   5135: 
                   5136: sub course_group_datechecker {
                   5137:     my ($dates,$now,$status) = @_;
                   5138:     my ($start,$end) = split(/\./,$dates);
                   5139:     if (!$start && !$end) {
                   5140:         return 'ok';
                   5141:     }
                   5142:     if (grep/^active$/,@{$status}) {
                   5143:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5144:             return 'ok';
                   5145:         }
                   5146:     }
                   5147:     if (grep/^previous$/,@{$status}) {
                   5148:         if ($end > $now ) {
                   5149:             return 'ok';
                   5150:         }
                   5151:     }
                   5152:     if (grep/^future$/,@{$status}) {
                   5153:         if ($start > $now) {
                   5154:             return 'ok';
                   5155:         }
                   5156:     }
                   5157:     return; 
                   5158: }
                   5159: 
                   5160: sub parse_portfolio_url {
                   5161:     my ($url) = @_;
                   5162: 
                   5163:     my ($type,$udom,$unum,$group,$file_name);
                   5164:     
1.823     albertel 5165:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5166: 	$type = 1;
                   5167:         $udom = $1;
                   5168:         $unum = $2;
                   5169:         $file_name = $3;
1.823     albertel 5170:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5171: 	$type = 2;
                   5172:         $udom = $1;
                   5173:         $unum = $2;
                   5174:         $group = $3;
                   5175:         $file_name = $3.'/'.$4;
                   5176:     }
                   5177:     if (wantarray) {
                   5178: 	return ($type,$udom,$unum,$file_name,$group);
                   5179:     }
                   5180:     return $type;
                   5181: }
                   5182: 
                   5183: sub is_portfolio_url {
                   5184:     my ($url) = @_;
                   5185:     return scalar(&parse_portfolio_url($url));
                   5186: }
                   5187: 
1.798     raeburn  5188: sub is_portfolio_file {
                   5189:     my ($file) = @_;
1.820     raeburn  5190:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5191:         return 1;
                   5192:     }
                   5193:     return;
                   5194: }
                   5195: 
1.976     raeburn  5196: sub usertools_access {
1.1084    raeburn  5197:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5198:     my ($access,%tools);
                   5199:     if ($context eq '') {
                   5200:         $context = 'tools';
                   5201:     }
                   5202:     if ($context eq 'requestcourses') {
                   5203:         %tools = (
                   5204:                       official   => 1,
                   5205:                       unofficial => 1,
1.1006    raeburn  5206:                       community  => 1,
1.985     raeburn  5207:                  );
                   5208:     } else {
                   5209:         %tools = (
                   5210:                       aboutme   => 1,
                   5211:                       blog      => 1,
                   5212:                       portfolio => 1,
                   5213:                  );
                   5214:     }
1.976     raeburn  5215:     return if (!defined($tools{$tool}));
                   5216: 
                   5217:     if ((!defined($udom)) || (!defined($uname))) {
                   5218:         $udom = $env{'user.domain'};
                   5219:         $uname = $env{'user.name'};
                   5220:     }
                   5221: 
1.978     raeburn  5222:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5223:         if ($action ne 'reload') {
1.985     raeburn  5224:             if ($context eq 'requestcourses') {
                   5225:                 return $env{'environment.canrequest.'.$tool};
                   5226:             } else {
                   5227:                 return $env{'environment.availabletools.'.$tool};
                   5228:             }
                   5229:         }
1.976     raeburn  5230:     }
                   5231: 
                   5232:     my ($toolstatus,$inststatus);
                   5233: 
1.985     raeburn  5234:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5235:          ($action ne 'reload')) {
                   5236:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5237:         $inststatus = $env{'environment.inststatus'};
                   5238:     } else {
1.1084    raeburn  5239:         if (ref($userenvref) eq 'HASH') {
                   5240:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5241:             $inststatus = $userenvref->{'inststatus'};
                   5242:         } else {
                   5243:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5244:             $toolstatus = $userenv{$context.'.'.$tool};
                   5245:             $inststatus = $userenv{'inststatus'};
                   5246:         }
1.976     raeburn  5247:     }
                   5248: 
                   5249:     if ($toolstatus ne '') {
                   5250:         if ($toolstatus) {
                   5251:             $access = 1;
                   5252:         } else {
                   5253:             $access = 0;
                   5254:         }
                   5255:         return $access;
                   5256:     }
                   5257: 
1.1084    raeburn  5258:     my ($is_adv,%domdef);
                   5259:     if (ref($is_advref) eq 'HASH') {
                   5260:         $is_adv = $is_advref->{'is_adv'};
                   5261:     } else {
                   5262:         $is_adv = &is_advanced_user($udom,$uname);
                   5263:     }
                   5264:     if (ref($domdefref) eq 'HASH') {
                   5265:         %domdef = %{$domdefref};
                   5266:     } else {
                   5267:         %domdef = &get_domain_defaults($udom);
                   5268:     }
1.976     raeburn  5269:     if (ref($domdef{$tool}) eq 'HASH') {
                   5270:         if ($is_adv) {
                   5271:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5272:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5273:                     $access = 1;
                   5274:                 } else {
                   5275:                     $access = 0;
                   5276:                 }
                   5277:                 return $access;
                   5278:             }
                   5279:         }
                   5280:         if ($inststatus ne '') {
                   5281:             my ($hasaccess,$hasnoaccess);
                   5282:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5283:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5284:                     if ($domdef{$tool}{$affiliation}) {
                   5285:                         $hasaccess = 1;
                   5286:                     } else {
                   5287:                         $hasnoaccess = 1;
                   5288:                     }
                   5289:                 }
                   5290:             }
                   5291:             if ($hasaccess || $hasnoaccess) {
                   5292:                 if ($hasaccess) {
                   5293:                     $access = 1;
                   5294:                 } elsif ($hasnoaccess) {
                   5295:                     $access = 0; 
                   5296:                 }
                   5297:                 return $access;
                   5298:             }
                   5299:         } else {
                   5300:             if ($domdef{$tool}{'default'} ne '') {
                   5301:                 if ($domdef{$tool}{'default'}) {
                   5302:                     $access = 1;
                   5303:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5304:                     $access = 0;
                   5305:                 }
                   5306:                 return $access;
                   5307:             }
                   5308:         }
                   5309:     } else {
1.985     raeburn  5310:         if ($context eq 'tools') {
                   5311:             $access = 1;
                   5312:         } else {
                   5313:             $access = 0;
                   5314:         }
1.976     raeburn  5315:         return $access;
                   5316:     }
                   5317: }
                   5318: 
1.1050    raeburn  5319: sub is_course_owner {
                   5320:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5321:     if (($udom eq '') || ($uname eq '')) {
                   5322:         $udom = $env{'user.domain'};
                   5323:         $uname = $env{'user.name'};
                   5324:     }
                   5325:     unless (($udom eq '') || ($uname eq '')) {
                   5326:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5327:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5328:                 return 1;
                   5329:             } else {
                   5330:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5331:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5332:                     return 1;
                   5333:                 }
                   5334:             }
                   5335:         }
                   5336:     }
                   5337:     return;
                   5338: }
                   5339: 
1.976     raeburn  5340: sub is_advanced_user {
                   5341:     my ($udom,$uname) = @_;
1.1085    raeburn  5342:     if ($udom ne '' && $uname ne '') {
                   5343:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5344:             return $env{'user.adv'};  
                   5345:         }
                   5346:     }
1.976     raeburn  5347:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5348:     my %allroles;
                   5349:     my $is_adv;
                   5350:     foreach my $role (keys(%roleshash)) {
                   5351:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5352:         my $area = '/'.$tdomain.'/'.$trest;
                   5353:         if ($sec ne '') {
                   5354:             $area .= '/'.$sec;
                   5355:         }
                   5356:         if (($area ne '') && ($trole ne '')) {
                   5357:             my $spec=$trole.'.'.$area;
                   5358:             if ($trole =~ /^cr\//) {
                   5359:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5360:             } elsif ($trole ne 'gr') {
                   5361:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5362:             }
                   5363:         }
                   5364:     }
                   5365:     foreach my $role (keys(%allroles)) {
                   5366:         last if ($is_adv);
                   5367:         foreach my $item (split(/:/,$allroles{$role})) {
                   5368:             if ($item ne '') {
                   5369:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5370:                 if ($privilege eq 'adv') {
                   5371:                     $is_adv = 1;
                   5372:                     last;
                   5373:                 }
                   5374:             }
                   5375:         }
                   5376:     }
                   5377:     return $is_adv;
                   5378: }
1.798     raeburn  5379: 
1.1035    raeburn  5380: sub check_can_request {
1.1036    raeburn  5381:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5382:     my $canreq = 0;
                   5383:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5384:     my @options = ('approval','validate','autolimit');
                   5385:     my $optregex = join('|',@options);
                   5386:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5387:         foreach my $type (@{$types}) {
                   5388:             if (&usertools_access($env{'user.name'},
                   5389:                                   $env{'user.domain'},
                   5390:                                   $type,undef,'requestcourses')) {
                   5391:                 $canreq ++;
1.1036    raeburn  5392:                 if (ref($request_domains) eq 'HASH') {
                   5393:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5394:                 }
1.1035    raeburn  5395:                 if ($dom eq $env{'user.domain'}) {
                   5396:                     $can_request->{$type} = 1;
                   5397:                 }
                   5398:             }
                   5399:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5400:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5401:                 if (@curr > 0) {
1.1036    raeburn  5402:                     foreach my $item (@curr) {
                   5403:                         if (ref($request_domains) eq 'HASH') {
                   5404:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5405:                             if ($otherdom ne '') {
                   5406:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5407:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5408:                                         push(@{$request_domains->{$type}},$otherdom);
                   5409:                                     }
                   5410:                                 } else {
                   5411:                                     push(@{$request_domains->{$type}},$otherdom);
                   5412:                                 }
                   5413:                             }
                   5414:                         }
                   5415:                     }
                   5416:                     unless($dom eq $env{'user.domain'}) {
                   5417:                         $canreq ++;
1.1035    raeburn  5418:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5419:                             $can_request->{$type} = 1;
                   5420:                         }
                   5421:                     }
                   5422:                 }
                   5423:             }
                   5424:         }
                   5425:     }
                   5426:     return $canreq;
                   5427: }
                   5428: 
1.341     www      5429: # ---------------------------------------------- Custom access rule evaluation
                   5430: 
                   5431: sub customaccess {
                   5432:     my ($priv,$uri)=@_;
1.807     albertel 5433:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5434:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5435:     $udom = &LONCAPA::clean_domain($udom);
                   5436:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5437:     my $access=0;
1.800     albertel 5438:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5439: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5440: 	if ($type eq 'user') {
                   5441: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5442: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5443: 		if ($tdom) {
                   5444: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5445: 		}
1.896     albertel 5446: 		if ($tuname) {
                   5447: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5448: 		}
                   5449: 		$access=($effect eq 'allow');
                   5450: 		last;
                   5451: 	    }
                   5452: 	} else {
                   5453: 	    if ($role) {
                   5454: 		if ($role ne $urole) { next; }
                   5455: 	    }
                   5456: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5457: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5458: 		if ($tdom) {
                   5459: 		    if ($tdom ne $udom) { next; }
                   5460: 		}
                   5461: 		if ($tcrs) {
                   5462: 		    if ($tcrs ne $ucrs) { next; }
                   5463: 		}
                   5464: 		if ($tsec) {
                   5465: 		    if ($tsec ne $usec) { next; }
                   5466: 		}
                   5467: 		$access=($effect eq 'allow');
                   5468: 		last;
                   5469: 	    }
                   5470: 	    if ($realm eq '' && $role eq '') {
                   5471: 		$access=($effect eq 'allow');
                   5472: 	    }
1.402     bowersj2 5473: 	}
1.341     www      5474:     }
                   5475:     return $access;
                   5476: }
                   5477: 
1.103     harris41 5478: # ------------------------------------------------- Check for a user privilege
1.12      www      5479: 
                   5480: sub allowed {
1.810     raeburn  5481:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5482:     my $ver_orguri=$uri;
1.439     www      5483:     $uri=&deversion($uri);
1.152     www      5484:     my $orguri=$uri;
1.52      www      5485:     $uri=&declutter($uri);
1.809     raeburn  5486: 
1.810     raeburn  5487:     if ($priv eq 'evb') {
                   5488: # Evade communication block restrictions for specified role in a course
                   5489:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5490:             return $1;
                   5491:         } else {
                   5492:             return;
                   5493:         }
                   5494:     }
                   5495: 
1.620     albertel 5496:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5497: # Free bre access to adm and meta resources
1.775     albertel 5498:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5499: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5500: 	&& ($priv eq 'bre')) {
1.14      www      5501: 	return 'F';
1.159     www      5502:     }
                   5503: 
1.545     banghart 5504: # Free bre access to user's own portfolio contents
1.714     raeburn  5505:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5506:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5507: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5508:         my %setters;
                   5509:         my ($startblock,$endblock) = 
                   5510:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5511:         if ($startblock && $endblock) {
                   5512:             return 'B';
                   5513:         } else {
                   5514:             return 'F';
                   5515:         }
1.545     banghart 5516:     }
                   5517: 
1.762     raeburn  5518: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5519:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5520:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5521:         if (exists($env{'request.course.id'})) {
                   5522:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5523:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5524:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5525:                 my $courseprivid=$env{'request.course.id'};
                   5526:                 $courseprivid=~s/\_/\//;
                   5527:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5528:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5529:                     return $1; 
1.762     raeburn  5530:                 } else {
                   5531:                     if ($env{'request.course.sec'}) {
                   5532:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5533:                     }
                   5534:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5535:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5536:                         return $2;
                   5537:                     }
1.714     raeburn  5538:                 }
                   5539:             }
                   5540:         }
                   5541:     }
                   5542: 
1.159     www      5543: # Free bre to public access
                   5544: 
                   5545:     if ($priv eq 'bre') {
1.238     www      5546:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5547: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5548:            return 'F'; 
                   5549:         }
1.238     www      5550:         if ($copyright eq 'priv') {
                   5551:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5552: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5553: 		return '';
                   5554:             }
                   5555:         }
                   5556:         if ($copyright eq 'domain') {
                   5557:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5558: 	    unless (($env{'user.domain'} eq $1) ||
                   5559:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5560: 		return '';
                   5561:             }
1.262     matthew  5562:         }
1.620     albertel 5563:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5564:             # Library role, so allow browsing of resources in this domain.
                   5565:             return 'F';
1.238     www      5566:         }
1.341     www      5567:         if ($copyright eq 'custom') {
                   5568: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5569:         }
1.14      www      5570:     }
1.264     matthew  5571:     # Domain coordinator is trying to create a course
1.620     albertel 5572:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5573:         # uri is the requested domain in this case.
                   5574:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5575:         # a role of dc for the domain in question.
1.620     albertel 5576:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5577:     }
1.29      www      5578: 
1.52      www      5579:     my $thisallowed='';
                   5580:     my $statecond=0;
                   5581:     my $courseprivid='';
                   5582: 
1.1039    raeburn  5583:     my $ownaccess;
1.1043    raeburn  5584:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5585:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5586:         if ($uri eq '') {
                   5587:             $ownaccess = 1;
                   5588:         } else {
                   5589:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5590:                 my $udom = $env{'user.domain'};
                   5591:                 my $uname = $env{'user.name'};
                   5592:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5593:                     $ownaccess = 1;
1.1040    raeburn  5594:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5595:                     unless ($uri =~ m{\.\./}) {
                   5596:                         $ownaccess = 1;
                   5597:                     }
                   5598:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5599:                     my $now = time;
                   5600:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5601:                         my $adom = $1;
                   5602:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5603:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5604:                                 my ($start,$end) = split('.',$env{$key});
                   5605:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5606:                                     $ownaccess = 1;
                   5607:                                     last;
                   5608:                                 }
                   5609:                             }
                   5610:                         }
                   5611:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5612:                         my $adom = $1;
                   5613:                         my $aname = $2;
1.1042    raeburn  5614:                         foreach my $role ('ca','aa') { 
                   5615:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5616:                                 my ($start,$end) =
                   5617:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5618:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5619:                                     $ownaccess = 1;
                   5620:                                     last;
                   5621:                                 }
1.1039    raeburn  5622:                             }
                   5623:                         }
                   5624:                     }
                   5625:                 }
                   5626:             }
                   5627:         }
                   5628:     }
                   5629: 
1.52      www      5630: # Course
                   5631: 
1.620     albertel 5632:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5633:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5634:             $thisallowed.=$1;
                   5635:         }
1.52      www      5636:     }
1.29      www      5637: 
1.52      www      5638: # Domain
                   5639: 
1.620     albertel 5640:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5641:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5642:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5643:             $thisallowed.=$1;
                   5644:         }
1.12      www      5645:     }
1.52      www      5646: 
                   5647: # Course: uri itself is a course
1.66      www      5648:     my $courseuri=$uri;
                   5649:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5650:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5651: 
1.620     albertel 5652:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5653:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5654:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5655:             $thisallowed.=$1;
                   5656:         }
1.12      www      5657:     }
1.29      www      5658: 
1.665     albertel 5659: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5660: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5661:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5662: 	$thisallowed='';
1.671     raeburn  5663:         my ($match)=&is_on_map($uri);
                   5664:         if ($match) {
                   5665:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5666:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5667:                 $thisallowed.=$1;
                   5668:             }
                   5669:         } else {
1.705     albertel 5670:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5671:             if ($refuri) {
                   5672:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5673:                     $thisallowed='F';
1.671     raeburn  5674:                 } else {
                   5675:                     $refuri=&declutter($refuri);
                   5676:                     my ($match) = &is_on_map($refuri);
                   5677:                     if ($match) {
                   5678:                         $thisallowed='F';
                   5679:                     }
1.669     raeburn  5680:                 }
1.671     raeburn  5681:             }
                   5682:         }
1.314     www      5683:     }
1.492     albertel 5684: 
1.766     albertel 5685:     if ($priv eq 'bre'
                   5686: 	&& $thisallowed ne 'F' 
                   5687: 	&& $thisallowed ne '2'
                   5688: 	&& &is_portfolio_url($uri)) {
                   5689: 	$thisallowed = &portfolio_access($uri);
                   5690:     }
                   5691:     
1.52      www      5692: # Full access at system, domain or course-wide level? Exit.
1.29      www      5693:     if ($thisallowed=~/F/) {
                   5694: 	return 'F';
                   5695:     }
                   5696: 
1.52      www      5697: # If this is generating or modifying users, exit with special codes
1.29      www      5698: 
1.643     www      5699:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5700: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5701: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5702: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5703: 	    unless ($auname) { return $thisallowed; }
                   5704: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5705: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5706: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5707: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5708: 	}
1.52      www      5709: 	return $thisallowed;
                   5710:     }
                   5711: #
1.103     harris41 5712: # Gathered so far: system, domain and course wide privileges
1.52      www      5713: #
                   5714: # Course: See if uri or referer is an individual resource that is part of 
                   5715: # the course
                   5716: 
1.620     albertel 5717:     if ($env{'request.course.id'}) {
1.232     www      5718: 
1.620     albertel 5719:        $courseprivid=$env{'request.course.id'};
                   5720:        if ($env{'request.course.sec'}) {
                   5721:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5722:        }
                   5723:        $courseprivid=~s/\_/\//;
                   5724:        my $checkreferer=1;
1.232     www      5725:        my ($match,$cond)=&is_on_map($uri);
                   5726:        if ($match) {
                   5727:            $statecond=$cond;
1.620     albertel 5728:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5729:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5730:                $thisallowed.=$1;
                   5731:                $checkreferer=0;
                   5732:            }
1.29      www      5733:        }
1.83      www      5734:        
1.148     www      5735:        if ($checkreferer) {
1.620     albertel 5736: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5737:             unless ($refuri) {
1.800     albertel 5738:                 foreach my $key (keys(%env)) {
                   5739: 		    if ($key=~/^httpref\..*\*/) {
                   5740: 			my $pattern=$key;
1.156     www      5741:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5742:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5743:                         $pattern=~s/\//\\\//g;
1.152     www      5744:                         if ($orguri=~/$pattern/) {
1.800     albertel 5745: 			    $refuri=$env{$key};
1.148     www      5746:                         }
                   5747:                     }
1.191     harris41 5748:                 }
1.148     www      5749:             }
1.232     www      5750: 
1.148     www      5751:          if ($refuri) { 
1.152     www      5752: 	  $refuri=&declutter($refuri);
1.232     www      5753:           my ($match,$cond)=&is_on_map($refuri);
                   5754:             if ($match) {
                   5755:               my $refstatecond=$cond;
1.620     albertel 5756:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5757:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5758:                   $thisallowed.=$1;
1.53      www      5759:                   $uri=$refuri;
                   5760:                   $statecond=$refstatecond;
1.52      www      5761:               }
                   5762:           }
1.148     www      5763:         }
1.29      www      5764:        }
1.52      www      5765:    }
1.29      www      5766: 
1.52      www      5767: #
1.103     harris41 5768: # Gathered now: all privileges that could apply, and condition number
1.52      www      5769: # 
                   5770: #
                   5771: # Full or no access?
                   5772: #
1.29      www      5773: 
1.52      www      5774:     if ($thisallowed=~/F/) {
                   5775: 	return 'F';
                   5776:     }
1.29      www      5777: 
1.52      www      5778:     unless ($thisallowed) {
                   5779:         return '';
                   5780:     }
1.29      www      5781: 
1.52      www      5782: # Restrictions exist, deal with them
                   5783: #
                   5784: #   C:according to course preferences
                   5785: #   R:according to resource settings
                   5786: #   L:unless locked
                   5787: #   X:according to user session state
                   5788: #
                   5789: 
                   5790: # Possibly locked functionality, check all courses
1.54      www      5791: # Locks might take effect only after 10 minutes cache expiration for other
                   5792: # courses, and 2 minutes for current course
1.52      www      5793: 
                   5794:     my $envkey;
                   5795:     if ($thisallowed=~/L/) {
1.1000    raeburn  5796:         foreach $envkey (keys(%env)) {
1.54      www      5797:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5798:                my $courseid=$2;
                   5799:                my $roleid=$1.'.'.$2;
1.92      www      5800:                $courseid=~s/^\///;
1.54      www      5801:                my $expiretime=600;
1.620     albertel 5802:                if ($env{'request.role'} eq $roleid) {
1.54      www      5803: 		  $expiretime=120;
                   5804:                }
                   5805: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5806:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5807:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5808: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5809:                }
1.620     albertel 5810:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5811:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5812: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5813:                        &log($env{'user.domain'},$env{'user.name'},
                   5814:                             $env{'user.home'},
1.57      www      5815:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5816:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5817:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5818: 		       return '';
                   5819:                    }
                   5820:                }
1.620     albertel 5821:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5822:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5823: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5824:                        &log($env{'user.domain'},$env{'user.name'},
                   5825:                             $env{'user.home'},
1.57      www      5826:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5827:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5828:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5829: 		       return '';
                   5830:                    }
                   5831:                }
                   5832: 	   }
1.29      www      5833:        }
1.52      www      5834:     }
                   5835:    
                   5836: #
                   5837: # Rest of the restrictions depend on selected course
                   5838: #
                   5839: 
1.620     albertel 5840:     unless ($env{'request.course.id'}) {
1.766     albertel 5841: 	if ($thisallowed eq 'A') {
                   5842: 	    return 'A';
1.814     raeburn  5843:         } elsif ($thisallowed eq 'B') {
                   5844:             return 'B';
1.766     albertel 5845: 	} else {
                   5846: 	    return '1';
                   5847: 	}
1.52      www      5848:     }
1.29      www      5849: 
1.52      www      5850: #
                   5851: # Now user is definitely in a course
                   5852: #
1.53      www      5853: 
                   5854: 
                   5855: # Course preferences
                   5856: 
                   5857:    if ($thisallowed=~/C/) {
1.620     albertel 5858:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5859:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5860:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5861: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5862: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5863: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5864: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5865: 			$env{'request.course.id'});
                   5866: 	   }
1.237     www      5867:            return '';
                   5868:        }
                   5869: 
1.620     albertel 5870:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5871: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5872: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5873: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5874: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5875: 			$env{'request.course.id'});
                   5876: 	   }
1.54      www      5877:            return '';
                   5878:        }
1.53      www      5879:    }
                   5880: 
                   5881: # Resource preferences
                   5882: 
                   5883:    if ($thisallowed=~/R/) {
1.620     albertel 5884:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5885:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5886: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5887: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5888: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5889: 	   }
                   5890: 	   return '';
1.54      www      5891:        }
1.53      www      5892:    }
1.30      www      5893: 
1.246     www      5894: # Restricted by state or randomout?
1.30      www      5895: 
1.52      www      5896:    if ($thisallowed=~/X/) {
1.620     albertel 5897:       if ($env{'acc.randomout'}) {
1.579     albertel 5898: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5899:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5900:             return ''; 
                   5901:          }
1.247     www      5902:       }
                   5903:       if (&condval($statecond)) {
1.52      www      5904: 	 return '2';
                   5905:       } else {
                   5906:          return '';
                   5907:       }
                   5908:    }
1.30      www      5909: 
1.766     albertel 5910:     if ($thisallowed eq 'A') {
                   5911: 	return 'A';
1.814     raeburn  5912:     } elsif ($thisallowed eq 'B') {
                   5913:         return 'B';
1.766     albertel 5914:     }
1.52      www      5915:    return 'F';
1.232     www      5916: }
                   5917: 
1.710     albertel 5918: sub split_uri_for_cond {
                   5919:     my $uri=&deversion(&declutter(shift));
                   5920:     my @uriparts=split(/\//,$uri);
                   5921:     my $filename=pop(@uriparts);
                   5922:     my $pathname=join('/',@uriparts);
                   5923:     return ($pathname,$filename);
                   5924: }
1.232     www      5925: # --------------------------------------------------- Is a resource on the map?
                   5926: 
                   5927: sub is_on_map {
1.710     albertel 5928:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5929:     #Trying to find the conditional for the file
1.620     albertel 5930:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5931: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5932:     if ($match) {
1.289     bowersj2 5933: 	return (1,$1);
                   5934:     } else {
1.434     www      5935: 	return (0,0);
1.289     bowersj2 5936:     }
1.12      www      5937: }
                   5938: 
1.427     www      5939: # --------------------------------------------------------- Get symb from alias
                   5940: 
                   5941: sub get_symb_from_alias {
                   5942:     my $symb=shift;
                   5943:     my ($map,$resid,$url)=&decode_symb($symb);
                   5944: # Already is a symb
                   5945:     if ($url) { return $symb; }
                   5946: # Must be an alias
                   5947:     my $aliassymb='';
                   5948:     my %bighash;
1.620     albertel 5949:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5950:                             &GDBM_READER(),0640)) {
                   5951:         my $rid=$bighash{'mapalias_'.$symb};
                   5952: 	if ($rid) {
                   5953: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5954: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5955: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5956: 	}
                   5957:         untie %bighash;
                   5958:     }
                   5959:     return $aliassymb;
                   5960: }
                   5961: 
1.12      www      5962: # ----------------------------------------------------------------- Define Role
                   5963: 
                   5964: sub definerole {
                   5965:   if (allowed('mcr','/')) {
                   5966:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5967:     foreach my $role (split(':',$sysrole)) {
                   5968: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5969:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5970:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5971: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5972:                return "refused:s:$crole&$cqual"; 
                   5973:             }
                   5974:         }
1.191     harris41 5975:     }
1.800     albertel 5976:     foreach my $role (split(':',$domrole)) {
                   5977: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5978:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5979:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5980: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5981:                return "refused:d:$crole&$cqual"; 
                   5982:             }
                   5983:         }
1.191     harris41 5984:     }
1.800     albertel 5985:     foreach my $role (split(':',$courole)) {
                   5986: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5987:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5988:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5989: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5990:                return "refused:c:$crole&$cqual"; 
                   5991:             }
                   5992:         }
1.191     harris41 5993:     }
1.620     albertel 5994:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5995:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5996: 	        "rolesdef_$rolename=".
                   5997:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5998:     return reply($command,$env{'user.home'});
1.12      www      5999:   } else {
                   6000:     return 'refused';
                   6001:   }
1.105     harris41 6002: }
                   6003: 
                   6004: # ---------------- Make a metadata query against the network of library servers
                   6005: 
                   6006: sub metadata_query {
1.244     matthew  6007:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6008:     my %rhash;
1.845     albertel 6009:     my %libserv = &all_library();
1.244     matthew  6010:     my @server_list = (defined($server_array) ? @$server_array
                   6011:                                               : keys(%libserv) );
                   6012:     for my $server (@server_list) {
1.118     harris41 6013: 	unless ($custom or $customshow) {
                   6014: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6015: 	    $rhash{$server}=$reply;
                   6016: 	}
                   6017: 	else {
                   6018: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6019: 			     &escape($custom).':'.&escape($customshow),
                   6020: 			     $server);
                   6021: 	    $rhash{$server}=$reply;
                   6022: 	}
1.112     harris41 6023:     }
1.118     harris41 6024:     return \%rhash;
1.240     www      6025: }
                   6026: 
                   6027: # ----------------------------------------- Send log queries and wait for reply
                   6028: 
                   6029: sub log_query {
                   6030:     my ($uname,$udom,$query,%filters)=@_;
                   6031:     my $uhome=&homeserver($uname,$udom);
                   6032:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6033:     my $uhost=&hostname($uhome);
1.800     albertel 6034:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6035:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6036:                        $uhome);
1.479     albertel 6037:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6038:     return get_query_reply($queryid);
                   6039: }
                   6040: 
1.818     raeburn  6041: # -------------------------- Update MySQL table for portfolio file
                   6042: 
                   6043: sub update_portfolio_table {
1.821     raeburn  6044:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6045:     if ($group ne '') {
                   6046:         $file_name =~s /^\Q$group\E//;
                   6047:     }
1.818     raeburn  6048:     my $homeserver = &homeserver($uname,$udom);
                   6049:     my $queryid=
1.821     raeburn  6050:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6051:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6052:     my $reply = &get_query_reply($queryid);
                   6053:     return $reply;
                   6054: }
                   6055: 
1.899     raeburn  6056: # -------------------------- Update MySQL allusers table
                   6057: 
                   6058: sub update_allusers_table {
                   6059:     my ($uname,$udom,$names) = @_;
                   6060:     my $homeserver = &homeserver($uname,$udom);
                   6061:     my $queryid=
                   6062:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6063:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6064:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6065:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6066:                'generation='.&escape($names->{'generation'}).'%%'.
                   6067:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6068:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6069:     return;
1.899     raeburn  6070: }
                   6071: 
1.508     raeburn  6072: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6073: 
                   6074: sub fetch_enrollment_query {
1.511     raeburn  6075:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6076:     my $homeserver;
1.547     raeburn  6077:     my $maxtries = 1;
1.508     raeburn  6078:     if ($context eq 'automated') {
                   6079:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6080:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6081:     } else {
                   6082:         $homeserver = &homeserver($cnum,$dom);
                   6083:     }
1.838     albertel 6084:     my $host=&hostname($homeserver);
1.506     raeburn  6085:     my $cmd = '';
1.1000    raeburn  6086:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6087:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6088:     }
                   6089:     $cmd =~ s/%%$//;
                   6090:     $cmd = &escape($cmd);
                   6091:     my $query = 'fetchenrollment';
1.620     albertel 6092:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6093:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6094:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6095:         return 'error: '.$queryid;
                   6096:     }
1.506     raeburn  6097:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6098:     my $tries = 1;
                   6099:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6100:         $reply = &get_query_reply($queryid);
                   6101:         $tries ++;
                   6102:     }
1.526     raeburn  6103:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6104:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6105:     } else {
1.901     albertel 6106:         my @responses = split(/:/,$reply);
1.515     raeburn  6107:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6108:             foreach my $line (@responses) {
                   6109:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6110:                 $$replyref{$key} = $value;
                   6111:             }
                   6112:         } else {
1.1117    foxr     6113:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6114:             foreach my $line (@responses) {
                   6115:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6116:                 $$replyref{$key} = $value;
                   6117:                 if ($value > 0) {
1.800     albertel 6118:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6119:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6120:                         my $destname = $pathname.'/'.$filename;
                   6121:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6122:                         if ($xml_classlist =~ /^error/) {
                   6123:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6124:                         } else {
1.506     raeburn  6125:                             if ( open(FILE,">$destname") ) {
                   6126:                                 print FILE &unescape($xml_classlist);
                   6127:                                 close(FILE);
1.526     raeburn  6128:                             } else {
                   6129:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6130:                             }
                   6131:                         }
                   6132:                     }
                   6133:                 }
                   6134:             }
                   6135:         }
                   6136:         return 'ok';
                   6137:     }
                   6138:     return 'error';
                   6139: }
                   6140: 
1.242     www      6141: sub get_query_reply {
                   6142:     my $queryid=shift;
1.1117    foxr     6143:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6144:     my $reply='';
                   6145:     for (1..100) {
                   6146: 	sleep 2;
                   6147:         if (-e $replyfile.'.end') {
1.448     albertel 6148: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6149: 		$reply = join('',<$fh>);
                   6150: 		close($fh);
1.240     www      6151: 	   } else { return 'error: reply_file_error'; }
1.242     www      6152:            return &unescape($reply);
                   6153: 	}
1.240     www      6154:     }
1.242     www      6155:     return 'timeout:'.$queryid;
1.240     www      6156: }
                   6157: 
                   6158: sub courselog_query {
1.241     www      6159: #
                   6160: # possible filters:
                   6161: # url: url or symb
                   6162: # username
                   6163: # domain
                   6164: # action: view, submit, grade
                   6165: # start: timestamp
                   6166: # end: timestamp
                   6167: #
1.240     www      6168:     my (%filters)=@_;
1.620     albertel 6169:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6170:     if ($filters{'url'}) {
                   6171: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6172:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6173:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6174:     }
1.620     albertel 6175:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6176:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6177:     return &log_query($cname,$cdom,'courselog',%filters);
                   6178: }
                   6179: 
                   6180: sub userlog_query {
1.858     raeburn  6181: #
                   6182: # possible filters:
                   6183: # action: log check role
                   6184: # start: timestamp
                   6185: # end: timestamp
                   6186: #
1.240     www      6187:     my ($uname,$udom,%filters)=@_;
                   6188:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6189: }
                   6190: 
1.506     raeburn  6191: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6192: 
                   6193: sub auto_run {
1.508     raeburn  6194:     my ($cnum,$cdom) = @_;
1.876     raeburn  6195:     my $response = 0;
                   6196:     my $settings;
                   6197:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6198:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6199:         $settings = $domconfig{'autoenroll'};
                   6200:         if ($settings->{'run'} eq '1') {
                   6201:             $response = 1;
                   6202:         }
                   6203:     } else {
1.934     raeburn  6204:         my $homeserver;
                   6205:         if (&is_course($cdom,$cnum)) {
                   6206:             $homeserver = &homeserver($cnum,$cdom);
                   6207:         } else {
                   6208:             $homeserver = &domain($cdom,'primary');
                   6209:         }
                   6210:         if ($homeserver ne 'no_host') {
                   6211:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6212:         }
1.876     raeburn  6213:     }
1.506     raeburn  6214:     return $response;
                   6215: }
1.776     albertel 6216: 
1.506     raeburn  6217: sub auto_get_sections {
1.508     raeburn  6218:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6219:     my $homeserver;
                   6220:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6221:         $homeserver = &homeserver($cnum,$cdom);
                   6222:     }
                   6223:     if (!defined($homeserver)) { 
                   6224:         if ($cdom =~ /^$match_domain$/) {
                   6225:             $homeserver = &domain($cdom,'primary');
                   6226:         }
                   6227:     }
                   6228:     my @secs;
                   6229:     if (defined($homeserver)) {
                   6230:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6231:         unless ($response eq 'refused') {
                   6232:             @secs = split(/:/,$response);
                   6233:         }
1.506     raeburn  6234:     }
                   6235:     return @secs;
                   6236: }
1.776     albertel 6237: 
1.506     raeburn  6238: sub auto_new_course {
1.1099    raeburn  6239:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6240:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6241:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6242:     return $response;
                   6243: }
1.776     albertel 6244: 
1.506     raeburn  6245: sub auto_validate_courseID {
1.508     raeburn  6246:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6247:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6248:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6249:     return $response;
                   6250: }
1.776     albertel 6251: 
1.1007    raeburn  6252: sub auto_validate_instcode {
1.1020    raeburn  6253:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6254:     my ($homeserver,$response);
                   6255:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6256:         $homeserver = &homeserver($cnum,$cdom);
                   6257:     }
                   6258:     if (!defined($homeserver)) {
                   6259:         if ($cdom =~ /^$match_domain$/) {
                   6260:             $homeserver = &domain($cdom,'primary');
                   6261:         }
                   6262:     }
1.1065    raeburn  6263:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6264:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6265:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6266:     return ($outcome,$description);
1.1007    raeburn  6267: }
                   6268: 
1.506     raeburn  6269: sub auto_create_password {
1.873     raeburn  6270:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6271:     my ($homeserver,$response);
1.506     raeburn  6272:     my $create_passwd = 0;
                   6273:     my $authchk = '';
1.873     raeburn  6274:     if ($udom =~ /^$match_domain$/) {
                   6275:         $homeserver = &domain($udom,'primary');
                   6276:     }
                   6277:     if ($homeserver eq '') {
                   6278:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6279:             $homeserver = &homeserver($cnum,$cdom);
                   6280:         }
                   6281:     }
                   6282:     if ($homeserver eq '') {
                   6283:         $authchk = 'nodomain';
1.506     raeburn  6284:     } else {
1.873     raeburn  6285:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6286:         if ($response eq 'refused') {
                   6287:             $authchk = 'refused';
                   6288:         } else {
1.901     albertel 6289:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6290:         }
1.506     raeburn  6291:     }
                   6292:     return ($authparam,$create_passwd,$authchk);
                   6293: }
                   6294: 
1.706     raeburn  6295: sub auto_photo_permission {
                   6296:     my ($cnum,$cdom,$students) = @_;
                   6297:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6298:     my ($outcome,$perm_reqd,$conditions) = 
                   6299: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6300:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6301: 	return (undef,undef);
                   6302:     }
1.706     raeburn  6303:     return ($outcome,$perm_reqd,$conditions);
                   6304: }
                   6305: 
                   6306: sub auto_checkphotos {
                   6307:     my ($uname,$udom,$pid) = @_;
                   6308:     my $homeserver = &homeserver($uname,$udom);
                   6309:     my ($result,$resulttype);
                   6310:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6311: 				   &escape($uname).':'.&escape($pid),
                   6312: 				   $homeserver));
1.709     albertel 6313:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6314: 	return (undef,undef);
                   6315:     }
1.706     raeburn  6316:     if ($outcome) {
                   6317:         ($result,$resulttype) = split(/:/,$outcome);
                   6318:     } 
                   6319:     return ($result,$resulttype);
                   6320: }
                   6321: 
                   6322: sub auto_photochoice {
                   6323:     my ($cnum,$cdom) = @_;
                   6324:     my $homeserver = &homeserver($cnum,$cdom);
                   6325:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6326: 						       &escape($cdom),
                   6327: 						       $homeserver)));
1.709     albertel 6328:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6329: 	return (undef,undef);
                   6330:     }
1.706     raeburn  6331:     return ($update,$comment);
                   6332: }
                   6333: 
                   6334: sub auto_photoupdate {
                   6335:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6336:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6337:     my $host=&hostname($homeserver);
1.706     raeburn  6338:     my $cmd = '';
                   6339:     my $maxtries = 1;
1.800     albertel 6340:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6341:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6342:     }
                   6343:     $cmd =~ s/%%$//;
                   6344:     $cmd = &escape($cmd);
                   6345:     my $query = 'institutionalphotos';
                   6346:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6347:     unless ($queryid=~/^\Q$host\E\_/) {
                   6348:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6349:         return 'error: '.$queryid;
                   6350:     }
                   6351:     my $reply = &get_query_reply($queryid);
                   6352:     my $tries = 1;
                   6353:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6354:         $reply = &get_query_reply($queryid);
                   6355:         $tries ++;
                   6356:     }
                   6357:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6358:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6359:     } else {
                   6360:         my @responses = split(/:/,$reply);
                   6361:         my $outcome = shift(@responses); 
                   6362:         foreach my $item (@responses) {
                   6363:             my ($key,$value) = split(/=/,$item);
                   6364:             $$photo{$key} = $value;
                   6365:         }
                   6366:         return $outcome;
                   6367:     }
                   6368:     return 'error';
                   6369: }
                   6370: 
1.521     raeburn  6371: sub auto_instcode_format {
1.793     albertel 6372:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6373: 	$cat_order) = @_;
1.521     raeburn  6374:     my $courses = '';
1.772     raeburn  6375:     my @homeservers;
1.521     raeburn  6376:     if ($caller eq 'global') {
1.841     albertel 6377: 	my %servers = &get_servers($codedom,'library');
                   6378: 	foreach my $tryserver (keys(%servers)) {
                   6379: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6380: 		push(@homeservers,$tryserver);
                   6381: 	    }
1.584     raeburn  6382:         }
1.1022    raeburn  6383:     } elsif ($caller eq 'requests') {
                   6384:         if ($codedom =~ /^$match_domain$/) {
                   6385:             my $chome = &domain($codedom,'primary');
                   6386:             unless ($chome eq 'no_host') {
                   6387:                 push(@homeservers,$chome);
                   6388:             }
                   6389:         }
1.521     raeburn  6390:     } else {
1.772     raeburn  6391:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6392:     }
1.793     albertel 6393:     foreach my $code (keys(%{$instcodes})) {
                   6394:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6395:     }
                   6396:     chop($courses);
1.772     raeburn  6397:     my $ok_response = 0;
                   6398:     my $response;
                   6399:     while (@homeservers > 0 && $ok_response == 0) {
                   6400:         my $server = shift(@homeservers); 
                   6401:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6402:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6403:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6404: 		split(/:/,$response);
1.772     raeburn  6405:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6406:             push(@{$codetitles},&str2array($codetitles_str));
                   6407:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6408:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6409:             $ok_response = 1;
                   6410:         }
                   6411:     }
                   6412:     if ($ok_response) {
1.521     raeburn  6413:         return 'ok';
1.772     raeburn  6414:     } else {
                   6415:         return $response;
1.521     raeburn  6416:     }
                   6417: }
                   6418: 
1.792     raeburn  6419: sub auto_instcode_defaults {
                   6420:     my ($domain,$returnhash,$code_order) = @_;
                   6421:     my @homeservers;
1.841     albertel 6422: 
                   6423:     my %servers = &get_servers($domain,'library');
                   6424:     foreach my $tryserver (keys(%servers)) {
                   6425: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6426: 	    push(@homeservers,$tryserver);
                   6427: 	}
1.792     raeburn  6428:     }
1.841     albertel 6429: 
1.792     raeburn  6430:     my $response;
1.841     albertel 6431:     foreach my $server (@homeservers) {
1.792     raeburn  6432:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6433:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6434: 	
                   6435: 	foreach my $pair (split(/\&/,$response)) {
                   6436: 	    my ($name,$value)=split(/\=/,$pair);
                   6437: 	    if ($name eq 'code_order') {
                   6438: 		@{$code_order} = split(/\&/,&unescape($value));
                   6439: 	    } else {
                   6440: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6441: 	    }
                   6442: 	}
                   6443: 	return 'ok';
1.792     raeburn  6444:     }
1.841     albertel 6445: 
                   6446:     return $response;
1.1003    raeburn  6447: }
                   6448: 
                   6449: sub auto_possible_instcodes {
1.1007    raeburn  6450:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6451:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6452:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6453:         return;
                   6454:     }
1.1003    raeburn  6455:     my (@homeservers,$uhome);
                   6456:     if (defined(&domain($domain,'primary'))) {
                   6457:         $uhome=&domain($domain,'primary');
                   6458:         push(@homeservers,&domain($domain,'primary'));
                   6459:     } else {
                   6460:         my %servers = &get_servers($domain,'library');
                   6461:         foreach my $tryserver (keys(%servers)) {
                   6462:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6463:                 push(@homeservers,$tryserver);
                   6464:             }
                   6465:         }
                   6466:     }
                   6467:     my $response;
                   6468:     foreach my $server (@homeservers) {
                   6469:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6470:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6471:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6472:             split(':',$response);
                   6473:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6474:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6475:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6476:             my ($name,$value)=split('=',$item);
                   6477:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6478:         }
                   6479:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6480:             my ($name,$value)=split('=',$item);
                   6481:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6482:         }
                   6483:         return 'ok';
                   6484:     }
                   6485:     return $response;
                   6486: }
1.792     raeburn  6487: 
1.1010    raeburn  6488: sub auto_courserequest_checks {
                   6489:     my ($dom) = @_;
1.1020    raeburn  6490:     my ($homeserver,%validations);
                   6491:     if ($dom =~ /^$match_domain$/) {
                   6492:         $homeserver = &domain($dom,'primary');
                   6493:     }
                   6494:     unless ($homeserver eq 'no_host') {
                   6495:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6496:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6497:             my @items = split(/&/,$response);
                   6498:             foreach my $item (@items) {
                   6499:                 my ($key,$value) = split('=',$item);
                   6500:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6501:             }
                   6502:         }
                   6503:     }
1.1010    raeburn  6504:     return %validations; 
                   6505: }
                   6506: 
1.1020    raeburn  6507: sub auto_courserequest_validation {
                   6508:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6509:     my ($homeserver,$response);
                   6510:     if ($dom =~ /^$match_domain$/) {
                   6511:         $homeserver = &domain($dom,'primary');
                   6512:     }
                   6513:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6514:           
1.1020    raeburn  6515:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6516:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6517:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6518:                                     $homeserver));
                   6519:     }
                   6520:     return $response;
                   6521: }
                   6522: 
1.777     albertel 6523: sub auto_validate_class_sec {
1.918     raeburn  6524:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6525:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6526:     my $ownerlist;
                   6527:     if (ref($owners) eq 'ARRAY') {
                   6528:         $ownerlist = join(',',@{$owners});
                   6529:     } else {
                   6530:         $ownerlist = $owners;
                   6531:     }
1.773     raeburn  6532:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6533:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6534:     return $response;
                   6535: }
                   6536: 
1.679     raeburn  6537: # ------------------------------------------------------- Course Group routines
                   6538: 
                   6539: sub get_coursegroups {
1.809     raeburn  6540:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6541:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6542: }
                   6543: 
1.679     raeburn  6544: sub modify_coursegroup {
                   6545:     my ($cdom,$cnum,$groupsettings) = @_;
                   6546:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6547: }
                   6548: 
1.809     raeburn  6549: sub toggle_coursegroup_status {
                   6550:     my ($cdom,$cnum,$group,$action) = @_;
                   6551:     my ($from_namespace,$to_namespace);
                   6552:     if ($action eq 'delete') {
                   6553:         $from_namespace = 'coursegroups';
                   6554:         $to_namespace = 'deleted_groups';
                   6555:     } else {
                   6556:         $from_namespace = 'deleted_groups';
                   6557:         $to_namespace = 'coursegroups';
                   6558:     }
                   6559:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6560:     if (my $tmp = &error(%curr_group)) {
                   6561:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6562:         return ('read error',$tmp);
                   6563:     } else {
                   6564:         my %savedsettings = %curr_group; 
1.809     raeburn  6565:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6566:         my $deloutcome;
                   6567:         if ($result eq 'ok') {
1.809     raeburn  6568:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6569:         } else {
                   6570:             return ('write error',$result);
                   6571:         }
                   6572:         if ($deloutcome eq 'ok') {
                   6573:             return 'ok';
                   6574:         } else {
                   6575:             return ('delete error',$deloutcome);
                   6576:         }
                   6577:     }
                   6578: }
                   6579: 
1.679     raeburn  6580: sub modify_group_roles {
1.957     raeburn  6581:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6582:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6583:     my $role = 'gr/'.&escape($userprivs);
                   6584:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6585:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6586:     if ($result eq 'ok') {
                   6587:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6588:     }
1.679     raeburn  6589:     return $result;
                   6590: }
                   6591: 
                   6592: sub modify_coursegroup_membership {
                   6593:     my ($cdom,$cnum,$membership) = @_;
                   6594:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6595:     return $result;
                   6596: }
                   6597: 
1.682     raeburn  6598: sub get_active_groups {
                   6599:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6600:     my $now = time;
                   6601:     my %groups = ();
                   6602:     foreach my $key (keys(%env)) {
1.811     albertel 6603:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6604:             my ($start,$end) = split(/\./,$env{$key});
                   6605:             if (($end!=0) && ($end<$now)) { next; }
                   6606:             if (($start!=0) && ($start>$now)) { next; }
                   6607:             if ($1 eq $cdom && $2 eq $cnum) {
                   6608:                 $groups{$3} = $env{$key} ;
                   6609:             }
                   6610:         }
                   6611:     }
                   6612:     return %groups;
                   6613: }
                   6614: 
1.683     raeburn  6615: sub get_group_membership {
                   6616:     my ($cdom,$cnum,$group) = @_;
                   6617:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6618: }
                   6619: 
                   6620: sub get_users_groups {
                   6621:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6622:     my @usersgroups;
1.683     raeburn  6623:     my $cachetime=1800;
                   6624: 
                   6625:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6626:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6627:     if (defined($cached)) {
1.734     albertel 6628:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6629:     } else {  
                   6630:         $grouplist = '';
1.816     raeburn  6631:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6632:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6633:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6634:         my $access_end = $env{'course.'.$courseid.
                   6635:                               '.default_enrollment_end_date'};
                   6636:         my $now = time;
                   6637:         foreach my $key (keys(%roleshash)) {
                   6638:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6639:                 my $group = $1;
                   6640:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6641:                     my $start = $2;
                   6642:                     my $end = $1;
                   6643:                     if ($start == -1) { next; } # deleted from group
                   6644:                     if (($start!=0) && ($start>$now)) { next; }
                   6645:                     if (($end!=0) && ($end<$now)) {
                   6646:                         if ($access_end && $access_end < $now) {
                   6647:                             if ($access_end - $end < 86400) {
                   6648:                                 push(@usersgroups,$group);
1.733     raeburn  6649:                             }
                   6650:                         }
1.817     raeburn  6651:                         next;
1.733     raeburn  6652:                     }
1.817     raeburn  6653:                     push(@usersgroups,$group);
1.683     raeburn  6654:                 }
                   6655:             }
                   6656:         }
1.817     raeburn  6657:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6658:         $grouplist = join(':',@usersgroups);
                   6659:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6660:     }
1.733     raeburn  6661:     return @usersgroups;
1.683     raeburn  6662: }
                   6663: 
                   6664: sub devalidate_getgroups_cache {
                   6665:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6666:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6667: 
1.683     raeburn  6668:     my $hashid="$udom:$uname:$courseid";
                   6669:     &devalidate_cache_new('getgroups',$hashid);
                   6670: }
                   6671: 
1.12      www      6672: # ------------------------------------------------------------------ Plain Text
                   6673: 
                   6674: sub plaintext {
1.988     raeburn  6675:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6676:     if ($short =~ m{^cr/}) {
1.758     albertel 6677: 	return (split('/',$short))[-1];
                   6678:     }
1.742     raeburn  6679:     if (!defined($cid)) {
                   6680:         $cid = $env{'request.course.id'};
                   6681:     }
                   6682:     my %rolenames = (
1.1008    raeburn  6683:                       Course    => 'std',
                   6684:                       Community => 'alt1',
1.742     raeburn  6685:                     );
1.1037    raeburn  6686:     if ($cid ne '') {
                   6687:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6688:             unless ($forcedefault) {
                   6689:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6690:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6691:                 return &Apache::lonlocal::mt($roletext);
                   6692:             }
                   6693:         }
                   6694:     }
                   6695:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6696:         (defined($rolenames{$type})) && 
                   6697:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6698:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6699:     } elsif ($cid ne '') {
                   6700:         my $crstype = $env{'course.'.$cid.'.type'};
                   6701:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6702:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6703:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6704:         }
1.742     raeburn  6705:     }
1.1037    raeburn  6706:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6707: }
                   6708: 
                   6709: # ----------------------------------------------------------------- Assign Role
                   6710: 
                   6711: sub assignrole {
1.957     raeburn  6712:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6713:         $context)=@_;
1.21      www      6714:     my $mrole;
                   6715:     if ($role =~ /^cr\//) {
1.393     www      6716:         my $cwosec=$url;
1.811     albertel 6717:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6718: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6719:            my $refused = 1;
                   6720:            if ($context eq 'requestcourses') {
                   6721:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6722:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6723:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6724:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6725:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6726:                            if ($crsenv{'internal.courseowner'} eq
                   6727:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6728:                                $refused = '';
                   6729:                            }
                   6730:                        }
                   6731:                    }
                   6732:                }
                   6733:            }
                   6734:            if ($refused) {
                   6735:                &logthis('Refused custom assignrole: '.
                   6736:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6737:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6738:                return 'refused';
                   6739:            }
1.104     www      6740:         }
1.21      www      6741:         $mrole='cr';
1.678     raeburn  6742:     } elsif ($role =~ /^gr\//) {
                   6743:         my $cwogrp=$url;
1.811     albertel 6744:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6745:         unless (&allowed('mdg',$cwogrp)) {
                   6746:             &logthis('Refused group assignrole: '.
                   6747:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6748:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6749:             return 'refused';
                   6750:         }
                   6751:         $mrole='gr';
1.21      www      6752:     } else {
1.82      www      6753:         my $cwosec=$url;
1.811     albertel 6754:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6755:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6756:             my $refused;
                   6757:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6758:                 if (!(&allowed('c'.$role,$url))) {
                   6759:                     $refused = 1;
                   6760:                 }
                   6761:             } else {
                   6762:                 $refused = 1;
                   6763:             }
1.947     raeburn  6764:             if ($refused) {
1.1045    raeburn  6765:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6766:                 if (!$selfenroll && $context eq 'course') {
                   6767:                     my %crsenv;
                   6768:                     if ($role eq 'cc' || $role eq 'co') {
                   6769:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6770:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6771:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6772:                                 if ($crsenv{'internal.courseowner'} eq 
                   6773:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6774:                                     $refused = '';
                   6775:                                 }
                   6776:                             }
                   6777:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6778:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6779:                                 if ($crsenv{'internal.courseowner'} eq 
                   6780:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6781:                                     $refused = '';
                   6782:                                 }
                   6783:                             }
                   6784:                         }
                   6785:                     }
                   6786:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6787:                     $refused = '';
1.1017    raeburn  6788:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6789:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6790:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6791:                         my $wrongcc;
                   6792:                         if ($cnum =~ /^$match_community$/) {
                   6793:                             $wrongcc = 1 if ($role eq 'cc');
                   6794:                         } else {
                   6795:                             $wrongcc = 1 if ($role eq 'co');
                   6796:                         }
                   6797:                         unless ($wrongcc) {
                   6798:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6799:                             if ($crsenv{'internal.courseowner'} eq 
                   6800:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6801:                                 $refused = '';
                   6802:                             }
1.1017    raeburn  6803:                         }
                   6804:                     }
                   6805:                 }
                   6806:                 if ($refused) {
1.947     raeburn  6807:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6808:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6809: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6810:                     return 'refused';
                   6811:                 }
1.932     raeburn  6812:             }
1.104     www      6813:         }
1.21      www      6814:         $mrole=$role;
                   6815:     }
1.620     albertel 6816:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6817:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6818:     if ($end) { $command.='_'.$end; }
1.21      www      6819:     if ($start) {
                   6820: 	if ($end) { 
1.81      www      6821:            $command.='_'.$start; 
1.21      www      6822:         } else {
1.81      www      6823:            $command.='_0_'.$start;
1.21      www      6824:         }
                   6825:     }
1.739     raeburn  6826:     my $origstart = $start;
                   6827:     my $origend = $end;
1.957     raeburn  6828:     my $delflag;
1.357     www      6829: # actually delete
                   6830:     if ($deleteflag) {
1.373     www      6831: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6832: # modify command to delete the role
1.620     albertel 6833:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6834:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6835: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6836: # set start and finish to negative values for userrolelog
                   6837:            $start=-1;
                   6838:            $end=-1;
1.957     raeburn  6839:            $delflag = 1;
1.357     www      6840:         }
                   6841:     }
                   6842: # send command
1.349     www      6843:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6844: # log new user role if status is ok
1.349     www      6845:     if ($answer eq 'ok') {
1.663     raeburn  6846: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6847: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6848:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6849:         unless ($role =~ /^gr/) {
                   6850:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6851:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6852:         }
1.1053    raeburn  6853:         if ($role eq 'cc') {
                   6854:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6855:         }
1.349     www      6856:     }
                   6857:     return $answer;
1.169     harris41 6858: }
                   6859: 
1.1053    raeburn  6860: sub autoupdate_coowners {
                   6861:     my ($url,$end,$start,$uname,$udom) = @_;
                   6862:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6863:     if (($cdom ne '') && ($cnum ne '')) {
                   6864:         my $now = time;
                   6865:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6866:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6867:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6868:             my $instcode = $coursehash{'internal.coursecode'};
                   6869:             if ($instcode ne '') {
1.1056    raeburn  6870:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6871:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6872:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6873:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6874:                         if ($result eq 'valid') {
                   6875:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6876:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6877:                                     push(@newcoowners,$coowner);
                   6878:                                 }
                   6879:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6880:                                     push(@newcoowners,$uname.':'.$udom);
                   6881:                                 }
                   6882:                                 @newcoowners = sort(@newcoowners);
                   6883:                             } else {
                   6884:                                 push(@newcoowners,$uname.':'.$udom);
                   6885:                             }
                   6886:                         } else {
                   6887:                             if ($coursehash{'internal.co-owners'}) {
                   6888:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6889:                                     unless ($coowner eq $uname.':'.$udom) {
                   6890:                                         push(@newcoowners,$coowner);
                   6891:                                     }
                   6892:                                 }
                   6893:                                 unless (@newcoowners > 0) {
                   6894:                                     $delcoowners = 1;
                   6895:                                     $coowners = '';
                   6896:                                 }
                   6897:                             }
                   6898:                         }
                   6899:                         if (@newcoowners || $delcoowners) {
                   6900:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6901:                                             $delcoowners,@newcoowners);
                   6902:                         }
                   6903:                     }
                   6904:                 }
                   6905:             }
                   6906:         }
                   6907:     }
                   6908: }
                   6909: 
                   6910: sub store_coowners {
                   6911:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6912:     my $cid = $cdom.'_'.$cnum;
                   6913:     my ($coowners,$delresult,$putresult);
                   6914:     if (@newcoowners) {
                   6915:         $coowners = join(',',@newcoowners);
                   6916:         my %coownershash = (
                   6917:                             'internal.co-owners' => $coowners,
                   6918:                            );
                   6919:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6920:         if ($putresult eq 'ok') {
                   6921:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6922:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6923:             }
                   6924:         }
                   6925:     }
                   6926:     if ($delcoowners) {
                   6927:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6928:         if ($delresult eq 'ok') {
                   6929:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6930:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6931:             }
                   6932:         }
                   6933:     }
                   6934:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6935:         my %crsinfo =
                   6936:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6937:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6938:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6939:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6940:         }
                   6941:     }
                   6942: }
                   6943: 
1.169     harris41 6944: # -------------------------------------------------- Modify user authentication
1.197     www      6945: # Overrides without validation
                   6946: 
1.169     harris41 6947: sub modifyuserauth {
                   6948:     my ($udom,$uname,$umode,$upass)=@_;
                   6949:     my $uhome=&homeserver($uname,$udom);
1.197     www      6950:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6951:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6952:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6953:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6954:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6955: 		     &escape($upass),$uhome);
1.620     albertel 6956:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6957:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6958:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6959:     &log($udom,,$uname,$uhome,
1.620     albertel 6960:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6961:                                      $env{'user.name'}.', '.$umode.
1.197     www      6962:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6963:     unless ($reply eq 'ok') {
1.197     www      6964:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6965: 	return 'error: '.$reply;
                   6966:     }   
1.170     harris41 6967:     return 'ok';
1.80      www      6968: }
                   6969: 
1.81      www      6970: # --------------------------------------------------------------- Modify a user
1.80      www      6971: 
1.81      www      6972: sub modifyuser {
1.206     matthew  6973:     my ($udom,    $uname, $uid,
                   6974:         $umode,   $upass, $first,
                   6975:         $middle,  $last,  $gene,
1.1058    raeburn  6976:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6977:     $udom= &LONCAPA::clean_domain($udom);
                   6978:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6979:     my $showcandelete = 'none';
                   6980:     if (ref($candelete) eq 'ARRAY') {
                   6981:         if (@{$candelete} > 0) {
                   6982:             $showcandelete = join(', ',@{$candelete});
                   6983:         }
                   6984:     }
1.81      www      6985:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6986:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6987: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6988:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6989:                                      ' desiredhome not specified'). 
1.620     albertel 6990:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6991:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6992:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6993:     my $newuser;
                   6994:     if ($uhome eq 'no_host') {
                   6995:         $newuser = 1;
                   6996:     }
1.80      www      6997: # ----------------------------------------------------------------- Create User
1.406     albertel 6998:     if (($uhome eq 'no_host') && 
                   6999: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7000:         my $unhome='';
1.844     albertel 7001:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7002:             $unhome = $desiredhome;
1.620     albertel 7003: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7004: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7005:         } else { # load balancing routine for determining $unhome
1.81      www      7006:             my $loadm=10000000;
1.841     albertel 7007: 	    my %servers = &get_servers($udom,'library');
                   7008: 	    foreach my $tryserver (keys(%servers)) {
                   7009: 		my $answer=reply('load',$tryserver);
                   7010: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7011: 		    $loadm=$answer;
                   7012: 		    $unhome=$tryserver;
                   7013: 		}
1.80      www      7014: 	    }
                   7015:         }
                   7016:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7017: 	    return 'error: unable to find a home server for '.$uname.
                   7018:                    ' in domain '.$udom;
1.80      www      7019:         }
                   7020:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7021:                          &escape($upass),$unhome);
                   7022: 	unless ($reply eq 'ok') {
                   7023:             return 'error: '.$reply;
                   7024:         }   
1.230     stredwic 7025:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7026:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7027: 	    return 'error: unable verify users home machine.';
1.80      www      7028:         }
1.209     matthew  7029:     }   # End of creation of new user
1.80      www      7030: # ---------------------------------------------------------------------- Add ID
                   7031:     if ($uid) {
                   7032:        $uid=~tr/A-Z/a-z/;
                   7033:        my %uidhash=&idrget($udom,$uname);
1.196     www      7034:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7035:          && (!$forceid)) {
1.80      www      7036: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7037: 	      return 'error: user id "'.$uid.'" does not match '.
                   7038:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7039:           }
                   7040:        } else {
                   7041: 	  &idput($udom,($uname => $uid));
                   7042:        }
                   7043:     }
                   7044: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7045:     my @tmp=&get('environment',
1.899     raeburn  7046: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7047:                     'permanentemail','inststatus'],
1.134     albertel 7048: 		   $udom,$uname);
1.1075    raeburn  7049:     my (%names,%oldnames);
1.313     matthew  7050:     if ($tmp[0] =~ m/^error:.*/) { 
                   7051:         %names=(); 
                   7052:     } else {
                   7053:         %names = @tmp;
1.1075    raeburn  7054:         %oldnames = %names;
1.313     matthew  7055:     }
1.388     www      7056: #
1.1058    raeburn  7057: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7058: # of users did not contain them), do not overwrite existing values
                   7059: # unless field is in $candelete array ref.  
                   7060: #
                   7061: 
                   7062:     my @fields = ('firstname','middlename','lastname','generation',
                   7063:                   'permanentemail','id');
                   7064:     my %newvalues;
                   7065:     if (ref($candelete) eq 'ARRAY') {
                   7066:         foreach my $field (@fields) {
                   7067:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7068:                 if ($field eq 'firstname') {
                   7069:                     $names{$field} = $first;
                   7070:                 } elsif ($field eq 'middlename') {
                   7071:                     $names{$field} = $middle;
                   7072:                 } elsif ($field eq 'lastname') {
                   7073:                     $names{$field} = $last;
                   7074:                 } elsif ($field eq 'generation') { 
                   7075:                     $names{$field} = $gene;
                   7076:                 } elsif ($field eq 'permanentemail') {
                   7077:                     $names{$field} = $email;
                   7078:                 } elsif ($field eq 'id') {
                   7079:                     $names{$field}  = $uid;
                   7080:                 }
                   7081:             }
                   7082:         }
                   7083:     }
1.388     www      7084:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7085:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7086:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7087:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7088:     if ($email) {
                   7089:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7090:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7091:     }
1.899     raeburn  7092:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7093:     if (defined($inststatus)) {
                   7094:         $names{'inststatus'} = '';
                   7095:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7096:         if (ref($usertypes) eq 'HASH') {
                   7097:             my @okstatuses; 
                   7098:             foreach my $item (split(/:/,$inststatus)) {
                   7099:                 if (defined($usertypes->{$item})) {
                   7100:                     push(@okstatuses,$item);  
                   7101:                 }
                   7102:             }
                   7103:             if (@okstatuses) {
                   7104:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7105:             }
                   7106:         }
                   7107:     }
1.1075    raeburn  7108:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7109:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7110:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7111:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7112:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7113:     } else {
                   7114:         $logmsg .= ' during self creation';
                   7115:     }
1.1075    raeburn  7116:     my $changed;
                   7117:     if ($newuser) {
                   7118:         $changed = 1;
                   7119:     } else {
                   7120:         foreach my $field (@fields) {
                   7121:             if ($names{$field} ne $oldnames{$field}) {
                   7122:                 $changed = 1;
                   7123:                 last;
                   7124:             }
                   7125:         }
                   7126:     }
                   7127:     unless ($changed) {
                   7128:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7129:         &logthis($logmsg);
                   7130:         return 'ok';
                   7131:     }
                   7132:     my $reply = &put('environment', \%names, $udom,$uname);
                   7133:     if ($reply ne 'ok') { 
                   7134:         return 'error: '.$reply;
                   7135:     }
1.1087    raeburn  7136:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7137:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7138:     }
1.1075    raeburn  7139:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7140:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7141:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7142:     &logthis($logmsg);
1.134     albertel 7143:     return 'ok';
1.80      www      7144: }
                   7145: 
1.81      www      7146: # -------------------------------------------------------------- Modify student
1.80      www      7147: 
1.81      www      7148: sub modifystudent {
                   7149:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7150:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7151:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7152:     if (!$cid) {
1.620     albertel 7153: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7154: 	    return 'not_in_class';
                   7155: 	}
1.80      www      7156:     }
                   7157: # --------------------------------------------------------------- Make the user
1.81      www      7158:     my $reply=&modifyuser
1.209     matthew  7159: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7160:          $desiredhome,$email,$inststatus);
1.80      www      7161:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7162:     # This will cause &modify_student_enrollment to get the uid from the
                   7163:     # students environment
                   7164:     $uid = undef if (!$forceid);
1.455     albertel 7165:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7166: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7167:     return $reply;
                   7168: }
                   7169: 
                   7170: sub modify_student_enrollment {
1.957     raeburn  7171:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7172:     my ($cdom,$cnum,$chome);
                   7173:     if (!$cid) {
1.620     albertel 7174: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7175: 	    return 'not_in_class';
                   7176: 	}
1.620     albertel 7177: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7178: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7179:     } else {
                   7180: 	($cdom,$cnum)=split(/_/,$cid);
                   7181:     }
1.620     albertel 7182:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7183:     if (!$chome) {
1.457     raeburn  7184: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7185:     }
1.455     albertel 7186:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7187:     # Make sure the user exists
1.81      www      7188:     my $uhome=&homeserver($uname,$udom);
                   7189:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7190: 	return 'error: no such user';
                   7191:     }
1.297     matthew  7192:     # Get student data if we were not given enough information
                   7193:     if (!defined($first)  || $first  eq '' || 
                   7194:         !defined($last)   || $last   eq '' || 
                   7195:         !defined($uid)    || $uid    eq '' || 
                   7196:         !defined($middle) || $middle eq '' || 
                   7197:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7198:         # They did not supply us with enough data to enroll the student, so
                   7199:         # we need to pick up more information.
1.297     matthew  7200:         my %tmp = &get('environment',
1.294     matthew  7201:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7202:                        ,$udom,$uname);
                   7203: 
1.800     albertel 7204:         #foreach my $key (keys(%tmp)) {
                   7205:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7206:         #}
1.294     matthew  7207:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7208:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7209:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7210:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7211:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7212:     }
1.556     albertel 7213:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7214:     my $reply=cput('classlist',
                   7215: 		   {"$uname:$udom" => 
1.515     raeburn  7216: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7217: 		   $cdom,$cnum);
1.81      www      7218:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7219: 	return 'error: '.$reply;
1.652     albertel 7220:     } else {
                   7221: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7222:     }
1.297     matthew  7223:     # Add student role to user
1.83      www      7224:     my $uurl='/'.$cid;
1.81      www      7225:     $uurl=~s/\_/\//g;
                   7226:     if ($usec) {
                   7227: 	$uurl.='/'.$usec;
                   7228:     }
1.957     raeburn  7229:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7230: }
                   7231: 
1.556     albertel 7232: sub format_name {
                   7233:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7234:     my $name;
                   7235:     if ($first ne 'lastname') {
                   7236: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7237:     } else {
                   7238: 	if ($lastname=~/\S/) {
                   7239: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7240: 	    $name=~s/\s+,/,/;
                   7241: 	} else {
                   7242: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7243: 	}
                   7244:     }
                   7245:     $name=~s/^\s+//;
                   7246:     $name=~s/\s+$//;
                   7247:     $name=~s/\s+/ /g;
                   7248:     return $name;
                   7249: }
                   7250: 
1.84      www      7251: # ------------------------------------------------- Write to course preferences
                   7252: 
                   7253: sub writecoursepref {
                   7254:     my ($courseid,%prefs)=@_;
                   7255:     $courseid=~s/^\///;
                   7256:     $courseid=~s/\_/\//g;
                   7257:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7258:     my $chome=homeserver($cnum,$cdomain);
                   7259:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7260: 	return 'error: no such course';
                   7261:     }
                   7262:     my $cstring='';
1.800     albertel 7263:     foreach my $pref (keys(%prefs)) {
                   7264: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7265:     }
1.84      www      7266:     $cstring=~s/\&$//;
                   7267:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7268: }
                   7269: 
                   7270: # ---------------------------------------------------------- Make/modify course
                   7271: 
                   7272: sub createcourse {
1.741     raeburn  7273:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7274:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7275:     $url=&declutter($url);
                   7276:     my $cid='';
1.1028    raeburn  7277:     if ($context eq 'requestcourses') {
                   7278:         my $can_create = 0;
                   7279:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7280:         if ($udom eq $ownerdom) {
                   7281:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7282:                                   $context)) {
                   7283:                 $can_create = 1;
                   7284:             }
                   7285:         } else {
                   7286:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7287:                                            $category);
                   7288:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7289:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7290:                 if (@curr > 0) {
                   7291:                     my @options = qw(approval validate autolimit);
                   7292:                     my $optregex = join('|',@options);
                   7293:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7294:                         $can_create = 1;
                   7295:                     }
                   7296:                 }
                   7297:             }
                   7298:         }
                   7299:         if ($can_create) {
                   7300:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7301:                 unless (&allowed('ccc',$udom)) {
                   7302:                     return 'refused'; 
                   7303:                 }
1.1017    raeburn  7304:             }
                   7305:         } else {
                   7306:             return 'refused';
                   7307:         }
1.1028    raeburn  7308:     } elsif (!&allowed('ccc',$udom)) {
                   7309:         return 'refused';
1.84      www      7310:     }
1.1011    raeburn  7311: # --------------------------------------------------------------- Get Unique ID
                   7312:     my $uname;
                   7313:     if ($cnum =~ /^$match_courseid$/) {
                   7314:         my $chome=&homeserver($cnum,$udom,'true');
                   7315:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7316:             $uname = $cnum;
                   7317:         } else {
1.1038    raeburn  7318:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7319:         }
                   7320:     } else {
1.1038    raeburn  7321:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7322:     }
                   7323:     return $uname if ($uname =~ /^error/);
                   7324: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7325:     if (!defined($course_server)) {
                   7326:         if (defined(&domain($udom,'primary'))) {
                   7327:             $course_server = &domain($udom,'primary');
                   7328:         } else {
                   7329:             $course_server = $env{'user.home'}; 
                   7330:         }
                   7331:     }
                   7332:     my %host_servers =
                   7333:         &Apache::lonnet::get_servers($udom,'library');
                   7334:     unless ($host_servers{$course_server}) {
                   7335:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7336:     }
1.84      www      7337: # ------------------------------------------------------------- Make the course
                   7338:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7339:                       $course_server);
1.84      www      7340:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7341:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7342:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7343: 	return 'error: no such course';
                   7344:     }
1.271     www      7345: # ----------------------------------------------------------------- Course made
1.516     raeburn  7346: # log existence
1.1029    raeburn  7347:     my $now = time;
1.918     raeburn  7348:     my $newcourse = {
                   7349:                     $udom.'_'.$uname => {
1.921     raeburn  7350:                                      description => $description,
                   7351:                                      inst_code   => $inst_code,
                   7352:                                      owner       => $course_owner,
                   7353:                                      type        => $crstype,
1.1029    raeburn  7354:                                      creator     => $env{'user.name'}.':'.
                   7355:                                                     $env{'user.domain'},
                   7356:                                      created     => $now,
                   7357:                                      context     => $context,
1.918     raeburn  7358:                                                 },
                   7359:                     };
1.921     raeburn  7360:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7361: # set toplevel url
1.271     www      7362:     my $topurl=$url;
                   7363:     unless ($nonstandard) {
                   7364: # ------------------------------------------ For standard courses, make top url
                   7365:         my $mapurl=&clutter($url);
1.278     www      7366:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7367:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7368: <map>
                   7369: <resource id="1" type="start"></resource>
                   7370: <resource id="2" src="$mapurl"></resource>
                   7371: <resource id="3" type="finish"></resource>
                   7372: <link index="1" from="1" to="2"></link>
                   7373: <link index="2" from="2" to="3"></link>
                   7374: </map>
                   7375: ENDINITMAP
                   7376:         $topurl=&declutter(
1.638     albertel 7377:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7378:                           );
                   7379:     }
                   7380: # ----------------------------------------------------------- Write preferences
1.84      www      7381:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7382:                      ('description'              => $description,
                   7383:                       'url'                      => $topurl,
                   7384:                       'internal.creator'         => $env{'user.name'}.':'.
                   7385:                                                     $env{'user.domain'},
                   7386:                       'internal.created'         => $now,
                   7387:                       'internal.creationcontext' => $context)
                   7388:                     );
1.84      www      7389:     return '/'.$udom.'/'.$uname;
                   7390: }
                   7391: 
1.1011    raeburn  7392: # ------------------------------------------------------------------- Create ID
                   7393: sub generate_coursenum {
1.1038    raeburn  7394:     my ($udom,$crstype) = @_;
1.1011    raeburn  7395:     my $domdesc = &domain($udom);
                   7396:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7397:     my $first;
                   7398:     if ($crstype eq 'Community') {
                   7399:         $first = '0';
                   7400:     } else {
                   7401:         $first = int(1+rand(9)); 
                   7402:     } 
                   7403:     my $uname=$first.
1.1011    raeburn  7404:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7405:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7406:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7407: # ----------------------------------------------- Make sure that does not exist
                   7408:     my $uhome=&homeserver($uname,$udom,'true');
                   7409:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7410:         if ($crstype eq 'Community') {
                   7411:             $first = '0';
                   7412:         } else {
                   7413:             $first = int(1+rand(9));
                   7414:         }
                   7415:         $uname=$first.
1.1011    raeburn  7416:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7417:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7418:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7419:         $uhome=&homeserver($uname,$udom,'true');
                   7420:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7421:             return 'error: unable to generate unique course-ID';
                   7422:         }
                   7423:     }
                   7424:     return $uname;
                   7425: }
                   7426: 
1.813     albertel 7427: sub is_course {
                   7428:     my ($cdom,$cnum) = @_;
                   7429:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7430: 				undef,'.');
1.813     albertel 7431:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7432:         return 1;
                   7433:     }
                   7434:     return 0;
                   7435: }
                   7436: 
1.1015    raeburn  7437: sub store_userdata {
                   7438:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7439:     my $result;
1.1016    raeburn  7440:     if ($datakey ne '') {
1.1013    raeburn  7441:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7442:             if ($udom eq '' || $uname eq '') {
                   7443:                 $udom = $env{'user.domain'};
                   7444:                 $uname = $env{'user.name'};
                   7445:             }
                   7446:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7447:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7448:                 $result = 'error: no_host';
                   7449:             } else {
                   7450:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7451:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7452: 
                   7453:                 my $namevalue='';
                   7454:                 foreach my $key (keys(%{$storehash})) {
                   7455:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7456:                 }
                   7457:                 $namevalue=~s/\&$//;
1.1105    raeburn  7458:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7459:                                   $namevalue,$uhome);
1.1013    raeburn  7460:             }
                   7461:         } else {
                   7462:             $result = 'error: data to store was not a hash reference'; 
                   7463:         }
                   7464:     } else {
                   7465:         $result= 'error: invalid requestkey'; 
                   7466:     }
                   7467:     return $result;
                   7468: }
                   7469: 
1.21      www      7470: # ---------------------------------------------------------- Assign Custom Role
                   7471: 
                   7472: sub assigncustomrole {
1.957     raeburn  7473:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7474:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7475:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7476: }
                   7477: 
                   7478: # ----------------------------------------------------------------- Revoke Role
                   7479: 
                   7480: sub revokerole {
1.957     raeburn  7481:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7482:     my $now=time;
1.965     raeburn  7483:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7484: }
                   7485: 
                   7486: # ---------------------------------------------------------- Revoke Custom Role
                   7487: 
                   7488: sub revokecustomrole {
1.957     raeburn  7489:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7490:     my $now=time;
1.357     www      7491:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7492:            $deleteflag,$selfenroll,$context);
1.17      www      7493: }
                   7494: 
1.533     banghart 7495: # ------------------------------------------------------------ Disk usage
1.535     albertel 7496: sub diskusage {
1.955     raeburn  7497:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7498:     $directorypath =~ s/\/$//;
                   7499:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7500:                        .&escape($getpropath).':'.&escape($uname).':'
                   7501:                        .&escape($udom),homeserver($uname,$udom));
                   7502:     if ($listing eq 'unknown_cmd') {
                   7503:         if ($getpropath) {
                   7504:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7505:         }
                   7506:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7507:     }
1.514     albertel 7508:     return $listing;
1.512     banghart 7509: }
                   7510: 
1.566     banghart 7511: sub is_locked {
1.1096    raeburn  7512:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7513:     my @check;
                   7514:     my $is_locked;
1.1093    raeburn  7515:     push (@check,$file_name);
1.613     albertel 7516:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7517: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7518:     my ($tmp)=keys(%locked);
                   7519:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7520:     
1.566     banghart 7521:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7522:         $is_locked = 'false';
                   7523:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7524:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7525:                $is_locked = 'true';
1.1096    raeburn  7526:                if (ref($which) eq 'ARRAY') {
                   7527:                    push(@{$which},$entry);
                   7528:                } else {
                   7529:                    last;
                   7530:                }
1.745     raeburn  7531:            }
                   7532:        }
1.566     banghart 7533:     } else {
                   7534:         $is_locked = 'false';
                   7535:     }
1.1093    raeburn  7536:     return $is_locked;
1.566     banghart 7537: }
                   7538: 
1.759     albertel 7539: sub declutter_portfile {
                   7540:     my ($file) = @_;
1.833     albertel 7541:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7542:     return $file;
                   7543: }
                   7544: 
1.559     banghart 7545: # ------------------------------------------------------------- Mark as Read Only
                   7546: 
                   7547: sub mark_as_readonly {
                   7548:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7549:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7550:     my ($tmp)=keys(%current_permissions);
                   7551:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7552:     foreach my $file (@{$files}) {
1.759     albertel 7553: 	$file = &declutter_portfile($file);
1.561     banghart 7554:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7555:     }
1.613     albertel 7556:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7557:     return;
                   7558: }
                   7559: 
1.572     banghart 7560: # ------------------------------------------------------------Save Selected Files
                   7561: 
                   7562: sub save_selected_files {
                   7563:     my ($user, $path, @files) = @_;
                   7564:     my $filename = $user."savedfiles";
1.573     banghart 7565:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7566:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7567:     foreach my $file (@files) {
1.620     albertel 7568:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7569:     }
                   7570:     foreach my $file (@other_files) {
1.574     banghart 7571:         print (OUT $file."\n");
1.572     banghart 7572:     }
1.574     banghart 7573:     close (OUT);
1.572     banghart 7574:     return 'ok';
                   7575: }
                   7576: 
1.574     banghart 7577: sub clear_selected_files {
                   7578:     my ($user) = @_;
                   7579:     my $filename = $user."savedfiles";
1.1117    foxr     7580:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7581:     print (OUT undef);
                   7582:     close (OUT);
                   7583:     return ("ok");    
                   7584: }
                   7585: 
1.572     banghart 7586: sub files_in_path {
                   7587:     my ($user, $path) = @_;
                   7588:     my $filename = $user."savedfiles";
                   7589:     my %return_files;
1.1117    foxr     7590:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7591:     while (my $line_in = <IN>) {
1.574     banghart 7592:         chomp ($line_in);
                   7593:         my @paths_and_file = split (m!/!, $line_in);
                   7594:         my $file_part = pop (@paths_and_file);
                   7595:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7596:         $path_part.='/';
                   7597:         my $path_and_file = $path_part.$file_part;
                   7598:         if ($path_part eq $path) {
                   7599:             $return_files{$file_part}= 'selected';
                   7600:         }
                   7601:     }
1.574     banghart 7602:     close (IN);
                   7603:     return (\%return_files);
1.572     banghart 7604: }
                   7605: 
                   7606: # called in portfolio select mode, to show files selected NOT in current directory
                   7607: sub files_not_in_path {
                   7608:     my ($user, $path) = @_;
                   7609:     my $filename = $user."savedfiles";
                   7610:     my @return_files;
                   7611:     my $path_part;
1.1117    foxr     7612:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7613:     while (my $line = <IN>) {
1.572     banghart 7614:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7615:         my @paths_and_file = split(m|/|, $line);
                   7616:         my $file_part = pop(@paths_and_file);
                   7617:         chomp($file_part);
                   7618:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7619:         $path_part .= '/';
                   7620:         my $path_and_file = $path_part.$file_part;
                   7621:         if ($path_part ne $path) {
1.800     albertel 7622:             push(@return_files, ($path_and_file));
1.572     banghart 7623:         }
                   7624:     }
1.800     albertel 7625:     close(OUT);
1.574     banghart 7626:     return (@return_files);
1.572     banghart 7627: }
                   7628: 
1.745     raeburn  7629: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7630: 
1.745     raeburn  7631: sub get_portfile_permissions {
                   7632:     my ($domain,$user) = @_;
1.613     albertel 7633:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7634:     my ($tmp)=keys(%current_permissions);
                   7635:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7636:     return \%current_permissions;
                   7637: }
                   7638: 
                   7639: #---------------------------------------------Get portfolio file access controls
                   7640: 
1.749     raeburn  7641: sub get_access_controls {
1.745     raeburn  7642:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7643:     my %access;
                   7644:     my $real_file = $file;
                   7645:     $file =~ s/\.meta$//;
1.745     raeburn  7646:     if (defined($file)) {
1.749     raeburn  7647:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7648:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7649:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7650:             }
                   7651:         }
1.745     raeburn  7652:     } else {
1.749     raeburn  7653:         foreach my $key (keys(%{$current_permissions})) {
                   7654:             if ($key =~ /\0accesscontrol$/) {
                   7655:                 if (defined($group)) {
                   7656:                     if ($key !~ m-^\Q$group\E/-) {
                   7657:                         next;
                   7658:                     }
                   7659:                 }
                   7660:                 my ($fullpath) = split(/\0/,$key);
                   7661:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7662:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7663:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7664:                     }
                   7665:                 }
                   7666:             }
                   7667:         }
                   7668:     }
                   7669:     return %access;
                   7670: }
                   7671: 
                   7672: sub modify_access_controls {
                   7673:     my ($file_name,$changes,$domain,$user)=@_;
                   7674:     my ($outcome,$deloutcome);
                   7675:     my %store_permissions;
                   7676:     my %new_values;
                   7677:     my %new_control;
                   7678:     my %translation;
                   7679:     my @deletions = ();
                   7680:     my $now = time;
                   7681:     if (exists($$changes{'activate'})) {
                   7682:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7683:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7684:             my $numnew = scalar(@newitems);
                   7685:             for (my $i=0; $i<$numnew; $i++) {
                   7686:                 my $newkey = $newitems[$i];
                   7687:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7688:                 if ($newkey =~ /^\d+:/) { 
                   7689:                     $newkey =~ s/^(\d+)/$newid/;
                   7690:                     $translation{$1} = $newid;
                   7691:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7692:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7693:                     $translation{$1} = $newid;
                   7694:                 }
1.749     raeburn  7695:                 $new_values{$file_name."\0".$newkey} = 
                   7696:                                           $$changes{'activate'}{$newitems[$i]};
                   7697:                 $new_control{$newkey} = $now;
                   7698:             }
                   7699:         }
                   7700:     }
                   7701:     my %todelete;
                   7702:     my %changed_items;
                   7703:     foreach my $action ('delete','update') {
                   7704:         if (exists($$changes{$action})) {
                   7705:             if (ref($$changes{$action}) eq 'HASH') {
                   7706:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7707:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7708:                     if ($action eq 'delete') { 
                   7709:                         $todelete{$itemnum} = 1;
                   7710:                     } else {
                   7711:                         $changed_items{$itemnum} = $key;
                   7712:                     }
                   7713:                 }
1.745     raeburn  7714:             }
                   7715:         }
1.749     raeburn  7716:     }
                   7717:     # get lock on access controls for file.
                   7718:     my $lockhash = {
                   7719:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7720:                                                        ':'.$env{'user.domain'},
                   7721:                    }; 
                   7722:     my $tries = 0;
                   7723:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7724:    
                   7725:     while (($gotlock ne 'ok') && $tries <3) {
                   7726:         $tries ++;
                   7727:         sleep 1;
                   7728:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7729:     }
                   7730:     if ($gotlock eq 'ok') {
                   7731:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7732:         my ($tmp)=keys(%curr_permissions);
                   7733:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7734:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7735:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7736:             if (ref($curr_controls) eq 'HASH') {
                   7737:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7738:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7739:                     if (defined($todelete{$itemnum})) {
                   7740:                         push(@deletions,$file_name."\0".$control_item);
                   7741:                     } else {
                   7742:                         if (defined($changed_items{$itemnum})) {
                   7743:                             $new_control{$changed_items{$itemnum}} = $now;
                   7744:                             push(@deletions,$file_name."\0".$control_item);
                   7745:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7746:                         } else {
                   7747:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7748:                         }
                   7749:                     }
1.745     raeburn  7750:                 }
                   7751:             }
                   7752:         }
1.970     raeburn  7753:         my ($group);
                   7754:         if (&is_course($domain,$user)) {
                   7755:             ($group,my $file) = split(/\//,$file_name,2);
                   7756:         }
1.749     raeburn  7757:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7758:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7759:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7760:         #  remove lock
                   7761:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7762:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7763:         my $sqlresult =
1.970     raeburn  7764:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7765:                                     $group);
1.749     raeburn  7766:     } else {
                   7767:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7768:     }
1.749     raeburn  7769:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7770: }
                   7771: 
1.827     raeburn  7772: sub make_public_indefinitely {
                   7773:     my ($requrl) = @_;
                   7774:     my $now = time;
                   7775:     my $action = 'activate';
                   7776:     my $aclnum = 0;
                   7777:     if (&is_portfolio_url($requrl)) {
                   7778:         my (undef,$udom,$unum,$file_name,$group) =
                   7779:             &parse_portfolio_url($requrl);
                   7780:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7781:         my %access_controls = &get_access_controls($current_perms,
                   7782:                                                    $group,$file_name);
                   7783:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7784:             my ($num,$scope,$end,$start) = 
                   7785:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7786:             if ($scope eq 'public') {
                   7787:                 if ($start <= $now && $end == 0) {
                   7788:                     $action = 'none';
                   7789:                 } else {
                   7790:                     $action = 'update';
                   7791:                     $aclnum = $num;
                   7792:                 }
                   7793:                 last;
                   7794:             }
                   7795:         }
                   7796:         if ($action eq 'none') {
                   7797:              return 'ok';
                   7798:         } else {
                   7799:             my %changes;
                   7800:             my $newend = 0;
                   7801:             my $newstart = $now;
                   7802:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7803:             $changes{$action}{$newkey} = {
                   7804:                 type => 'public',
                   7805:                 time => {
                   7806:                     start => $newstart,
                   7807:                     end   => $newend,
                   7808:                 },
                   7809:             };
                   7810:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7811:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7812:             return $outcome;
                   7813:         }
                   7814:     } else {
                   7815:         return 'invalid';
                   7816:     }
                   7817: }
                   7818: 
1.745     raeburn  7819: #------------------------------------------------------Get Marked as Read Only
                   7820: 
                   7821: sub get_marked_as_readonly {
                   7822:     my ($domain,$user,$what,$group) = @_;
                   7823:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7824:     my @readonly_files;
1.629     banghart 7825:     my $cmp1=$what;
                   7826:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7827:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7828:         if (defined($group)) {
                   7829:             if ($file_name !~ m-^\Q$group\E/-) {
                   7830:                 next;
                   7831:             }
                   7832:         }
1.561     banghart 7833:         if (ref($value) eq "ARRAY"){
                   7834:             foreach my $stored_what (@{$value}) {
1.629     banghart 7835:                 my $cmp2=$stored_what;
1.759     albertel 7836:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7837:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7838:                 }
1.629     banghart 7839:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7840:                     push(@readonly_files, $file_name);
1.745     raeburn  7841:                     last;
1.563     banghart 7842:                 } elsif (!defined($what)) {
                   7843:                     push(@readonly_files, $file_name);
1.745     raeburn  7844:                     last;
1.561     banghart 7845:                 }
                   7846:             }
1.745     raeburn  7847:         }
1.561     banghart 7848:     }
                   7849:     return @readonly_files;
                   7850: }
1.577     banghart 7851: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7852: 
1.577     banghart 7853: sub get_marked_as_readonly_hash {
1.745     raeburn  7854:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7855:     my %readonly_files;
1.745     raeburn  7856:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7857:         if (defined($group)) {
                   7858:             if ($file_name !~ m-^\Q$group\E/-) {
                   7859:                 next;
                   7860:             }
                   7861:         }
1.577     banghart 7862:         if (ref($value) eq "ARRAY"){
                   7863:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7864:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7865:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7866:                         if ($lock_descriptor eq 'graded') {
                   7867:                             $readonly_files{$file_name} = 'graded';
                   7868:                         } elsif ($lock_descriptor eq 'handback') {
                   7869:                             $readonly_files{$file_name} = 'handback';
                   7870:                         } else {
                   7871:                             if (!exists($readonly_files{$file_name})) {
                   7872:                                 $readonly_files{$file_name} = 'locked';
                   7873:                             }
                   7874:                         }
1.745     raeburn  7875:                     }
1.750     banghart 7876:                 } 
1.577     banghart 7877:             }
                   7878:         } 
                   7879:     }
                   7880:     return %readonly_files;
                   7881: }
1.559     banghart 7882: # ------------------------------------------------------------ Unmark as Read Only
                   7883: 
                   7884: sub unmark_as_readonly {
1.629     banghart 7885:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7886:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7887:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7888:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7889:     my $symb_crs = $what;
                   7890:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7891:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7892:     my ($tmp)=keys(%current_permissions);
                   7893:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7894:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7895:     foreach my $file (@readonly_files) {
1.759     albertel 7896: 	my $clean_file = &declutter_portfile($file);
                   7897: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7898: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7899:         my @new_locks;
                   7900:         my @del_keys;
                   7901:         if (ref($current_locks) eq "ARRAY"){
                   7902:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7903:                 my $compare=$locker;
1.749     raeburn  7904:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7905:                     $compare=join('',@{$locker});
1.746     raeburn  7906:                     if ($compare ne $symb_crs) {
                   7907:                         push(@new_locks, $locker);
                   7908:                     }
1.563     banghart 7909:                 }
                   7910:             }
1.650     albertel 7911:             if (scalar(@new_locks) > 0) {
1.563     banghart 7912:                 $current_permissions{$file} = \@new_locks;
                   7913:             } else {
                   7914:                 push(@del_keys, $file);
1.613     albertel 7915:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7916:                 delete($current_permissions{$file});
1.563     banghart 7917:             }
                   7918:         }
1.561     banghart 7919:     }
1.613     albertel 7920:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7921:     return;
                   7922: }
1.512     banghart 7923: 
1.17      www      7924: # ------------------------------------------------------------ Directory lister
                   7925: 
                   7926: sub dirlist {
1.955     raeburn  7927:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7928:     $uri=~s/^\///;
                   7929:     $uri=~s/\/$//;
1.253     stredwic 7930:     my ($udom, $uname);
1.955     raeburn  7931:     if ($getuserdir) {
1.253     stredwic 7932:         $udom = $userdomain;
                   7933:         $uname = $username;
1.955     raeburn  7934:     } else {
                   7935:         (undef,$udom,$uname)=split(/\//,$uri);
                   7936:         if(defined($userdomain)) {
                   7937:             $udom = $userdomain;
                   7938:         }
                   7939:         if(defined($username)) {
                   7940:             $uname = $username;
                   7941:         }
1.253     stredwic 7942:     }
1.955     raeburn  7943:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7944: 
1.955     raeburn  7945:     $dirRoot = $perlvar{'lonDocRoot'};
                   7946:     if (defined($getpropath)) {
                   7947:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7948:         $dirRoot =~ s/\/$//;
1.955     raeburn  7949:     } elsif (defined($getuserdir)) {
                   7950:         my $subdir=$uname.'__';
                   7951:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7952:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7953:                    ."/$udom/$subdir/$uname";
                   7954:     } elsif (defined($alternateRoot)) {
                   7955:         $dirRoot = $alternateRoot;
1.751     banghart 7956:     }
1.253     stredwic 7957: 
                   7958:     if($udom) {
                   7959:         if($uname) {
1.955     raeburn  7960:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7961:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7962:                               .':'.&escape($uname).':'.&escape($udom),
                   7963:                               &homeserver($uname,$udom));
                   7964:             if ($listing eq 'unknown_cmd') {
                   7965:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7966:                                   &homeserver($uname,$udom));
                   7967:             } else {
                   7968:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7969:             }
1.605     matthew  7970:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7971:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7972: 				  &homeserver($uname,$udom));
1.605     matthew  7973:                 @listing_results = split(/:/,$listing);
                   7974:             } else {
                   7975:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7976:             }
                   7977:             return @listing_results;
1.955     raeburn  7978:         } elsif(!$alternateRoot) {
1.800     albertel 7979:             my %allusers;
1.841     albertel 7980: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7981:  	    foreach my $tryserver (keys(%servers)) {
                   7982:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7983:                                   &escape($udom),$tryserver);
                   7984:                 if ($listing eq 'unknown_cmd') {
                   7985: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7986: 				      $udom, $tryserver);
                   7987:                 } else {
                   7988:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7989:                 }
1.841     albertel 7990: 		if ($listing eq 'unknown_cmd') {
                   7991: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7992: 				      $udom, $tryserver);
                   7993: 		    @listing_results = split(/:/,$listing);
                   7994: 		} else {
                   7995: 		    @listing_results =
                   7996: 			map { &unescape($_); } split(/:/,$listing);
                   7997: 		}
                   7998: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7999: 		    $listing_results[0] ne 'empty'       &&
                   8000: 		    $listing_results[0] ne 'con_lost') {
                   8001: 		    foreach my $line (@listing_results) {
                   8002: 			my ($entry) = split(/&/,$line,2);
                   8003: 			$allusers{$entry} = 1;
                   8004: 		    }
                   8005: 		}
1.253     stredwic 8006:             }
                   8007:             my $alluserstr='';
1.800     albertel 8008:             foreach my $user (sort(keys(%allusers))) {
                   8009:                 $alluserstr.=$user.'&user:';
1.253     stredwic 8010:             }
                   8011:             $alluserstr=~s/:$//;
                   8012:             return split(/:/,$alluserstr);
                   8013:         } else {
1.800     albertel 8014:             return ('missing user name');
1.253     stredwic 8015:         }
1.955     raeburn  8016:     } elsif(!defined($getpropath)) {
1.841     albertel 8017:         my @all_domains = sort(&all_domains());
1.955     raeburn  8018:         foreach my $domain (@all_domains) {
                   8019:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   8020:         }
                   8021:         return @all_domains;
                   8022:     } else {
1.800     albertel 8023:         return ('missing domain');
1.275     stredwic 8024:     }
                   8025: }
                   8026: 
                   8027: # --------------------------------------------- GetFileTimestamp
                   8028: # This function utilizes dirlist and returns the date stamp for
                   8029: # when it was last modified.  It will also return an error of -1
                   8030: # if an error occurs
                   8031: 
                   8032: sub GetFileTimestamp {
1.955     raeburn  8033:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8034:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8035:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  8036:     my ($fileStat) = 
                   8037:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   8038:                                  undef,$getuserdir);
1.275     stredwic 8039:     my @stats = split('&', $fileStat);
                   8040:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  8041:         # @stats contains first the filename, then the stat output
                   8042:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8043:     } else {
                   8044:         return -1;
1.253     stredwic 8045:     }
1.26      www      8046: }
                   8047: 
1.712     albertel 8048: sub stat_file {
                   8049:     my ($uri) = @_;
1.787     albertel 8050:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8051: 
1.955     raeburn  8052:     my ($udom,$uname,$file);
1.712     albertel 8053:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8054: 	($udom,$uname,$file) =
1.811     albertel 8055: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8056: 	$file = 'userfiles/'.$file;
                   8057:     }
                   8058:     if ($uri =~ m-^/res/-) {
                   8059: 	($udom,$uname) = 
1.807     albertel 8060: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8061: 	$file = $uri;
                   8062:     }
                   8063: 
                   8064:     if (!$udom || !$uname || !$file) {
                   8065: 	# unable to handle the uri
                   8066: 	return ();
                   8067:     }
1.956     raeburn  8068:     my $getpropath;
                   8069:     if ($file =~ /^userfiles\//) {
                   8070:         $getpropath = 1;
                   8071:     }
1.955     raeburn  8072:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8073:     my @stats = split('&', $result);
1.721     banghart 8074:     
1.712     albertel 8075:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8076: 	shift(@stats); #filename is first
                   8077: 	return @stats;
                   8078:     }
                   8079:     return ();
                   8080: }
                   8081: 
1.26      www      8082: # -------------------------------------------------------- Value of a Condition
                   8083: 
1.713     albertel 8084: # gets the value of a specific preevaluated condition
                   8085: #    stored in the string  $env{user.state.<cid>}
                   8086: # or looks up a condition reference in the bighash and if if hasn't
                   8087: # already been evaluated recurses into docondval to get the value of
                   8088: # the condition, then memoizing it to 
                   8089: #   $env{user.state.<cid>.<condition>}
1.40      www      8090: sub directcondval {
                   8091:     my $number=shift;
1.620     albertel 8092:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8093: 	&Apache::lonuserstate::evalstate();
                   8094:     }
1.713     albertel 8095:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8096: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8097:     } elsif ($number =~ /^_/) {
                   8098: 	my $sub_condition;
                   8099: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8100: 		&GDBM_READER(),0640)) {
                   8101: 	    $sub_condition=$bighash{'conditions'.$number};
                   8102: 	    untie(%bighash);
                   8103: 	}
                   8104: 	my $value = &docondval($sub_condition);
1.949     raeburn  8105: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8106: 	return $value;
                   8107:     }
1.620     albertel 8108:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8109:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8110:     } else {
                   8111:        return 2;
                   8112:     }
                   8113: }
                   8114: 
1.713     albertel 8115: # get the collection of conditions for this resource
1.26      www      8116: sub condval {
                   8117:     my $condidx=shift;
1.54      www      8118:     my $allpathcond='';
1.713     albertel 8119:     foreach my $cond (split(/\|/,$condidx)) {
                   8120: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8121: 	    $allpathcond.=
                   8122: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8123: 	}
1.191     harris41 8124:     }
1.54      www      8125:     $allpathcond=~s/\|$//;
1.713     albertel 8126:     return &docondval($allpathcond);
                   8127: }
                   8128: 
                   8129: #evaluates an expression of conditions
                   8130: sub docondval {
                   8131:     my ($allpathcond) = @_;
                   8132:     my $result=0;
                   8133:     if ($env{'request.course.id'}
                   8134: 	&& defined($allpathcond)) {
                   8135: 	my $operand='|';
                   8136: 	my @stack;
                   8137: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8138: 	    if ($chunk eq '(') {
                   8139: 		push @stack,($operand,$result);
                   8140: 	    } elsif ($chunk eq ')') {
                   8141: 		my $before=pop @stack;
                   8142: 		if (pop @stack eq '&') {
                   8143: 		    $result=$result>$before?$before:$result;
                   8144: 		} else {
                   8145: 		    $result=$result>$before?$result:$before;
                   8146: 		}
                   8147: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8148: 		$operand=$chunk;
                   8149: 	    } else {
                   8150: 		my $new=directcondval($chunk);
                   8151: 		if ($operand eq '&') {
                   8152: 		    $result=$result>$new?$new:$result;
                   8153: 		} else {
                   8154: 		    $result=$result>$new?$result:$new;
                   8155: 		}
                   8156: 	    }
                   8157: 	}
1.26      www      8158:     }
                   8159:     return $result;
1.421     albertel 8160: }
                   8161: 
                   8162: # ---------------------------------------------------- Devalidate courseresdata
                   8163: 
                   8164: sub devalidatecourseresdata {
                   8165:     my ($coursenum,$coursedomain)=@_;
                   8166:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8167:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8168: }
                   8169: 
1.763     www      8170: 
1.200     www      8171: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8172: #
                   8173: #  Parameters:
                   8174: #      $coursenum    - Number of the course.
                   8175: #      $coursedomain - Domain at which the course was created.
                   8176: #  Returns:
                   8177: #     A hash of the course parameters along (I think) with timestamps
                   8178: #     and version info.
1.877     foxr     8179: 
1.624     albertel 8180: sub get_courseresdata {
                   8181:     my ($coursenum,$coursedomain)=@_;
1.200     www      8182:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8183:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8184:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8185:     my %dumpreply;
1.417     albertel 8186:     unless (defined($cached)) {
1.624     albertel 8187: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8188: 	$result=\%dumpreply;
1.251     albertel 8189: 	my ($tmp) = keys(%dumpreply);
                   8190: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8191: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8192: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8193: 	    return $tmp;
1.416     albertel 8194: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8195: 	    $result=undef;
1.599     albertel 8196: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8197: 	}
                   8198:     }
1.624     albertel 8199:     return $result;
                   8200: }
                   8201: 
1.633     albertel 8202: sub devalidateuserresdata {
                   8203:     my ($uname,$udom)=@_;
                   8204:     my $hashid="$udom:$uname";
                   8205:     &devalidate_cache_new('userres',$hashid);
                   8206: }
                   8207: 
1.624     albertel 8208: sub get_userresdata {
                   8209:     my ($uname,$udom)=@_;
                   8210:     #most student don\'t have any data set, check if there is some data
                   8211:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8212: 
                   8213:     my $hashid="$udom:$uname";
                   8214:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8215:     if (!defined($cached)) {
                   8216: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8217: 	$result=\%resourcedata;
                   8218: 	&do_cache_new('userres',$hashid,$result,600);
                   8219:     }
                   8220:     my ($tmp)=keys(%$result);
                   8221:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8222: 	return $result;
                   8223:     }
                   8224:     #error 2 occurs when the .db doesn't exist
                   8225:     if ($tmp!~/error: 2 /) {
1.672     albertel 8226: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8227: 		 " Trying to get resource data for ".
                   8228: 		 $uname." at ".$udom.": ".
                   8229: 		 $tmp."</font>");
                   8230:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8231: 	#&EXT_cache_set($udom,$uname);
                   8232: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8233: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8234:     }
                   8235:     return $tmp;
                   8236: }
1.879     foxr     8237: #----------------------------------------------- resdata - return resource data
                   8238: #  Purpose:
                   8239: #    Return resource data for either users or for a course.
                   8240: #  Parameters:
                   8241: #     $name      - Course/user name.
                   8242: #     $domain    - Name of the domain the user/course is registered on.
                   8243: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8244: #     @which     - Array of names of resources desired.
                   8245: #  Returns:
                   8246: #     The value of the first reasource in @which that is found in the
                   8247: #     resource hash.
                   8248: #  Exceptional Conditions:
                   8249: #     If the $type passed in is not valid (not the string 'course' or 
                   8250: #     'user', an undefined  reference is returned.
                   8251: #     If none of the resources are found, an undef is returned
1.624     albertel 8252: sub resdata {
                   8253:     my ($name,$domain,$type,@which)=@_;
                   8254:     my $result;
                   8255:     if ($type eq 'course') {
                   8256: 	$result=&get_courseresdata($name,$domain);
                   8257:     } elsif ($type eq 'user') {
                   8258: 	$result=&get_userresdata($name,$domain);
                   8259:     }
                   8260:     if (!ref($result)) { return $result; }    
1.251     albertel 8261:     foreach my $item (@which) {
1.927     albertel 8262: 	if (defined($result->{$item->[0]})) {
                   8263: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8264: 	}
1.250     albertel 8265:     }
1.291     albertel 8266:     return undef;
1.200     www      8267: }
                   8268: 
1.379     matthew  8269: #
                   8270: # EXT resource caching routines
                   8271: #
                   8272: 
                   8273: sub clear_EXT_cache_status {
1.383     albertel 8274:     &delenv('cache.EXT.');
1.379     matthew  8275: }
                   8276: 
                   8277: sub EXT_cache_status {
                   8278:     my ($target_domain,$target_user) = @_;
1.383     albertel 8279:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8280:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8281:         # We know already the user has no data
                   8282:         return 1;
                   8283:     } else {
                   8284:         return 0;
                   8285:     }
                   8286: }
                   8287: 
                   8288: sub EXT_cache_set {
                   8289:     my ($target_domain,$target_user) = @_;
1.383     albertel 8290:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8291:     #&appenv({$cachename => time});
1.379     matthew  8292: }
                   8293: 
1.28      www      8294: # --------------------------------------------------------- Value of a Variable
1.58      www      8295: sub EXT {
1.715     albertel 8296: 
1.395     albertel 8297:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8298:     unless ($varname) { return ''; }
1.218     albertel 8299:     #get real user name/domain, courseid and symb
                   8300:     my $courseid;
1.359     albertel 8301:     my $publicuser;
1.427     www      8302:     if ($symbparm) {
                   8303: 	$symbparm=&get_symb_from_alias($symbparm);
                   8304:     }
1.218     albertel 8305:     if (!($uname && $udom)) {
1.790     albertel 8306:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8307:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8308:     } else {
1.620     albertel 8309: 	$courseid=$env{'request.course.id'};
1.218     albertel 8310:     }
1.48      www      8311:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8312:     my $rest;
1.320     albertel 8313:     if (defined($therest[0])) {
1.48      www      8314:        $rest=join('.',@therest);
                   8315:     } else {
                   8316:        $rest='';
                   8317:     }
1.320     albertel 8318: 
1.57      www      8319:     my $qualifierrest=$qualifier;
                   8320:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8321:     my $spacequalifierrest=$space;
                   8322:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8323:     if ($realm eq 'user') {
1.48      www      8324: # --------------------------------------------------------------- user.resource
                   8325: 	if ($space eq 'resource') {
1.651     albertel 8326: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8327: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8328: 		 &&
1.744     albertel 8329: 		 ($symbparm eq &symbread()) ) {	
                   8330: 		# if we are in the middle of processing the resource the
                   8331: 		# get the value we are planning on committing
                   8332:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8333:                     return $Apache::lonhomework::results{$qualifierrest};
                   8334:                 } else {
                   8335:                     return $Apache::lonhomework::history{$qualifierrest};
                   8336:                 }
1.335     albertel 8337: 	    } else {
1.359     albertel 8338: 		my %restored;
1.620     albertel 8339: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8340: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8341: 		} else {
                   8342: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8343: 		}
1.335     albertel 8344: 		return $restored{$qualifierrest};
                   8345: 	    }
1.48      www      8346: # ----------------------------------------------------------------- user.access
                   8347:         } elsif ($space eq 'access') {
1.218     albertel 8348: 	    # FIXME - not supporting calls for a specific user
1.48      www      8349:             return &allowed($qualifier,$rest);
                   8350: # ------------------------------------------ user.preferences, user.environment
                   8351:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8352: 	    if (($uname eq $env{'user.name'}) &&
                   8353: 		($udom eq $env{'user.domain'})) {
                   8354: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8355: 	    } else {
1.359     albertel 8356: 		my %returnhash;
                   8357: 		if (!$publicuser) {
                   8358: 		    %returnhash=&userenvironment($udom,$uname,
                   8359: 						 $qualifierrest);
                   8360: 		}
1.218     albertel 8361: 		return $returnhash{$qualifierrest};
                   8362: 	    }
1.48      www      8363: # ----------------------------------------------------------------- user.course
                   8364:         } elsif ($space eq 'course') {
1.218     albertel 8365: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8366:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8367: # ------------------------------------------------------------------- user.role
                   8368:         } elsif ($space eq 'role') {
1.218     albertel 8369: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8370:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8371:             if ($qualifier eq 'value') {
                   8372: 		return $role;
                   8373:             } elsif ($qualifier eq 'extent') {
                   8374:                 return $where;
                   8375:             }
                   8376: # ----------------------------------------------------------------- user.domain
                   8377:         } elsif ($space eq 'domain') {
1.218     albertel 8378:             return $udom;
1.48      www      8379: # ------------------------------------------------------------------- user.name
                   8380:         } elsif ($space eq 'name') {
1.218     albertel 8381:             return $uname;
1.48      www      8382: # ---------------------------------------------------- Any other user namespace
1.29      www      8383:         } else {
1.359     albertel 8384: 	    my %reply;
                   8385: 	    if (!$publicuser) {
                   8386: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8387: 	    }
                   8388: 	    return $reply{$qualifierrest};
1.48      www      8389:         }
1.236     www      8390:     } elsif ($realm eq 'query') {
                   8391: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8392:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8393: 						[$spacequalifierrest]);
1.620     albertel 8394: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8395:    } elsif ($realm eq 'request') {
1.48      www      8396: # ------------------------------------------------------------- request.browser
                   8397:         if ($space eq 'browser') {
1.430     www      8398: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8399: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8400: 		    return 1;
                   8401: 		} else {
                   8402: 		    return 0;
                   8403: 		}
                   8404: 	    } else {
1.620     albertel 8405: 		return $env{'browser.'.$qualifier};
1.430     www      8406: 	    }
1.57      www      8407: # ------------------------------------------------------------ request.filename
                   8408:         } else {
1.620     albertel 8409:             return $env{'request.'.$spacequalifierrest};
1.29      www      8410:         }
1.28      www      8411:     } elsif ($realm eq 'course') {
1.48      www      8412: # ---------------------------------------------------------- course.description
1.620     albertel 8413:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8414:     } elsif ($realm eq 'resource') {
1.165     www      8415: 
1.620     albertel 8416: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8417: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8418: 	}
1.693     albertel 8419: 
                   8420: 	if ($space eq 'title') {
                   8421: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8422: 	    return &gettitle($symbparm);
                   8423: 	}
                   8424: 	
                   8425: 	if ($space eq 'map') {
                   8426: 	    my ($map) = &decode_symb($symbparm);
                   8427: 	    return &symbread($map);
                   8428: 	}
1.905     albertel 8429: 	if ($space eq 'filename') {
                   8430: 	    if ($symbparm) {
                   8431: 		return &clutter((&decode_symb($symbparm))[2]);
                   8432: 	    }
                   8433: 	    return &hreflocation('',$env{'request.filename'});
                   8434: 	}
1.693     albertel 8435: 
                   8436: 	my ($section, $group, @groups);
1.593     albertel 8437: 	my ($courselevelm,$courselevel);
1.539     albertel 8438: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8439: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8440: 
1.218     albertel 8441: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8442: 
1.60      www      8443: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8444: 	    my $symbp=$symbparm;
1.735     albertel 8445: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8446: 
                   8447: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8448: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8449: 
1.620     albertel 8450: 	    if (($env{'user.name'} eq $uname) &&
                   8451: 		($env{'user.domain'} eq $udom)) {
                   8452: 		$section=$env{'request.course.sec'};
1.733     raeburn  8453:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8454:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8455: 	    } else {
1.539     albertel 8456: 		if (! defined($usection)) {
1.551     albertel 8457: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8458: 		} else {
                   8459: 		    $section = $usection;
                   8460: 		}
1.733     raeburn  8461:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8462: 	    }
                   8463: 
                   8464: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8465: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8466: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8467: 
1.593     albertel 8468: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8469: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8470: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8471: 
1.60      www      8472: # ----------------------------------------------------------- first, check user
1.624     albertel 8473: 
                   8474: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8475: 				       ([$courselevelr,'resource'],
                   8476: 					[$courselevelm,'map'     ],
                   8477: 					[$courselevel, 'course'  ]));
1.931     albertel 8478: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8479: 
1.594     albertel 8480: # ------------------------------------------------ second, check some of course
1.684     raeburn  8481:             my $coursereply;
1.691     raeburn  8482:             if (@groups > 0) {
                   8483:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8484:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8485:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8486:             }
1.96      www      8487: 
1.684     raeburn  8488: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8489: 				  $env{'course.'.$courseid.'.domain'},
                   8490: 				  'course',
                   8491: 				  ([$seclevelr,   'resource'],
                   8492: 				   [$seclevelm,   'map'     ],
                   8493: 				   [$seclevel,    'course'  ],
                   8494: 				   [$courselevelr,'resource']));
                   8495: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8496: 
1.60      www      8497: # ------------------------------------------------------ third, check map parms
1.218     albertel 8498: 	    my %parmhash=();
                   8499: 	    my $thisparm='';
                   8500: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8501: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8502: 		    &GDBM_READER(),0640)) {
1.218     albertel 8503: 		$thisparm=$parmhash{$symbparm};
                   8504: 		untie(%parmhash);
                   8505: 	    }
1.927     albertel 8506: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8507: 	}
1.594     albertel 8508: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8509: 
1.218     albertel 8510: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8511: 	my $filename;
                   8512: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8513: 	if ($symbparm) {
1.409     www      8514: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8515: 	} else {
1.620     albertel 8516: 	    $filename=$env{'request.filename'};
1.282     albertel 8517: 	}
                   8518: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8519: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8520: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8521: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8522: 
1.927     albertel 8523: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8524: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8525: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8526: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8527: 				     $env{'course.'.$courseid.'.domain'},
                   8528: 				     'course',
1.927     albertel 8529: 				     ([$courselevelm,'map'   ],
                   8530: 				      [$courselevel, 'course']));
                   8531: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8532: 	}
1.145     www      8533: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8534: 	unless ($space eq '0') {
1.336     albertel 8535: 	    my @parts=split(/_/,$space);
                   8536: 	    my $id=pop(@parts);
                   8537: 	    my $part=join('_',@parts);
                   8538: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8539: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8540: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8541: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8542: 	}
1.395     albertel 8543: 	if ($recurse) { return undef; }
                   8544: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8545: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8546: # ---------------------------------------------------- Any other user namespace
                   8547:     } elsif ($realm eq 'environment') {
                   8548: # ----------------------------------------------------------------- environment
1.620     albertel 8549: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8550: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8551: 	} else {
1.770     albertel 8552: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8553: 		return '';
                   8554: 	    }
1.219     albertel 8555: 	    my %returnhash=&userenvironment($udom,$uname,
                   8556: 					    $spacequalifierrest);
                   8557: 	    return $returnhash{$spacequalifierrest};
                   8558: 	}
1.28      www      8559:     } elsif ($realm eq 'system') {
1.48      www      8560: # ----------------------------------------------------------------- system.time
                   8561: 	if ($space eq 'time') {
                   8562: 	    return time;
                   8563:         }
1.696     albertel 8564:     } elsif ($realm eq 'server') {
                   8565: # ----------------------------------------------------------------- system.time
                   8566: 	if ($space eq 'name') {
                   8567: 	    return $ENV{'SERVER_NAME'};
                   8568:         }
1.28      www      8569:     }
1.48      www      8570:     return '';
1.61      www      8571: }
                   8572: 
1.927     albertel 8573: sub get_reply {
                   8574:     my ($reply_value) = @_;
1.940     raeburn  8575:     if (ref($reply_value) eq 'ARRAY') {
                   8576:         if (wantarray) {
                   8577: 	    return @$reply_value;
                   8578:         }
                   8579:         return $reply_value->[0];
                   8580:     } else {
                   8581:         return $reply_value;
1.927     albertel 8582:     }
                   8583: }
                   8584: 
1.691     raeburn  8585: sub check_group_parms {
                   8586:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8587:     my @groupitems = ();
                   8588:     my $resultitem;
1.927     albertel 8589:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8590:     foreach my $group (@{$groups}) {
                   8591:         foreach my $level (@levels) {
1.927     albertel 8592:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8593:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8594:         }
                   8595:     }
                   8596:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8597:                             $env{'course.'.$courseid.'.domain'},
                   8598:                                      'course',@groupitems);
                   8599:     return $coursereply;
                   8600: }
                   8601: 
                   8602: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8603:     my ($courseid,@groups) = @_;
                   8604:     @groups = sort(@groups);
1.691     raeburn  8605:     return @groups;
                   8606: }
                   8607: 
1.395     albertel 8608: sub packages_tab_default {
                   8609:     my ($uri,$varname)=@_;
                   8610:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8611: 
                   8612:     my (@extension,@specifics,$do_default);
                   8613:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8614: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8615: 	if ($pack_type eq 'default') {
                   8616: 	    $do_default=1;
                   8617: 	} elsif ($pack_type eq 'extension') {
                   8618: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8619: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8620: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8621: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8622: 	}
                   8623:     }
                   8624:     # first look for a package that matches the requested part id
                   8625:     foreach my $package (@specifics) {
                   8626: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8627: 	next if ($pack_part ne $part);
                   8628: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8629: 	    return $packagetab{"$pack_type&$name&default"};
                   8630: 	}
                   8631:     }
                   8632:     # look for any possible matching non extension_ package
                   8633:     foreach my $package (@specifics) {
                   8634: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8635: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8636: 	    return $packagetab{"$pack_type&$name&default"};
                   8637: 	}
1.585     albertel 8638: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8639: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8640: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8641: 	}
                   8642:     }
1.738     albertel 8643:     # look for any posible extension_ match
                   8644:     foreach my $package (@extension) {
                   8645: 	my ($package,$pack_type)=@{$package};
                   8646: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8647: 	    return $packagetab{"$pack_type&$name&default"};
                   8648: 	}
                   8649: 	if (defined($packagetab{$package."&$name&default"})) {
                   8650: 	    return $packagetab{$package."&$name&default"};
                   8651: 	}
                   8652:     }
                   8653:     # look for a global default setting
                   8654:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8655: 	return $packagetab{"default&$name&default"};
                   8656:     }
1.395     albertel 8657:     return undef;
                   8658: }
                   8659: 
1.334     albertel 8660: sub add_prefix_and_part {
                   8661:     my ($prefix,$part)=@_;
                   8662:     my $keyroot;
                   8663:     if (defined($prefix) && $prefix !~ /^__/) {
                   8664: 	# prefix that has a part already
                   8665: 	$keyroot=$prefix;
                   8666:     } elsif (defined($prefix)) {
                   8667: 	# prefix that is missing a part
                   8668: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8669:     } else {
                   8670: 	# no prefix at all
                   8671: 	if (defined($part)) { $keyroot='_'.$part; }
                   8672:     }
                   8673:     return $keyroot;
                   8674: }
                   8675: 
1.71      www      8676: # ---------------------------------------------------------------- Get metadata
                   8677: 
1.599     albertel 8678: my %metaentry;
1.1070    www      8679: my %importedpartids;
1.71      www      8680: sub metadata {
1.176     www      8681:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8682:     $uri=&declutter($uri);
1.288     albertel 8683:     # if it is a non metadata possible uri return quickly
1.529     albertel 8684:     if (($uri eq '') || 
                   8685: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8686: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8687:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8688: 	return undef;
                   8689:     }
                   8690:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8691: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8692: 	return undef;
1.288     albertel 8693:     }
1.73      www      8694:     my $filename=$uri;
                   8695:     $uri=~s/\.meta$//;
1.172     www      8696: #
                   8697: # Is the metadata already cached?
1.177     www      8698: # Look at timestamp of caching
1.172     www      8699: # Everything is cached by the main uri, libraries are never directly cached
                   8700: #
1.428     albertel 8701:     if (!defined($liburi)) {
1.599     albertel 8702: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8703: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8704:     }
                   8705:     {
1.1069    www      8706: # Imported parts would go here
1.1070    www      8707:         my %importedids=();
                   8708:         my @origfileimportpartids=();
1.1069    www      8709:         my $importedparts=0;
1.172     www      8710: #
                   8711: # Is this a recursive call for a library?
                   8712: #
1.599     albertel 8713: #	if (! exists($metacache{$uri})) {
                   8714: #	    $metacache{$uri}={};
                   8715: #	}
1.924     albertel 8716: 	my $cachetime = 60*60;
1.171     www      8717:         if ($liburi) {
                   8718: 	    $liburi=&declutter($liburi);
                   8719:             $filename=$liburi;
1.401     bowersj2 8720:         } else {
1.599     albertel 8721: 	    &devalidate_cache_new('meta',$uri);
                   8722: 	    undef(%metaentry);
1.401     bowersj2 8723: 	}
1.140     www      8724:         my %metathesekeys=();
1.73      www      8725:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8726: 	my $metastring;
1.924     albertel 8727: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8728: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8729: 	    $metastring = 
1.929     albertel 8730: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8731: 					  ('grade_target' => 'meta'));
                   8732: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8733: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8734:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8735: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8736: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8737: 	    $metastring=&getfile($file);
1.489     albertel 8738: 	}
1.208     albertel 8739:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8740:         my $token;
1.140     www      8741:         undef %metathesekeys;
1.71      www      8742:         while ($token=$parser->get_token) {
1.339     albertel 8743: 	    if ($token->[0] eq 'S') {
                   8744: 		if (defined($token->[2]->{'package'})) {
1.172     www      8745: #
                   8746: # This is a package - get package info
                   8747: #
1.339     albertel 8748: 		    my $package=$token->[2]->{'package'};
                   8749: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8750: 		    if (defined($token->[2]->{'id'})) { 
                   8751: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8752: 		    }
1.599     albertel 8753: 		    if ($metaentry{':packages'}) {
                   8754: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8755: 		    } else {
1.599     albertel 8756: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8757: 		    }
1.736     albertel 8758: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8759: 			my $part=$keyroot;
                   8760: 			$part=~s/^\_//;
1.736     albertel 8761: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8762: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8763: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8764: 			    # ignore package.tab specified default values
                   8765:                             # here &package_tab_default() will fetch those
                   8766: 			    if ($subp eq 'default') { next; }
1.736     albertel 8767: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8768: 			    my $unikey;
                   8769: 			    if ($pack =~ /_0$/) {
                   8770: 				$unikey='parameter_0_'.$name;
                   8771: 				$part=0;
                   8772: 			    } else {
                   8773: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8774: 			    }
1.339     albertel 8775: 			    if ($subp eq 'display') {
                   8776: 				$value.=' [Part: '.$part.']';
                   8777: 			    }
1.599     albertel 8778: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8779: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8780: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8781: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8782: 			    }
1.599     albertel 8783: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8784: 				$metaentry{':'.$unikey}=
                   8785: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8786: 			    }
1.339     albertel 8787: 			}
                   8788: 		    }
                   8789: 		} else {
1.172     www      8790: #
                   8791: # This is not a package - some other kind of start tag
1.339     albertel 8792: #
                   8793: 		    my $entry=$token->[1];
1.1068    www      8794: 		    my $unikey='';
1.175     www      8795: 
1.339     albertel 8796: 		    if ($entry eq 'import') {
1.175     www      8797: #
                   8798: # Importing a library here
1.339     albertel 8799: #
1.1067    www      8800:                         my $location=$parser->get_text('/import');
                   8801:                         my $dir=$filename;
                   8802:                         $dir=~s|[^/]*$||;
                   8803:                         $location=&filelocation($dir,$location);
1.1069    www      8804:                        
1.1068    www      8805:                         my $importmode=$token->[2]->{'importmode'};
                   8806:                         if ($importmode eq 'problem') {
1.1069    www      8807: # Import as problem/response
1.1068    www      8808:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8809:                         } elsif ($importmode eq 'part') {
                   8810: # Import as part(s)
1.1069    www      8811:                            $importedparts=1;
                   8812: # We need to get the original file and the imported file to get the part order correct
                   8813: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8814: # Load and inspect original file
1.1070    www      8815:                            if ($#origfileimportpartids<0) {
                   8816:                               undef(%importedpartids);
                   8817:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8818:                               my $origfile=&getfile($origfilelocation);
                   8819:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8820:                            }
                   8821: 
1.1069    www      8822: # Load and inspect imported file
                   8823:                            my $impfile=&getfile($location);
                   8824:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8825:                            if ($#impfilepartids>=0) {
                   8826: # This problem had parts
1.1070    www      8827:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8828:                            } else {
                   8829: # Importing by turning a single problem into a problem part
                   8830: # It gets the import-tags ID as part-ID
                   8831:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8832:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8833:                            }
1.1068    www      8834:                         } else {
                   8835: # Normal import
                   8836:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8837:                            if (defined($token->[2]->{'id'})) {
                   8838:                               $unikey.='_'.$token->[2]->{'id'};
                   8839:                            }
1.1067    www      8840:                         }
                   8841: 
1.339     albertel 8842: 			if ($depthcount<20) {
1.736     albertel 8843: 			    my $metadata = 
                   8844: 				&metadata($uri,'keys', $location,$unikey,
                   8845: 					  $depthcount+1);
                   8846: 			    foreach my $meta (split(',',$metadata)) {
                   8847: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8848: 				$metathesekeys{$meta}=1;
1.339     albertel 8849: 			    }
1.1068    www      8850: 			
                   8851:                         }
1.1067    www      8852: 		    } else {
                   8853: #
                   8854: # Not importing, some other kind of non-package, non-library start tag
                   8855: # 
                   8856:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8857:                         if (defined($token->[2]->{'id'})) {
                   8858:                             $unikey.='_'.$token->[2]->{'id'};
                   8859:                         }
1.339     albertel 8860: 			if (defined($token->[2]->{'name'})) { 
                   8861: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8862: 			}
                   8863: 			$metathesekeys{$unikey}=1;
1.736     albertel 8864: 			foreach my $param (@{$token->[3]}) {
                   8865: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8866: 				$token->[2]->{$param};
1.339     albertel 8867: 			}
                   8868: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8869: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8870: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8871: 		 # only ws inside the tag, and not in default, so use default
                   8872: 		 # as value
1.599     albertel 8873: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8874: 			} elsif ( $internaltext =~ /\S/ ) {
                   8875: 		  # something interesting inside the tag
                   8876: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8877: 			} else {
1.908     albertel 8878: 		  # no interesting values, don't set a default
1.339     albertel 8879: 			}
1.172     www      8880: # end of not-a-package not-a-library import
1.339     albertel 8881: 		    }
1.172     www      8882: # end of not-a-package start tag
1.339     albertel 8883: 		}
1.172     www      8884: # the next is the end of "start tag"
1.339     albertel 8885: 	    }
                   8886: 	}
1.483     albertel 8887: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8888: 	$extension = lc($extension);
                   8889: 	if ($extension eq 'htm') { $extension='html'; }
                   8890: 
1.737     albertel 8891: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8892: 	    #no specific packages #how's our extension
                   8893: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8894: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8895: 					 \%metathesekeys);
                   8896: 	}
1.883     albertel 8897: 
                   8898: 	if (!exists($metaentry{':packages'})
                   8899: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8900: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8901: 		#no specific packages well let's get default then
                   8902: 		if ($key!~/^default&/) { next; }
1.488     albertel 8903: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8904: 					     \%metathesekeys);
                   8905: 	    }
                   8906: 	}
1.338     www      8907: # are there custom rights to evaluate
1.599     albertel 8908: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8909: 
1.338     www      8910:     #
                   8911:     # Importing a rights file here
1.339     albertel 8912:     #
                   8913: 	    unless ($depthcount) {
1.599     albertel 8914: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8915: 		my $dir=$filename;
                   8916: 		$dir=~s|[^/]*$||;
                   8917: 		$location=&filelocation($dir,$location);
1.736     albertel 8918: 		my $rights_metadata =
                   8919: 		    &metadata($uri,'keys',$location,'_rights',
                   8920: 			      $depthcount+1);
                   8921: 		foreach my $rights (split(',',$rights_metadata)) {
                   8922: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8923: 		    $metathesekeys{$rights}=1;
1.339     albertel 8924: 		}
                   8925: 	    }
                   8926: 	}
1.737     albertel 8927: 	# uniqifiy package listing
                   8928: 	my %seen;
                   8929: 	my @uniq_packages =
                   8930: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8931: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8932: 
1.1070    www      8933:         if ($importedparts) {
                   8934: # We had imported parts and need to rebuild partorder
                   8935:            $metaentry{':partorder'}='';
                   8936:            $metathesekeys{'partorder'}=1;
                   8937:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8938:                if ($origfileimportpartids[$index] eq 'part') {
                   8939: # original part, part of the problem
                   8940:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8941:                } else {
                   8942: # we have imported parts at this position
                   8943:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8944:                }
                   8945:            }
                   8946:            $metaentry{':partorder'}=~s/^\,//;
                   8947:         }
                   8948: 
1.737     albertel 8949: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8950: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8951: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8952: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8953: # this is the end of "was not already recently cached
1.71      www      8954:     }
1.599     albertel 8955:     return $metaentry{':'.$what};
1.261     albertel 8956: }
                   8957: 
1.488     albertel 8958: sub metadata_create_package_def {
1.483     albertel 8959:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8960:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8961:     if ($subp eq 'default') { next; }
                   8962:     
1.599     albertel 8963:     if (defined($metaentry{':packages'})) {
                   8964: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8965:     } else {
1.599     albertel 8966: 	$metaentry{':packages'}=$package;
1.483     albertel 8967:     }
                   8968:     my $value=$packagetab{$key};
                   8969:     my $unikey;
                   8970:     $unikey='parameter_0_'.$name;
1.599     albertel 8971:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8972:     $$metathesekeys{$unikey}=1;
1.599     albertel 8973:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8974: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8975:     }
1.599     albertel 8976:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8977: 	$metaentry{':'.$unikey}=
                   8978: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8979:     }
                   8980: }
                   8981: 
1.261     albertel 8982: sub metadata_generate_part0 {
                   8983:     my ($metadata,$metacache,$uri) = @_;
                   8984:     my %allnames;
1.737     albertel 8985:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8986: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8987: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8988: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8989: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8990: 	    $allnames{$name}=$part;
                   8991: 	  }
                   8992: 	}
                   8993:     }
                   8994:     foreach my $name (keys(%allnames)) {
                   8995:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8996:       my $key=":parameter_0_$name";
1.261     albertel 8997:       $$metacache{"$key.part"}='0';
                   8998:       $$metacache{"$key.name"}=$name;
1.428     albertel 8999:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9000: 					   $allnames{$name}.'_'.$name.
                   9001: 					   '.type'};
1.428     albertel 9002:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9003: 			     '.display'};
1.644     www      9004:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9005:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9006:       $$metacache{"$key.display"}=$olddis;
                   9007:     }
1.71      www      9008: }
                   9009: 
1.764     albertel 9010: # ------------------------------------------------------ Devalidate title cache
                   9011: 
                   9012: sub devalidate_title_cache {
                   9013:     my ($url)=@_;
                   9014:     if (!$env{'request.course.id'}) { return; }
                   9015:     my $symb=&symbread($url);
                   9016:     if (!$symb) { return; }
                   9017:     my $key=$env{'request.course.id'}."\0".$symb;
                   9018:     &devalidate_cache_new('title',$key);
                   9019: }
                   9020: 
1.1014    droeschl 9021: # ------------------------------------------------- Get the title of a course
                   9022: 
                   9023: sub current_course_title {
                   9024:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9025: }
1.301     www      9026: # ------------------------------------------------- Get the title of a resource
                   9027: 
                   9028: sub gettitle {
                   9029:     my $urlsymb=shift;
                   9030:     my $symb=&symbread($urlsymb);
1.534     albertel 9031:     if ($symb) {
1.620     albertel 9032: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9033: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9034: 	if (defined($cached)) { 
                   9035: 	    return $result;
                   9036: 	}
1.534     albertel 9037: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9038: 	my $title='';
1.907     albertel 9039: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9040: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9041: 	} else {
                   9042: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9043: 		    &GDBM_READER(),0640)) {
                   9044: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9045: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9046: 		untie(%bighash);
                   9047: 	    }
1.534     albertel 9048: 	}
                   9049: 	$title=~s/\&colon\;/\:/gs;
                   9050: 	if ($title) {
1.599     albertel 9051: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9052: 	}
                   9053: 	$urlsymb=$url;
                   9054:     }
                   9055:     my $title=&metadata($urlsymb,'title');
                   9056:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9057:     return $title;
1.301     www      9058: }
1.613     albertel 9059: 
1.614     albertel 9060: sub get_slot {
                   9061:     my ($which,$cnum,$cdom)=@_;
                   9062:     if (!$cnum || !$cdom) {
1.790     albertel 9063: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9064: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9065: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9066:     }
1.703     albertel 9067:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9068:     my %slotinfo;
                   9069:     if (exists($remembered{$key})) {
                   9070: 	$slotinfo{$which} = $remembered{$key};
                   9071:     } else {
                   9072: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9073: 	&Apache::lonhomework::showhash(%slotinfo);
                   9074: 	my ($tmp)=keys(%slotinfo);
                   9075: 	if ($tmp=~/^error:/) { return (); }
                   9076: 	$remembered{$key} = $slotinfo{$which};
                   9077:     }
1.616     albertel 9078:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9079: 	return %{$slotinfo{$which}};
                   9080:     }
                   9081:     return $slotinfo{$which};
1.614     albertel 9082: }
1.31      www      9083: # ------------------------------------------------- Update symbolic store links
                   9084: 
                   9085: sub symblist {
                   9086:     my ($mapname,%newhash)=@_;
1.438     www      9087:     $mapname=&deversion(&declutter($mapname));
1.31      www      9088:     my %hash;
1.620     albertel 9089:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9090:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9091:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9092: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9093: 		next if ($url eq 'last_known'
                   9094: 			 && $env{'form.no_update_last_known'});
                   9095: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9096: 						    $newhash{$url}->[1],
                   9097: 						    $newhash{$url}->[0]);
1.191     harris41 9098:             }
1.31      www      9099:             if (untie(%hash)) {
                   9100: 		return 'ok';
                   9101:             }
                   9102:         }
                   9103:     }
                   9104:     return 'error';
1.212     www      9105: }
                   9106: 
                   9107: # --------------------------------------------------------------- Verify a symb
                   9108: 
                   9109: sub symbverify {
1.510     www      9110:     my ($symb,$thisurl)=@_;
                   9111:     my $thisfn=$thisurl;
1.439     www      9112:     $thisfn=&declutter($thisfn);
1.215     www      9113: # direct jump to resource in page or to a sequence - will construct own symbs
                   9114:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9115: # check URL part
1.409     www      9116:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9117: 
1.431     www      9118:     unless ($url eq $thisfn) { return 0; }
1.213     www      9119: 
1.216     www      9120:     $symb=&symbclean($symb);
1.510     www      9121:     $thisurl=&deversion($thisurl);
1.439     www      9122:     $thisfn=&deversion($thisfn);
1.213     www      9123: 
                   9124:     my %bighash;
                   9125:     my $okay=0;
1.431     www      9126: 
1.620     albertel 9127:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9128:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9129:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9130:             $thisurl =~ s/\?.+$//;
                   9131:         }
1.510     www      9132:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9133:         unless ($ids) {
                   9134:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9135:             $ids=$bighash{$idkey};
1.216     www      9136:         }
                   9137:         if ($ids) {
                   9138: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9139: 	    foreach my $id (split(/\,/,$ids)) {
                   9140: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9141:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9142:                    $symb =~ s/\?.+$//;
                   9143:                }
1.216     www      9144:                if (
                   9145:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9146:    eq $symb) { 
1.620     albertel 9147: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9148: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9149:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9150: 		       $okay=1; 
                   9151: 		   }
                   9152: 	       }
1.216     www      9153: 	   }
                   9154:         }
1.213     www      9155: 	untie(%bighash);
                   9156:     }
                   9157:     return $okay;
1.31      www      9158: }
                   9159: 
1.210     www      9160: # --------------------------------------------------------------- Clean-up symb
                   9161: 
                   9162: sub symbclean {
                   9163:     my $symb=shift;
1.568     albertel 9164:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9165: # remove version from map
                   9166:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9167: 
1.210     www      9168: # remove version from URL
                   9169:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9170: 
1.507     www      9171: # remove wrapper
                   9172: 
1.510     www      9173:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9174:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9175:     return $symb;
1.409     www      9176: }
                   9177: 
                   9178: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9179: 
                   9180: sub encode_symb {
                   9181:     my ($map,$resid,$url)=@_;
                   9182:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9183: }
1.409     www      9184: 
                   9185: sub decode_symb {
1.568     albertel 9186:     my $symb=shift;
                   9187:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9188:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9189:     return (&fixversion($map),$resid,&fixversion($url));
                   9190: }
                   9191: 
                   9192: sub fixversion {
                   9193:     my $fn=shift;
1.609     banghart 9194:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9195:     my %bighash;
                   9196:     my $uri=&clutter($fn);
1.620     albertel 9197:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9198: # is this cached?
1.599     albertel 9199:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9200:     if (defined($cached)) { return $result; }
                   9201: # unfortunately not cached, or expired
1.620     albertel 9202:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9203: 	    &GDBM_READER(),0640)) {
                   9204:  	if ($bighash{'version_'.$uri}) {
                   9205:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9206:  	    unless (($version eq 'mostrecent') || 
                   9207: 		    ($version==&getversion($uri))) {
1.440     www      9208:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9209:  	    }
                   9210:  	}
                   9211:  	untie %bighash;
1.413     www      9212:     }
1.599     albertel 9213:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9214: }
                   9215: 
                   9216: sub deversion {
                   9217:     my $url=shift;
                   9218:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9219:     return $url;
1.210     www      9220: }
                   9221: 
1.31      www      9222: # ------------------------------------------------------ Return symb list entry
                   9223: 
                   9224: sub symbread {
1.249     www      9225:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9226:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9227:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9228: # no filename provided? try from environment
1.44      www      9229:     unless ($thisfn) {
1.620     albertel 9230:         if ($env{'request.symb'}) {
                   9231: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9232: 	}
1.620     albertel 9233: 	$thisfn=$env{'request.filename'};
1.44      www      9234:     }
1.569     albertel 9235:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9236: # is that filename actually a symb? Verify, clean, and return
                   9237:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9238: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9239: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9240: 	}
1.242     www      9241:     }
1.44      www      9242:     $thisfn=declutter($thisfn);
1.31      www      9243:     my %hash;
1.37      www      9244:     my %bighash;
                   9245:     my $syval='';
1.620     albertel 9246:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9247:         my $targetfn = $thisfn;
1.609     banghart 9248:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9249:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9250:         }
1.687     albertel 9251: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9252: 	    $targetfn=$1;
                   9253: 	}
1.620     albertel 9254:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9255:                       &GDBM_READER(),0640)) {
1.481     raeburn  9256: 	    $syval=$hash{$targetfn};
1.37      www      9257:             untie(%hash);
                   9258:         }
                   9259: # ---------------------------------------------------------- There was an entry
                   9260:         if ($syval) {
1.601     albertel 9261: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9262: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9263: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9264: 		    #return $env{$cache_str}='';
1.601     albertel 9265: 		#}    
                   9266: 		#$syval.=$1;
                   9267: 	    #}
1.37      www      9268:         } else {
                   9269: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9270:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9271:                             &GDBM_READER(),0640)) {
1.37      www      9272: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9273:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9274:               unless ($ids) { 
                   9275:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9276:               }
                   9277:               unless ($ids) {
                   9278: # alias?
                   9279: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9280:               }
1.37      www      9281:               if ($ids) {
                   9282: # ------------------------------------------------------------------- Has ID(s)
                   9283:                  my @possibilities=split(/\,/,$ids);
1.39      www      9284:                  if ($#possibilities==0) {
                   9285: # ----------------------------------------------- There is only one possibility
1.37      www      9286: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9287: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9288: 						    $resid,$thisfn);
1.249     www      9289:                  } elsif (!$donotrecurse) {
1.39      www      9290: # ------------------------------------------ There is more than one possibility
                   9291:                      my $realpossible=0;
1.800     albertel 9292:                      foreach my $id (@possibilities) {
                   9293: 			 my $file=$bighash{'src_'.$id};
1.39      www      9294:                          if (&allowed('bre',$file)) {
1.800     albertel 9295:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9296:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9297: 				$realpossible++;
1.626     albertel 9298:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9299: 						    $resid,$thisfn);
1.39      www      9300:                             }
                   9301: 			 }
1.191     harris41 9302:                      }
1.39      www      9303: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9304:                  } else {
                   9305:                      $syval='';
1.37      www      9306:                  }
                   9307: 	      }
                   9308:               untie(%bighash)
1.481     raeburn  9309:            }
1.31      www      9310:         }
1.62      www      9311:         if ($syval) {
1.620     albertel 9312: 	    return $env{$cache_str}=$syval;
1.62      www      9313:         }
1.31      www      9314:     }
1.949     raeburn  9315:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9316:     return $env{$cache_str}='';
1.31      www      9317: }
                   9318: 
                   9319: # ---------------------------------------------------------- Return random seed
                   9320: 
1.32      www      9321: sub numval {
                   9322:     my $txt=shift;
                   9323:     $txt=~tr/A-J/0-9/;
                   9324:     $txt=~tr/a-j/0-9/;
                   9325:     $txt=~tr/K-T/0-9/;
                   9326:     $txt=~tr/k-t/0-9/;
                   9327:     $txt=~tr/U-Z/0-5/;
                   9328:     $txt=~tr/u-z/0-5/;
                   9329:     $txt=~s/\D//g;
1.564     albertel 9330:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9331:     return int($txt);
1.368     albertel 9332: }
                   9333: 
1.484     albertel 9334: sub numval2 {
                   9335:     my $txt=shift;
                   9336:     $txt=~tr/A-J/0-9/;
                   9337:     $txt=~tr/a-j/0-9/;
                   9338:     $txt=~tr/K-T/0-9/;
                   9339:     $txt=~tr/k-t/0-9/;
                   9340:     $txt=~tr/U-Z/0-5/;
                   9341:     $txt=~tr/u-z/0-5/;
                   9342:     $txt=~s/\D//g;
                   9343:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9344:     my $total;
                   9345:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9346:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9347:     return int($total);
                   9348: }
                   9349: 
1.575     albertel 9350: sub numval3 {
                   9351:     use integer;
                   9352:     my $txt=shift;
                   9353:     $txt=~tr/A-J/0-9/;
                   9354:     $txt=~tr/a-j/0-9/;
                   9355:     $txt=~tr/K-T/0-9/;
                   9356:     $txt=~tr/k-t/0-9/;
                   9357:     $txt=~tr/U-Z/0-5/;
                   9358:     $txt=~tr/u-z/0-5/;
                   9359:     $txt=~s/\D//g;
                   9360:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9361:     my $total;
                   9362:     foreach my $val (@txts) { $total+=$val; }
                   9363:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9364:     return $total;
                   9365: }
                   9366: 
1.675     albertel 9367: sub digest {
                   9368:     my ($data)=@_;
                   9369:     my $digest=&Digest::MD5::md5($data);
                   9370:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9371:     my ($e,$f);
                   9372:     {
                   9373:         use integer;
                   9374:         $e=($a+$b);
                   9375:         $f=($c+$d);
                   9376:         if ($_64bit) {
                   9377:             $e=(($e<<32)>>32);
                   9378:             $f=(($f<<32)>>32);
                   9379:         }
                   9380:     }
                   9381:     if (wantarray) {
                   9382: 	return ($e,$f);
                   9383:     } else {
                   9384: 	my $g;
                   9385: 	{
                   9386: 	    use integer;
                   9387: 	    $g=($e+$f);
                   9388: 	    if ($_64bit) {
                   9389: 		$g=(($g<<32)>>32);
                   9390: 	    }
                   9391: 	}
                   9392: 	return $g;
                   9393:     }
                   9394: }
                   9395: 
1.368     albertel 9396: sub latest_rnd_algorithm_id {
1.675     albertel 9397:     return '64bit5';
1.366     albertel 9398: }
1.32      www      9399: 
1.503     albertel 9400: sub get_rand_alg {
                   9401:     my ($courseid)=@_;
1.790     albertel 9402:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9403:     if ($courseid) {
1.620     albertel 9404: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9405:     }
                   9406:     return &latest_rnd_algorithm_id();
                   9407: }
                   9408: 
1.562     albertel 9409: sub validCODE {
                   9410:     my ($CODE)=@_;
                   9411:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9412:     return 0;
                   9413: }
                   9414: 
1.491     albertel 9415: sub getCODE {
1.620     albertel 9416:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9417:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9418: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9419: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9420: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9421:     }
                   9422:     return undef;
                   9423: }
                   9424: 
1.31      www      9425: sub rndseed {
1.155     albertel 9426:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9427:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9428:     if (!defined($symb)) {
1.366     albertel 9429: 	unless ($symb=$wsymb) { return time; }
                   9430:     }
                   9431:     if (!$courseid) { $courseid=$wcourseid; }
                   9432:     if (!$domain) { $domain=$wdomain; }
                   9433:     if (!$username) { $username=$wusername }
1.503     albertel 9434:     my $which=&get_rand_alg();
1.1110    www      9435: 
1.491     albertel 9436:     if (defined(&getCODE())) {
1.675     albertel 9437: 	if ($which eq '64bit5') {
                   9438: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9439: 	} elsif ($which eq '64bit4') {
1.575     albertel 9440: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9441: 	} else {
                   9442: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9443: 	}
1.675     albertel 9444:     } elsif ($which eq '64bit5') {
                   9445: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9446:     } elsif ($which eq '64bit4') {
                   9447: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9448:     } elsif ($which eq '64bit3') {
                   9449: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9450:     } elsif ($which eq '64bit2') {
                   9451: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9452:     } elsif ($which eq '64bit') {
                   9453: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9454:     }
                   9455:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9456: }
                   9457: 
                   9458: sub rndseed_32bit {
                   9459:     my ($symb,$courseid,$domain,$username)=@_;
                   9460:     {
                   9461: 	use integer;
                   9462: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9463: 	my $symbseed=numval($symb) << 22;
                   9464: 	my $namechck=unpack("%32C*",$username) << 17;
                   9465: 	my $nameseed=numval($username) << 12;
                   9466: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9467: 	my $courseseed=unpack("%32C*",$courseid);
                   9468: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9469: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9470: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9471: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9472: 	return $num;
                   9473:     }
                   9474: }
                   9475: 
                   9476: sub rndseed_64bit {
                   9477:     my ($symb,$courseid,$domain,$username)=@_;
                   9478:     {
                   9479: 	use integer;
                   9480: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9481: 	my $symbseed=numval($symb) << 10;
                   9482: 	my $namechck=unpack("%32S*",$username);
                   9483: 	
                   9484: 	my $nameseed=numval($username) << 21;
                   9485: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9486: 	my $courseseed=unpack("%32S*",$courseid);
                   9487: 	
                   9488: 	my $num1=$symbchck+$symbseed+$namechck;
                   9489: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9490: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9491: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9492: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9493: 	return "$num1,$num2";
1.155     albertel 9494:     }
1.366     albertel 9495: }
                   9496: 
1.443     albertel 9497: sub rndseed_64bit2 {
                   9498:     my ($symb,$courseid,$domain,$username)=@_;
                   9499:     {
                   9500: 	use integer;
                   9501: 	# strings need to be an even # of cahracters long, it it is odd the
                   9502:         # last characters gets thrown away
                   9503: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9504: 	my $symbseed=numval($symb) << 10;
                   9505: 	my $namechck=unpack("%32S*",$username.' ');
                   9506: 	
                   9507: 	my $nameseed=numval($username) << 21;
1.501     albertel 9508: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9509: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9510: 	
                   9511: 	my $num1=$symbchck+$symbseed+$namechck;
                   9512: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9513: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9514: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9515: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9516: 	return "$num1,$num2";
                   9517:     }
                   9518: }
                   9519: 
                   9520: sub rndseed_64bit3 {
                   9521:     my ($symb,$courseid,$domain,$username)=@_;
                   9522:     {
                   9523: 	use integer;
                   9524: 	# strings need to be an even # of cahracters long, it it is odd the
                   9525:         # last characters gets thrown away
                   9526: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9527: 	my $symbseed=numval2($symb) << 10;
                   9528: 	my $namechck=unpack("%32S*",$username.' ');
                   9529: 	
                   9530: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9531: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9532: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9533: 	
                   9534: 	my $num1=$symbchck+$symbseed+$namechck;
                   9535: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9536: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9537: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9538: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9539: 	
1.503     albertel 9540: 	return "$num1:$num2";
1.443     albertel 9541:     }
                   9542: }
                   9543: 
1.575     albertel 9544: sub rndseed_64bit4 {
                   9545:     my ($symb,$courseid,$domain,$username)=@_;
                   9546:     {
                   9547: 	use integer;
                   9548: 	# strings need to be an even # of cahracters long, it it is odd the
                   9549:         # last characters gets thrown away
                   9550: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9551: 	my $symbseed=numval3($symb) << 10;
                   9552: 	my $namechck=unpack("%32S*",$username.' ');
                   9553: 	
                   9554: 	my $nameseed=numval3($username) << 21;
                   9555: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9556: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9557: 	
                   9558: 	my $num1=$symbchck+$symbseed+$namechck;
                   9559: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9560: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9561: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9562: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9563: 	
1.575     albertel 9564: 	return "$num1:$num2";
                   9565:     }
                   9566: }
                   9567: 
1.675     albertel 9568: sub rndseed_64bit5 {
                   9569:     my ($symb,$courseid,$domain,$username)=@_;
                   9570:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9571:     return "$num1:$num2";
                   9572: }
                   9573: 
1.366     albertel 9574: sub rndseed_CODE_64bit {
                   9575:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9576:     {
1.366     albertel 9577: 	use integer;
1.443     albertel 9578: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9579: 	my $symbseed=numval2($symb);
1.491     albertel 9580: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9581: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9582: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9583: 	my $num1=$symbseed+$CODEchck;
                   9584: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9585: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9586: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9587: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9588: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9589: 	return "$num1:$num2";
1.366     albertel 9590:     }
                   9591: }
                   9592: 
1.575     albertel 9593: sub rndseed_CODE_64bit4 {
                   9594:     my ($symb,$courseid,$domain,$username)=@_;
                   9595:     {
                   9596: 	use integer;
                   9597: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9598: 	my $symbseed=numval3($symb);
                   9599: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9600: 	my $CODEseed=numval3(&getCODE());
                   9601: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9602: 	my $num1=$symbseed+$CODEchck;
                   9603: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9604: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9605: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9606: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9607: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9608: 	return "$num1:$num2";
                   9609:     }
                   9610: }
                   9611: 
1.675     albertel 9612: sub rndseed_CODE_64bit5 {
                   9613:     my ($symb,$courseid,$domain,$username)=@_;
                   9614:     my $code = &getCODE();
                   9615:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9616:     return "$num1:$num2";
                   9617: }
                   9618: 
1.366     albertel 9619: sub setup_random_from_rndseed {
                   9620:     my ($rndseed)=@_;
1.503     albertel 9621:     if ($rndseed =~/([,:])/) {
                   9622: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9623: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9624:     } else {
                   9625: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9626:     }
1.36      albertel 9627: }
                   9628: 
1.474     albertel 9629: sub latest_receipt_algorithm_id {
1.835     albertel 9630:     return 'receipt3';
1.474     albertel 9631: }
                   9632: 
1.480     www      9633: sub recunique {
                   9634:     my $fucourseid=shift;
                   9635:     my $unique;
1.835     albertel 9636:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9637: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9638: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9639:     } else {
                   9640: 	$unique=$perlvar{'lonReceipt'};
                   9641:     }
                   9642:     return unpack("%32C*",$unique);
                   9643: }
                   9644: 
                   9645: sub recprefix {
                   9646:     my $fucourseid=shift;
                   9647:     my $prefix;
1.835     albertel 9648:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9649: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9650: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9651:     } else {
                   9652: 	$prefix=$perlvar{'lonHostID'};
                   9653:     }
                   9654:     return unpack("%32C*",$prefix);
                   9655: }
                   9656: 
1.76      www      9657: sub ireceipt {
1.474     albertel 9658:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9659: 
                   9660:     my $return =&recprefix($fucourseid).'-';
                   9661: 
                   9662:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9663: 	$env{'request.state'} eq 'construct') {
                   9664: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9665: 	return $return;
                   9666:     }
                   9667: 
1.76      www      9668:     my $cuname=unpack("%32C*",$funame);
                   9669:     my $cudom=unpack("%32C*",$fudom);
                   9670:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9671:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9672:     my $cunique=&recunique($fucourseid);
1.474     albertel 9673:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9674:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9675: 
1.790     albertel 9676: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9677: 			       
                   9678: 	$return.= ($cunique%$cuname+
                   9679: 		   $cunique%$cudom+
                   9680: 		   $cusymb%$cuname+
                   9681: 		   $cusymb%$cudom+
                   9682: 		   $cucourseid%$cuname+
                   9683: 		   $cucourseid%$cudom+
                   9684: 		   $cpart%$cuname+
                   9685: 		   $cpart%$cudom);
                   9686:     } else {
                   9687: 	$return.= ($cunique%$cuname+
                   9688: 		   $cunique%$cudom+
                   9689: 		   $cusymb%$cuname+
                   9690: 		   $cusymb%$cudom+
                   9691: 		   $cucourseid%$cuname+
                   9692: 		   $cucourseid%$cudom);
                   9693:     }
                   9694:     return $return;
1.76      www      9695: }
                   9696: 
                   9697: sub receipt {
1.474     albertel 9698:     my ($part)=@_;
1.790     albertel 9699:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9700:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9701: }
1.260     ng       9702: 
1.790     albertel 9703: sub whichuser {
                   9704:     my ($passedsymb)=@_;
                   9705:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9706:     if (defined($env{'form.grade_symb'})) {
                   9707: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9708: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9709: 	if (!$allowed &&
                   9710: 	    exists($env{'request.course.sec'}) &&
                   9711: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9712: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9713: 			      '/'.$env{'request.course.sec'});
                   9714: 	}
                   9715: 	if ($allowed) {
                   9716: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9717: 	    $courseid=$tmp_courseid;
                   9718: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9719: 	    ($name)=&get_env_multiple('form.grade_username');
                   9720: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9721: 	}
                   9722:     }
                   9723:     if (!$passedsymb) {
                   9724: 	$symb=&symbread();
                   9725:     } else {
                   9726: 	$symb=$passedsymb;
                   9727:     }
                   9728:     $courseid=$env{'request.course.id'};
                   9729:     $domain=$env{'user.domain'};
                   9730:     $name=$env{'user.name'};
                   9731:     if ($name eq 'public' && $domain eq 'public') {
                   9732: 	if (!defined($env{'form.username'})) {
                   9733: 	    $env{'form.username'}.=time.rand(10000000);
                   9734: 	}
                   9735: 	$name.=$env{'form.username'};
                   9736:     }
                   9737:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9738: 
                   9739: }
                   9740: 
1.36      albertel 9741: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9742: # returns either the contents of the file or 
                   9743: # -1 if the file doesn't exist
1.481     raeburn  9744: #
                   9745: # if the target is a file that was uploaded via DOCS, 
                   9746: # a check will be made to see if a current copy exists on the local server,
                   9747: # if it does this will be served, otherwise a copy will be retrieved from
                   9748: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9749: # the local server.   
1.472     albertel 9750: 
1.36      albertel 9751: sub getfile {
1.538     albertel 9752:     my ($file) = @_;
1.609     banghart 9753:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9754:     &repcopy($file);
                   9755:     return &readfile($file);
                   9756: }
                   9757: 
                   9758: sub repcopy_userfile {
                   9759:     my ($file)=@_;
1.609     banghart 9760:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9761:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9762:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9763: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9764:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9765:     if (-e "$file") {
1.828     www      9766: # we already have a local copy, check it out
1.538     albertel 9767: 	my @fileinfo = stat($file);
1.828     www      9768: 	my $rtncode;
                   9769: 	my $info;
1.538     albertel 9770: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9771: 	if ($lwpresp ne 'ok') {
1.828     www      9772: # there is no such file anymore, even though we had a local copy
1.482     albertel 9773: 	    if ($rtncode eq '404') {
1.538     albertel 9774: 		unlink($file);
1.482     albertel 9775: 	    }
                   9776: 	    return -1;
                   9777: 	}
                   9778: 	if ($info < $fileinfo[9]) {
1.828     www      9779: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9780: 	    return 'ok';
1.828     www      9781: 	} else {
                   9782: # the file is outdated, get rid of it
                   9783: 	    unlink($file);
1.482     albertel 9784: 	}
1.828     www      9785:     }
                   9786: # one way or the other, at this point, we don't have the file
                   9787: # construct the correct path for the file
                   9788:     my @parts = ($cdom,$cnum); 
                   9789:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9790: 	push @parts, split(/\//,$1);
                   9791:     }
                   9792:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9793:     foreach my $part (@parts) {
                   9794: 	$path .= '/'.$part;
                   9795: 	if (!-e $path) {
                   9796: 	    mkdir($path,0770);
1.482     albertel 9797: 	}
                   9798:     }
1.828     www      9799: # now the path exists for sure
                   9800: # get a user agent
                   9801:     my $ua=new LWP::UserAgent;
                   9802:     my $transferfile=$file.'.in.transfer';
                   9803: # FIXME: this should flock
                   9804:     if (-e $transferfile) { return 'ok'; }
                   9805:     my $request;
                   9806:     $uri=~s/^\///;
1.980     raeburn  9807:     my $homeserver = &homeserver($cnum,$cdom);
                   9808:     my $protocol = $protocol{$homeserver};
                   9809:     $protocol = 'http' if ($protocol ne 'https');
                   9810:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9811:     my $response=$ua->request($request,$transferfile);
                   9812: # did it work?
                   9813:     if ($response->is_error()) {
                   9814: 	unlink($transferfile);
                   9815: 	&logthis("Userfile repcopy failed for $uri");
                   9816: 	return -1;
                   9817:     }
                   9818: # worked, rename the transfer file
                   9819:     rename($transferfile,$file);
1.607     raeburn  9820:     return 'ok';
1.481     raeburn  9821: }
                   9822: 
1.517     albertel 9823: sub tokenwrapper {
                   9824:     my $uri=shift;
1.980     raeburn  9825:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9826:     $uri=~s|^/||;
1.620     albertel 9827:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9828:     my $token=$1;
1.552     albertel 9829:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9830:     if ($udom && $uname && $file) {
                   9831: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9832:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9833:         my $homeserver = &homeserver($uname,$udom);
                   9834:         my $protocol = $protocol{$homeserver};
                   9835:         $protocol = 'http' if ($protocol ne 'https');
                   9836:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9837:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9838:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9839:     } else {
                   9840:         return '/adm/notfound.html';
                   9841:     }
                   9842: }
                   9843: 
1.828     www      9844: # call with reqtype HEAD: get last modification time
                   9845: # call with reqtype GET: get the file contents
                   9846: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9847: #
1.481     raeburn  9848: sub getuploaded {
                   9849:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9850:     $uri=~s/^\///;
1.980     raeburn  9851:     my $homeserver = &homeserver($cnum,$cdom);
                   9852:     my $protocol = $protocol{$homeserver};
                   9853:     $protocol = 'http' if ($protocol ne 'https');
                   9854:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9855:     my $ua=new LWP::UserAgent;
                   9856:     my $request=new HTTP::Request($reqtype,$uri);
                   9857:     my $response=$ua->request($request);
                   9858:     $$rtncode = $response->code;
1.482     albertel 9859:     if (! $response->is_success()) {
                   9860: 	return 'failed';
                   9861:     }      
                   9862:     if ($reqtype eq 'HEAD') {
1.486     www      9863: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9864:     } elsif ($reqtype eq 'GET') {
                   9865: 	$$info = $response->content;
1.472     albertel 9866:     }
1.482     albertel 9867:     return 'ok';
1.36      albertel 9868: }
                   9869: 
1.481     raeburn  9870: sub readfile {
                   9871:     my $file = shift;
                   9872:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9873:     my $fh;
                   9874:     open($fh,"<$file");
                   9875:     my $a='';
1.800     albertel 9876:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9877:     return $a;
                   9878: }
                   9879: 
1.36      albertel 9880: sub filelocation {
1.590     banghart 9881:     my ($dir,$file) = @_;
                   9882:     my $location;
                   9883:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9884: 
                   9885:     if ($file =~ m-^/adm/-) {
                   9886: 	$file=~s-^/adm/wrapper/-/-;
                   9887: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9888:     }
1.882     albertel 9889: 
1.590     banghart 9890:     if ($file=~m:^/~:) { # is a contruction space reference
                   9891:         $location = $file;
                   9892:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9893:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9894: 	# is a correct contruction space reference
                   9895:         $location = $file;
1.956     raeburn  9896:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9897:         $location = $file;
1.609     banghart 9898:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9899:         my ($udom,$uname,$filename)=
1.811     albertel 9900:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9901:         my $home=&homeserver($uname,$udom);
                   9902:         my $is_me=0;
                   9903:         my @ids=&current_machine_ids();
                   9904:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9905:         if ($is_me) {
1.1117    foxr     9906:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9907:         } else {
                   9908:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9909:   	      $udom.'/'.$uname.'/'.$filename;
                   9910:         }
1.882     albertel 9911:     } elsif ($file =~ m-^/adm/-) {
                   9912: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9913:     } else {
                   9914:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9915:         $file=~s:^/res/:/:;
                   9916:         if ( !( $file =~ m:^/:) ) {
                   9917:             $location = $dir. '/'.$file;
                   9918:         } else {
                   9919:             $location = '/home/httpd/html/res'.$file;
                   9920:         }
1.59      albertel 9921:     }
1.590     banghart 9922:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9923:     while ($location=~m{/\.\./}) {
                   9924: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9925: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9926: 	} else {
                   9927: 	    $location=~ s{/\.\./}{/}g;
                   9928: 	}
                   9929:     } #remove dir/..
1.590     banghart 9930:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9931:     return $location;
1.46      www      9932: }
1.36      albertel 9933: 
1.46      www      9934: sub hreflocation {
                   9935:     my ($dir,$file)=@_;
1.980     raeburn  9936:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9937: 	$file=filelocation($dir,$file);
1.700     albertel 9938:     } elsif ($file=~m-^/adm/-) {
                   9939: 	$file=~s-^/adm/wrapper/-/-;
                   9940: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9941:     }
                   9942:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9943: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9944:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9945: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9946:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9947: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9948: 	    -/uploaded/$1/$2/-x;
1.46      www      9949:     }
1.913     albertel 9950:     if ($file=~ m{^/userfiles/}) {
                   9951: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9952:     }
1.462     albertel 9953:     return $file;
1.465     albertel 9954: }
                   9955: 
                   9956: sub current_machine_domains {
1.853     albertel 9957:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9958: }
                   9959: 
                   9960: sub machine_domains {
                   9961:     my ($hostname) = @_;
1.465     albertel 9962:     my @domains;
1.838     albertel 9963:     my %hostname = &all_hostnames();
1.465     albertel 9964:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9965: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9966: 	if ($hostname eq $name) {
1.844     albertel 9967: 	    push(@domains,&host_domain($id));
1.465     albertel 9968: 	}
                   9969:     }
                   9970:     return @domains;
                   9971: }
                   9972: 
                   9973: sub current_machine_ids {
1.853     albertel 9974:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9975: }
                   9976: 
                   9977: sub machine_ids {
                   9978:     my ($hostname) = @_;
                   9979:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9980:     my @ids;
1.888     albertel 9981:     my %name_to_host = &all_names();
1.889     albertel 9982:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9983: 	return @{ $name_to_host{$hostname} };
                   9984:     }
                   9985:     return;
1.31      www      9986: }
                   9987: 
1.824     raeburn  9988: sub additional_machine_domains {
                   9989:     my @domains;
                   9990:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9991:     while( my $line = <$fh>) {
                   9992:         $line =~ s/\s//g;
                   9993:         push(@domains,$line);
                   9994:     }
                   9995:     return @domains;
                   9996: }
                   9997: 
                   9998: sub default_login_domain {
                   9999:     my $domain = $perlvar{'lonDefDomain'};
                   10000:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10001:     foreach my $posdom (&current_machine_domains(),
                   10002:                         &additional_machine_domains()) {
                   10003:         if (lc($posdom) eq lc($testdomain)) {
                   10004:             $domain=$posdom;
                   10005:             last;
                   10006:         }
                   10007:     }
                   10008:     return $domain;
                   10009: }
                   10010: 
1.31      www      10011: # ------------------------------------------------------------- Declutters URLs
                   10012: 
                   10013: sub declutter {
                   10014:     my $thisfn=shift;
1.569     albertel 10015:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10016:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10017:     $thisfn=~s/^\///;
1.697     albertel 10018:     $thisfn=~s|^adm/wrapper/||;
                   10019:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10020:     $thisfn=~s/^res\///;
1.1032    raeburn  10021:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10022:         $thisfn=~s/\?.+$//;
                   10023:     }
1.268     www      10024:     return $thisfn;
                   10025: }
                   10026: 
                   10027: # ------------------------------------------------------------- Clutter up URLs
                   10028: 
                   10029: sub clutter {
                   10030:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10031:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10032: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10033:        $thisfn='/res'.$thisfn; 
                   10034:     }
1.1031    raeburn  10035:     if ($thisfn !~m|^/adm|) {
                   10036: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10037: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10038: 	} else {
                   10039: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10040: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10041: 	    if ($embstyle eq 'ssi'
                   10042: 		|| ($embstyle eq 'hdn')
                   10043: 		|| ($embstyle eq 'rat')
                   10044: 		|| ($embstyle eq 'prv')
                   10045: 		|| ($embstyle eq 'ign')) {
                   10046: 		#do nothing with these
                   10047: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10048: 		|| ($embstyle eq 'emb')
                   10049: 		|| ($embstyle eq 'wrp')) {
                   10050: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10051: 	    } elsif ($embstyle eq 'unk'
                   10052: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10053: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10054: 	    } else {
1.718     www      10055: #		&logthis("Got a blank emb style");
1.695     albertel 10056: 	    }
1.694     albertel 10057: 	}
                   10058:     }
1.31      www      10059:     return $thisfn;
1.12      www      10060: }
                   10061: 
1.787     albertel 10062: sub clutter_with_no_wrapper {
                   10063:     my $uri = &clutter(shift);
                   10064:     if ($uri =~ m-^/adm/-) {
                   10065: 	$uri =~ s-^/adm/wrapper/-/-;
                   10066: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10067:     }
                   10068:     return $uri;
                   10069: }
                   10070: 
1.557     albertel 10071: sub freeze_escape {
                   10072:     my ($value)=@_;
                   10073:     if (ref($value)) {
                   10074: 	$value=&nfreeze($value);
                   10075: 	return '__FROZEN__'.&escape($value);
                   10076:     }
                   10077:     return &escape($value);
                   10078: }
                   10079: 
1.11      www      10080: 
1.557     albertel 10081: sub thaw_unescape {
                   10082:     my ($value)=@_;
                   10083:     if ($value =~ /^__FROZEN__/) {
                   10084: 	substr($value,0,10,undef);
                   10085: 	$value=&unescape($value);
                   10086: 	return &thaw($value);
                   10087:     }
                   10088:     return &unescape($value);
                   10089: }
                   10090: 
1.436     albertel 10091: sub correct_line_ends {
                   10092:     my ($result)=@_;
                   10093:     $$result =~s/\r\n/\n/mg;
                   10094:     $$result =~s/\r/\n/mg;
1.415     albertel 10095: }
1.1       albertel 10096: # ================================================================ Main Program
                   10097: 
1.184     www      10098: sub goodbye {
1.204     albertel 10099:    &logthis("Starting Shut down");
1.443     albertel 10100: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10101:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10102: #converted
1.599     albertel 10103: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10104:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10105: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10106: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10107: #1.1 only
1.870     albertel 10108: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10109: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10110: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10111: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10112:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10113:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10114:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10115:    &flushcourselogs();
                   10116:    &logthis("Shutting down");
                   10117: }
                   10118: 
1.852     albertel 10119: sub get_dns {
1.869     albertel 10120:     my ($url,$func,$ignore_cache) = @_;
                   10121:     if (!$ignore_cache) {
                   10122: 	my ($content,$cached)=
                   10123: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10124: 	if ($cached) {
                   10125: 	    &$func($content);
                   10126: 	    return;
                   10127: 	}
                   10128:     }
                   10129: 
                   10130:     my %alldns;
1.852     albertel 10131:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10132:     foreach my $dns (<$config>) {
                   10133: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10134:         my $line = $1;
                   10135:         my ($host,$protocol) = split(/:/,$line);
                   10136:         if ($protocol ne 'https') {
                   10137:             $protocol = 'http';
                   10138:         }
                   10139: 	$alldns{$host} = $protocol;
1.869     albertel 10140:     }
                   10141:     while (%alldns) {
                   10142: 	my ($dns) = keys(%alldns);
1.852     albertel 10143: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10144: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10145: 	my $response=$ua->request($request);
1.979     raeburn  10146:         delete($alldns{$dns});
1.852     albertel 10147: 	next if ($response->is_error());
                   10148: 	my @content = split("\n",$response->content);
1.869     albertel 10149: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10150: 	&$func(\@content);
1.869     albertel 10151: 	return;
1.852     albertel 10152:     }
                   10153:     close($config);
1.871     albertel 10154:     my $which = (split('/',$url))[3];
                   10155:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10156:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10157:     my @content = <$config>;
                   10158:     &$func(\@content);
                   10159:     return;
1.852     albertel 10160: }
1.327     albertel 10161: # ------------------------------------------------------------ Read domain file
                   10162: {
1.852     albertel 10163:     my $loaded;
1.846     albertel 10164:     my %domain;
                   10165: 
1.852     albertel 10166:     sub parse_domain_tab {
                   10167: 	my ($lines) = @_;
                   10168: 	foreach my $line (@$lines) {
                   10169: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10170: 
1.846     albertel 10171: 	    chomp($line);
1.852     albertel 10172: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10173: 	    my %this_domain;
                   10174: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10175: 			       'lang_def', 'city', 'longi', 'lati',
                   10176: 			       'primary') {
                   10177: 		$this_domain{$field} = shift(@elements);
                   10178: 	    }
                   10179: 	    $domain{$name} = \%this_domain;
1.852     albertel 10180: 	}
                   10181:     }
1.864     albertel 10182: 
                   10183:     sub reset_domain_info {
                   10184: 	undef($loaded);
                   10185: 	undef(%domain);
                   10186:     }
                   10187: 
1.852     albertel 10188:     sub load_domain_tab {
1.869     albertel 10189: 	my ($ignore_cache) = @_;
                   10190: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10191: 	my $fh;
                   10192: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10193: 	    my @lines = <$fh>;
                   10194: 	    &parse_domain_tab(\@lines);
1.448     albertel 10195: 	}
1.852     albertel 10196: 	close($fh);
                   10197: 	$loaded = 1;
1.327     albertel 10198:     }
1.846     albertel 10199: 
                   10200:     sub domain {
1.852     albertel 10201: 	&load_domain_tab() if (!$loaded);
                   10202: 
1.846     albertel 10203: 	my ($name,$what) = @_;
                   10204: 	return if ( !exists($domain{$name}) );
                   10205: 
                   10206: 	if (!$what) {
                   10207: 	    return $domain{$name}{'description'};
                   10208: 	}
                   10209: 	return $domain{$name}{$what};
                   10210:     }
1.974     raeburn  10211: 
                   10212:     sub domain_info {
                   10213:         &load_domain_tab() if (!$loaded);
                   10214:         return %domain;
                   10215:     }
                   10216: 
1.327     albertel 10217: }
                   10218: 
                   10219: 
1.1       albertel 10220: # ------------------------------------------------------------- Read hosts file
                   10221: {
1.838     albertel 10222:     my %hostname;
1.844     albertel 10223:     my %hostdom;
1.845     albertel 10224:     my %libserv;
1.852     albertel 10225:     my $loaded;
1.888     albertel 10226:     my %name_to_host;
1.1074    raeburn  10227:     my %internetdom;
1.1107    raeburn  10228:     my %LC_dns_serv;
1.852     albertel 10229: 
                   10230:     sub parse_hosts_tab {
                   10231: 	my ($file) = @_;
                   10232: 	foreach my $configline (@$file) {
                   10233: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10234:             chomp($configline);
                   10235: 	    if ($configline =~ /^\^/) {
                   10236:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10237:                     $LC_dns_serv{$1} = 1;
                   10238:                 }
                   10239:                 next;
                   10240:             }
1.1074    raeburn  10241: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10242: 	    $name=~s/\s//g;
                   10243: 	    if ($id && $domain && $role && $name) {
                   10244: 		$hostname{$id}=$name;
1.888     albertel 10245: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10246: 		$hostdom{$id}=$domain;
                   10247: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10248:                 if (defined($protocol)) {
                   10249:                     if ($protocol eq 'https') {
                   10250:                         $protocol{$id} = $protocol;
                   10251:                     } else {
                   10252:                         $protocol{$id} = 'http'; 
                   10253:                     }
1.968     raeburn  10254:                 } else {
1.969     raeburn  10255:                     $protocol{$id} = 'http';
1.968     raeburn  10256:                 }
1.1074    raeburn  10257:                 if (defined($intdom)) {
                   10258:                     $internetdom{$id} = $intdom;
                   10259:                 }
1.852     albertel 10260: 	    }
                   10261: 	}
                   10262:     }
1.864     albertel 10263:     
                   10264:     sub reset_hosts_info {
1.897     albertel 10265: 	&purge_remembered();
1.864     albertel 10266: 	&reset_domain_info();
                   10267: 	&reset_hosts_ip_info();
1.892     albertel 10268: 	undef(%name_to_host);
1.864     albertel 10269: 	undef(%hostname);
                   10270: 	undef(%hostdom);
                   10271: 	undef(%libserv);
                   10272: 	undef($loaded);
                   10273:     }
1.1       albertel 10274: 
1.852     albertel 10275:     sub load_hosts_tab {
1.869     albertel 10276: 	my ($ignore_cache) = @_;
                   10277: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10278: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10279: 	my @config = <$config>;
                   10280: 	&parse_hosts_tab(\@config);
                   10281: 	close($config);
                   10282: 	$loaded=1;
1.1       albertel 10283:     }
1.852     albertel 10284: 
1.838     albertel 10285:     sub hostname {
1.852     albertel 10286: 	&load_hosts_tab() if (!$loaded);
                   10287: 
1.838     albertel 10288: 	my ($lonid) = @_;
                   10289: 	return $hostname{$lonid};
                   10290:     }
1.845     albertel 10291: 
1.838     albertel 10292:     sub all_hostnames {
1.852     albertel 10293: 	&load_hosts_tab() if (!$loaded);
                   10294: 
1.838     albertel 10295: 	return %hostname;
                   10296:     }
1.845     albertel 10297: 
1.888     albertel 10298:     sub all_names {
                   10299: 	&load_hosts_tab() if (!$loaded);
                   10300: 
                   10301: 	return %name_to_host;
                   10302:     }
                   10303: 
1.974     raeburn  10304:     sub all_host_domain {
                   10305:         &load_hosts_tab() if (!$loaded);
                   10306:         return %hostdom;
                   10307:     }
                   10308: 
1.845     albertel 10309:     sub is_library {
1.852     albertel 10310: 	&load_hosts_tab() if (!$loaded);
                   10311: 
1.845     albertel 10312: 	return exists($libserv{$_[0]});
                   10313:     }
                   10314: 
                   10315:     sub all_library {
1.852     albertel 10316: 	&load_hosts_tab() if (!$loaded);
                   10317: 
1.845     albertel 10318: 	return %libserv;
                   10319:     }
                   10320: 
1.1062    droeschl 10321:     sub unique_library {
                   10322: 	#2x reverse removes all hostnames that appear more than once
                   10323:         my %unique = reverse &all_library();
                   10324:         return reverse %unique;
                   10325:     }
                   10326: 
1.841     albertel 10327:     sub get_servers {
1.852     albertel 10328: 	&load_hosts_tab() if (!$loaded);
                   10329: 
1.841     albertel 10330: 	my ($domain,$type) = @_;
                   10331: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10332: 	                                          : %hostname;
                   10333: 	my %result;
1.842     albertel 10334: 	if (ref($domain) eq 'ARRAY') {
                   10335: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10336: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10337: 		    $result{$host} = $hostname;
                   10338: 		}
                   10339: 	    }
                   10340: 	} else {
                   10341: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10342: 		if ($hostdom{$host} eq $domain) {
                   10343: 		    $result{$host} = $hostname;
                   10344: 		}
1.841     albertel 10345: 	    }
                   10346: 	}
                   10347: 	return %result;
                   10348:     }
1.845     albertel 10349: 
1.1062    droeschl 10350:     sub get_unique_servers {
                   10351:         my %unique = reverse &get_servers(@_);
                   10352: 	return reverse %unique;
                   10353:     }
                   10354: 
1.844     albertel 10355:     sub host_domain {
1.852     albertel 10356: 	&load_hosts_tab() if (!$loaded);
                   10357: 
1.844     albertel 10358: 	my ($lonid) = @_;
                   10359: 	return $hostdom{$lonid};
                   10360:     }
                   10361: 
1.841     albertel 10362:     sub all_domains {
1.852     albertel 10363: 	&load_hosts_tab() if (!$loaded);
                   10364: 
1.841     albertel 10365: 	my %seen;
                   10366: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10367: 	return @uniq;
                   10368:     }
1.1074    raeburn  10369: 
                   10370:     sub internet_dom {
                   10371:         &load_hosts_tab() if (!$loaded);
                   10372: 
                   10373:         my ($lonid) = @_;
                   10374:         return $internetdom{$lonid};
                   10375:     }
1.1107    raeburn  10376: 
                   10377:     sub is_LC_dns {
                   10378:         &load_hosts_tab() if (!$loaded);
                   10379: 
                   10380:         my ($hostname) = @_;
                   10381:         return exists($LC_dns_serv{$hostname});
                   10382:     }
                   10383: 
1.1       albertel 10384: }
                   10385: 
1.847     albertel 10386: { 
                   10387:     my %iphost;
1.856     albertel 10388:     my %name_to_ip;
                   10389:     my %lonid_to_ip;
1.869     albertel 10390: 
1.847     albertel 10391:     sub get_hosts_from_ip {
                   10392: 	my ($ip) = @_;
                   10393: 	my %iphosts = &get_iphost();
                   10394: 	if (ref($iphosts{$ip})) {
                   10395: 	    return @{$iphosts{$ip}};
                   10396: 	}
                   10397: 	return;
1.839     albertel 10398:     }
1.864     albertel 10399:     
                   10400:     sub reset_hosts_ip_info {
                   10401: 	undef(%iphost);
                   10402: 	undef(%name_to_ip);
                   10403: 	undef(%lonid_to_ip);
                   10404:     }
1.856     albertel 10405: 
                   10406:     sub get_host_ip {
                   10407: 	my ($lonid) = @_;
                   10408: 	if (exists($lonid_to_ip{$lonid})) {
                   10409: 	    return $lonid_to_ip{$lonid};
                   10410: 	}
                   10411: 	my $name=&hostname($lonid);
                   10412:    	my $ip = gethostbyname($name);
                   10413: 	return if (!$ip || length($ip) ne 4);
                   10414: 	$ip=inet_ntoa($ip);
                   10415: 	$name_to_ip{$name}   = $ip;
                   10416: 	$lonid_to_ip{$lonid} = $ip;
                   10417: 	return $ip;
                   10418:     }
1.847     albertel 10419:     
                   10420:     sub get_iphost {
1.869     albertel 10421: 	my ($ignore_cache) = @_;
1.894     albertel 10422: 
1.869     albertel 10423: 	if (!$ignore_cache) {
                   10424: 	    if (%iphost) {
                   10425: 		return %iphost;
                   10426: 	    }
                   10427: 	    my ($ip_info,$cached)=
                   10428: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10429: 	    if ($cached) {
                   10430: 		%iphost      = %{$ip_info->[0]};
                   10431: 		%name_to_ip  = %{$ip_info->[1]};
                   10432: 		%lonid_to_ip = %{$ip_info->[2]};
                   10433: 		return %iphost;
                   10434: 	    }
                   10435: 	}
1.894     albertel 10436: 
                   10437: 	# get yesterday's info for fallback
                   10438: 	my %old_name_to_ip;
                   10439: 	my ($ip_info,$cached)=
                   10440: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10441: 	if ($cached) {
                   10442: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10443: 	}
                   10444: 
1.888     albertel 10445: 	my %name_to_host = &all_names();
                   10446: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10447: 	    my $ip;
                   10448: 	    if (!exists($name_to_ip{$name})) {
                   10449: 		$ip = gethostbyname($name);
                   10450: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10451: 		    if (defined($old_name_to_ip{$name})) {
                   10452: 			$ip = $old_name_to_ip{$name};
                   10453: 			&logthis("Can't find $name defaulting to old $ip");
                   10454: 		    } else {
                   10455: 			&logthis("Name $name no IP found");
                   10456: 			next;
                   10457: 		    }
                   10458: 		} else {
                   10459: 		    $ip=inet_ntoa($ip);
1.847     albertel 10460: 		}
                   10461: 		$name_to_ip{$name} = $ip;
                   10462: 	    } else {
                   10463: 		$ip = $name_to_ip{$name};
1.653     albertel 10464: 	    }
1.888     albertel 10465: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10466: 		$lonid_to_ip{$id} = $ip;
                   10467: 	    }
                   10468: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10469: 	}
1.869     albertel 10470: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10471: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10472: 				      48*60*60);
1.869     albertel 10473: 
1.847     albertel 10474: 	return %iphost;
1.598     albertel 10475:     }
                   10476: 
1.992     raeburn  10477:     #
                   10478:     #  Given a DNS returns the loncapa host name for that DNS 
                   10479:     # 
                   10480:     sub host_from_dns {
                   10481:         my ($dns) = @_;
                   10482:         my @hosts;
                   10483:         my $ip;
                   10484: 
1.993     raeburn  10485:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10486:             $ip = $name_to_ip{$dns};
                   10487:         }
                   10488:         if (!$ip) {
                   10489:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10490:             if (length($ip) == 4) { 
                   10491: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10492:             }
                   10493:         }
                   10494:         if ($ip) {
                   10495: 	    @hosts = get_hosts_from_ip($ip);
                   10496: 	    return $hosts[0];
                   10497:         }
                   10498:         return undef;
1.986     foxr     10499:     }
1.992     raeburn  10500: 
1.1074    raeburn  10501:     sub get_internet_names {
                   10502:         my ($lonid) = @_;
                   10503:         return if ($lonid eq '');
                   10504:         my ($idnref,$cached)=
                   10505:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10506:         if ($cached) {
                   10507:             return $idnref;
                   10508:         }
                   10509:         my $ip = &get_host_ip($lonid);
                   10510:         my @hosts = &get_hosts_from_ip($ip);
                   10511:         my %iphost = &get_iphost();
                   10512:         my (@idns,%seen);
                   10513:         foreach my $id (@hosts) {
                   10514:             my $dom = &host_domain($id);
                   10515:             my $prim_id = &domain($dom,'primary');
                   10516:             my $prim_ip = &get_host_ip($prim_id);
                   10517:             next if ($seen{$prim_ip});
                   10518:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10519:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10520:                     my $intdom = &internet_dom($id);
                   10521:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10522:                         push(@idns,$intdom);
                   10523:                     }
                   10524:                 }
                   10525:             }
                   10526:             $seen{$prim_ip} = 1;
                   10527:         }
                   10528:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10529:     }
                   10530: 
1.986     foxr     10531: }
                   10532: 
1.1079    raeburn  10533: sub all_loncaparevs {
                   10534:     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);
                   10535: }
                   10536: 
1.862     albertel 10537: BEGIN {
                   10538: 
                   10539: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10540:     unless ($readit) {
                   10541: {
                   10542:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10543:     %perlvar = (%perlvar,%{$configvars});
                   10544: }
                   10545: 
                   10546: 
1.1       albertel 10547: # ------------------------------------------------------ Read spare server file
                   10548: {
1.448     albertel 10549:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10550: 
                   10551:     while (my $configline=<$config>) {
                   10552:        chomp($configline);
1.284     matthew  10553:        if ($configline) {
1.784     albertel 10554: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10555: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10556: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10557:        }
                   10558:     }
1.448     albertel 10559:     close($config);
1.1       albertel 10560: }
1.11      www      10561: # ------------------------------------------------------------ Read permissions
                   10562: {
1.448     albertel 10563:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10564: 
                   10565:     while (my $configline=<$config>) {
1.448     albertel 10566: 	chomp($configline);
                   10567: 	if ($configline) {
                   10568: 	    my ($role,$perm)=split(/ /,$configline);
                   10569: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10570: 	}
1.11      www      10571:     }
1.448     albertel 10572:     close($config);
1.11      www      10573: }
                   10574: 
                   10575: # -------------------------------------------- Read plain texts for permissions
                   10576: {
1.448     albertel 10577:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10578: 
                   10579:     while (my $configline=<$config>) {
1.448     albertel 10580: 	chomp($configline);
                   10581: 	if ($configline) {
1.742     raeburn  10582: 	    my ($short,@plain)=split(/:/,$configline);
                   10583:             %{$prp{$short}} = ();
                   10584: 	    if (@plain > 0) {
                   10585:                 $prp{$short}{'std'} = $plain[0];
                   10586:                 for (my $i=1; $i<@plain; $i++) {
                   10587:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10588:                 }
                   10589:             }
1.448     albertel 10590: 	}
1.135     www      10591:     }
1.448     albertel 10592:     close($config);
1.135     www      10593: }
                   10594: 
                   10595: # ---------------------------------------------------------- Read package table
                   10596: {
1.448     albertel 10597:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10598: 
                   10599:     while (my $configline=<$config>) {
1.483     albertel 10600: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10601: 	chomp($configline);
                   10602: 	my ($short,$plain)=split(/:/,$configline);
                   10603: 	my ($pack,$name)=split(/\&/,$short);
                   10604: 	if ($plain ne '') {
                   10605: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10606: 	    $packagetab{$short}=$plain; 
                   10607: 	}
1.11      www      10608:     }
1.448     albertel 10609:     close($config);
1.329     matthew  10610: }
                   10611: 
1.1073    raeburn  10612: # ---------------------------------------------------------- Read loncaparev table
                   10613: {
                   10614:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10615:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10616:             while (my $configline=<$config>) {
                   10617:                 chomp($configline);
                   10618:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10619:                 $loncaparevs{$hostid}=$loncaparev;
                   10620:             }
                   10621:             close($config);
                   10622:         }
                   10623:     }
                   10624: }
                   10625: 
1.1074    raeburn  10626: # ---------------------------------------------------------- Read serverhostID table
                   10627: {
                   10628:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10629:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10630:             while (my $configline=<$config>) {
                   10631:                 chomp($configline);
                   10632:                 my ($name,$id)=split(/:/,$configline);
                   10633:                 $serverhomeIDs{$name}=$id;
                   10634:             }
                   10635:             close($config);
                   10636:         }
                   10637:     }
                   10638: }
                   10639: 
1.1079    raeburn  10640: {
                   10641:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10642:     if (-e $file) {
                   10643:         my $parser = HTML::LCParser->new($file);
                   10644:         while (my $token = $parser->get_token()) {
                   10645:             if ($token->[0] eq 'S') {
                   10646:                 my $item = $token->[1];
                   10647:                 my $name = $token->[2]{'name'};
                   10648:                 my $value = $token->[2]{'value'};
                   10649:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10650:                     my $release = $parser->get_text();
                   10651:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10652:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10653:                 }
                   10654:             }
                   10655:         }
                   10656:     }
1.1073    raeburn  10657: }
                   10658: 
1.329     matthew  10659: # ------------- set up temporary directory
                   10660: {
1.1117    foxr     10661:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10662: 
1.11      www      10663: }
                   10664: 
1.794     albertel 10665: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10666: 				'compress_threshold'=> 20_000,
                   10667:  			        });
1.185     www      10668: 
1.281     www      10669: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10670: $dumpcount=0;
1.958     www      10671: $locknum=0;
1.22      www      10672: 
1.163     harris41 10673: &logtouch();
1.672     albertel 10674: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10675: $readit=1;
1.564     albertel 10676:     {
                   10677: 	use integer;
                   10678: 	my $test=(2**32)+1;
1.568     albertel 10679: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10680: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10681:     }
1.195     www      10682: }
1.1       albertel 10683: }
1.179     www      10684: 
1.1       albertel 10685: 1;
1.191     harris41 10686: __END__
                   10687: 
1.243     albertel 10688: =pod
                   10689: 
1.191     harris41 10690: =head1 NAME
                   10691: 
1.243     albertel 10692: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10693: 
                   10694: =head1 SYNOPSIS
                   10695: 
1.243     albertel 10696: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10697: 
                   10698:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10699: 
1.243     albertel 10700: Common parameters:
                   10701: 
                   10702: =over 4
                   10703: 
                   10704: =item *
                   10705: 
                   10706: $uname : an internal username (if $cname expecting a course Id specifically)
                   10707: 
                   10708: =item *
                   10709: 
                   10710: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10711: 
                   10712: =item *
                   10713: 
                   10714: $symb : a resource instance identifier
                   10715: 
                   10716: =item *
                   10717: 
                   10718: $namespace : the name of a .db file that contains the data needed or
                   10719: being set.
                   10720: 
                   10721: =back
                   10722: 
1.394     bowersj2 10723: =head1 OVERVIEW
1.191     harris41 10724: 
1.394     bowersj2 10725: lonnet provides subroutines which interact with the
                   10726: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10727: about classes, users, and resources.
1.243     albertel 10728: 
                   10729: For many of these objects you can also use this to store data about
                   10730: them or modify them in various ways.
1.191     harris41 10731: 
1.394     bowersj2 10732: =head2 Symbs
1.191     harris41 10733: 
1.394     bowersj2 10734: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10735: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10736: map, the resource number of the resource in the map, and the URL of
                   10737: the resource itself. The latter is somewhat redundant, but might help
                   10738: if maps change.
                   10739: 
                   10740: An example is
                   10741: 
                   10742:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10743: 
                   10744: The respective map entry is
                   10745: 
                   10746:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10747:   title="Problem 2">
                   10748:  </resource>
                   10749: 
                   10750: Symbs are used by the random number generator, as well as to store and
                   10751: restore data specific to a certain instance of for example a problem.
                   10752: 
                   10753: =head2 Storing And Retrieving Data
                   10754: 
                   10755: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10756: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10757: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10758: is is the non-critical message twin of cstore. These functions are for
                   10759: handlers to store a perl hash to a user's permanent data space in an
                   10760: easy manner, and to retrieve it again on another call. It is expected
                   10761: that a handler would use this once at the beginning to retrieve data,
                   10762: and then again once at the end to send only the new data back.
                   10763: 
                   10764: The data is stored in the user's data directory on the user's
                   10765: homeserver under the ID of the course.
                   10766: 
                   10767: The hash that is returned by restore will have all of the previous
                   10768: value for all of the elements of the hash.
                   10769: 
                   10770: Example:
                   10771: 
                   10772:  #creating a hash
                   10773:  my %hash;
                   10774:  $hash{'foo'}='bar';
                   10775: 
                   10776:  #storing it
                   10777:  &Apache::lonnet::cstore(\%hash);
                   10778: 
                   10779:  #changing a value
                   10780:  $hash{'foo'}='notbar';
                   10781: 
                   10782:  #adding a new value
                   10783:  $hash{'bar'}='foo';
                   10784:  &Apache::lonnet::cstore(\%hash);
                   10785: 
                   10786:  #retrieving the hash
                   10787:  my %history=&Apache::lonnet::restore();
                   10788: 
                   10789:  #print the hash
                   10790:  foreach my $key (sort(keys(%history))) {
                   10791:    print("\%history{$key} = $history{$key}");
                   10792:  }
                   10793: 
                   10794: Will print out:
1.191     harris41 10795: 
1.394     bowersj2 10796:  %history{1:foo} = bar
                   10797:  %history{1:keys} = foo:timestamp
                   10798:  %history{1:timestamp} = 990455579
                   10799:  %history{2:bar} = foo
                   10800:  %history{2:foo} = notbar
                   10801:  %history{2:keys} = foo:bar:timestamp
                   10802:  %history{2:timestamp} = 990455580
                   10803:  %history{bar} = foo
                   10804:  %history{foo} = notbar
                   10805:  %history{timestamp} = 990455580
                   10806:  %history{version} = 2
                   10807: 
                   10808: Note that the special hash entries C<keys>, C<version> and
                   10809: C<timestamp> were added to the hash. C<version> will be equal to the
                   10810: total number of versions of the data that have been stored. The
                   10811: C<timestamp> attribute will be the UNIX time the hash was
                   10812: stored. C<keys> is available in every historical section to list which
                   10813: keys were added or changed at a specific historical revision of a
                   10814: hash.
                   10815: 
                   10816: B<Warning>: do not store the hash that restore returns directly. This
                   10817: will cause a mess since it will restore the historical keys as if the
                   10818: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10819: 
1.394     bowersj2 10820: Calling convention:
1.191     harris41 10821: 
1.394     bowersj2 10822:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10823:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10824: 
1.394     bowersj2 10825: For more detailed information, see lonnet specific documentation.
1.191     harris41 10826: 
1.394     bowersj2 10827: =head1 RETURN MESSAGES
1.191     harris41 10828: 
1.394     bowersj2 10829: =over 4
1.191     harris41 10830: 
1.394     bowersj2 10831: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10832: 
1.394     bowersj2 10833: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10834: when the connection is brought back up
1.191     harris41 10835: 
1.394     bowersj2 10836: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10837: for later delivery
1.191     harris41 10838: 
1.967     bisitz   10839: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10840: 
1.394     bowersj2 10841: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10842: that was requested
1.191     harris41 10843: 
1.243     albertel 10844: =back
1.191     harris41 10845: 
1.243     albertel 10846: =head1 PUBLIC SUBROUTINES
1.191     harris41 10847: 
1.243     albertel 10848: =head2 Session Environment Functions
1.191     harris41 10849: 
1.243     albertel 10850: =over 4
1.191     harris41 10851: 
1.394     bowersj2 10852: =item * 
                   10853: X<appenv()>
1.949     raeburn  10854: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10855: the user envirnoment file, and will be restored for each access this
1.620     albertel 10856: user makes during this session, also modifies the %env for the current
1.949     raeburn  10857: process. Optional rolesarrayref - if defined contains a reference to an array
                   10858: of roles which are exempt from the restriction on modifying user.role entries 
                   10859: in the user's environment.db and in %env.    
1.191     harris41 10860: 
                   10861: =item *
1.394     bowersj2 10862: X<delenv()>
1.987     raeburn  10863: B<delenv($delthis,$regexp)>: removes all items from the session
                   10864: environment file that begin with $delthis. If the 
                   10865: optional second arg - $regexp - is true, $delthis is treated as a 
                   10866: regular expression, otherwise \Q$delthis\E is used. 
                   10867: The values are also deleted from the current processes %env.
1.191     harris41 10868: 
1.795     albertel 10869: =item * get_env_multiple($name) 
                   10870: 
                   10871: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10872: values may be defined and end up as an array ref.
                   10873: 
                   10874: returns an array of values
                   10875: 
1.243     albertel 10876: =back
                   10877: 
                   10878: =head2 User Information
1.191     harris41 10879: 
1.243     albertel 10880: =over 4
1.191     harris41 10881: 
                   10882: =item *
1.394     bowersj2 10883: X<queryauthenticate()>
                   10884: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10885: authentication scheme
                   10886: 
                   10887: =item *
1.394     bowersj2 10888: X<authenticate()>
1.1073    raeburn  10889: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10890: authenticate user from domain's lib servers (first use the current
                   10891: one). C<$upass> should be the users password.
1.1073    raeburn  10892: $checkdefauth is optional (value is 1 if a check should be made to
                   10893:    authenticate user using default authentication method, and allow
                   10894:    account creation if username does not have account in the domain).
                   10895: $clientcancheckhost is optional (value is 1 if checking whether the
                   10896:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10897: 
                   10898: =item *
1.394     bowersj2 10899: X<homeserver()>
                   10900: B<homeserver($uname,$udom)>: find the server which has
                   10901: the user's directory and files (there must be only one), this caches
                   10902: the answer, and also caches if there is a borken connection.
1.191     harris41 10903: 
                   10904: =item *
1.394     bowersj2 10905: X<idget()>
                   10906: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10907: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10908: username, and only 1 username per ID in a specific domain) (returns
                   10909: hash: id=>name,id=>name)
1.191     harris41 10910: 
                   10911: =item *
1.394     bowersj2 10912: X<idrget()>
                   10913: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10914: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10915: 
                   10916: =item *
1.394     bowersj2 10917: X<idput()>
                   10918: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10919: 
                   10920: =item *
1.394     bowersj2 10921: X<rolesinit()>
                   10922: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10923: 
                   10924: =item *
1.551     albertel 10925: X<getsection()>
                   10926: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10927: course $cname, return section name/number or '' for "not in course"
                   10928: and '-1' for "no section"
                   10929: 
                   10930: =item *
1.394     bowersj2 10931: X<userenvironment()>
                   10932: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10933: passed in @what from the requested user's environment, returns a hash
                   10934: 
1.858     raeburn  10935: =item * 
                   10936: X<userlog_query()>
1.859     albertel 10937: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10938: activity.log file. %filters defines filters applied when parsing the
                   10939: log file. These can be start or end timestamps, or the type of action
                   10940: - log to look for Login or Logout events, check for Checkin or
                   10941: Checkout, role for role selection. The response is in the form
                   10942: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10943: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10944: 
1.243     albertel 10945: =back
                   10946: 
                   10947: =head2 User Roles
                   10948: 
                   10949: =over 4
                   10950: 
                   10951: =item *
                   10952: 
1.810     raeburn  10953: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10954:  F: full access
                   10955:  U,I,K: authentication modes (cxx only)
                   10956:  '': forbidden
                   10957:  1: user needs to choose course
                   10958:  2: browse allowed
1.766     albertel 10959:  A: passphrase authentication needed
1.243     albertel 10960: 
                   10961: =item *
                   10962: 
                   10963: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10964: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10965: and course level
                   10966: 
                   10967: =item *
                   10968: 
1.988     raeburn  10969: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10970: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10971: $type is Course (default) or Community.
1.988     raeburn  10972: If $forcedefault evaluates to true, text returned will be default 
                   10973: text for $type. Otherwise, if this is a course, the text returned 
                   10974: will be a custom name for the role (if defined in the course's 
                   10975: environment).  If no custom name is defined the default is returned.
                   10976:    
1.832     raeburn  10977: =item *
                   10978: 
1.935     raeburn  10979: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10980: All arguments are optional. Returns a hash of a roles, either for
                   10981: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10982: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10983: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10984: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10985: For each key, value is set to colon-separated start and end times for
                   10986: the role.  If no username and domain are specified, will default to
1.934     raeburn  10987: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10988: of role statuses (active, future or previous), roles 
                   10989: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10990: to restrict the list of roles reported. If no array ref is 
                   10991: provided for types, will default to return only active roles.
1.834     albertel 10992: 
1.243     albertel 10993: =back
                   10994: 
                   10995: =head2 User Modification
                   10996: 
                   10997: =over 4
                   10998: 
                   10999: =item *
                   11000: 
1.957     raeburn  11001: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11002: user for the level given by URL.  Optional start and end dates (leave empty
                   11003: string or zero for "no date")
1.191     harris41 11004: 
                   11005: =item *
                   11006: 
1.243     albertel 11007: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11008: change a users, password, possible return values are: ok,
                   11009: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11010: refused
1.191     harris41 11011: 
                   11012: =item *
                   11013: 
1.243     albertel 11014: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11015: 
                   11016: =item *
                   11017: 
1.1058    raeburn  11018: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11019:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11020: 
                   11021: will update user information (firstname,middlename,lastname,generation,
                   11022: permanentemail), and if forceid is true, student/employee ID also.
                   11023: A user's institutional affiliation(s) can also be updated.
                   11024: User information fields will not be overwritten with empty entries 
                   11025: unless the field is included in the $candelete array reference.
                   11026: This array is included when a single user is modified via "Manage Users",
                   11027: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11028: 
                   11029: =item *
                   11030: 
1.286     matthew  11031: modifystudent
                   11032: 
1.957     raeburn  11033: modify a student's enrollment and identification information.
1.286     matthew  11034: The course id is resolved based on the current users environment.  
                   11035: This means the envoking user must be a course coordinator or otherwise
                   11036: associated with a course.
                   11037: 
1.297     matthew  11038: This call is essentially a wrapper for lonnet::modifyuser and
                   11039: lonnet::modify_student_enrollment
1.286     matthew  11040: 
                   11041: Inputs: 
                   11042: 
                   11043: =over 4
                   11044: 
1.957     raeburn  11045: =item B<$udom> Student's loncapa domain
1.286     matthew  11046: 
1.957     raeburn  11047: =item B<$uname> Student's loncapa login name
1.286     matthew  11048: 
1.964     bisitz   11049: =item B<$uid> Student/Employee ID
1.286     matthew  11050: 
1.957     raeburn  11051: =item B<$umode> Student's authentication mode
1.286     matthew  11052: 
1.957     raeburn  11053: =item B<$upass> Student's password
1.286     matthew  11054: 
1.957     raeburn  11055: =item B<$first> Student's first name
1.286     matthew  11056: 
1.957     raeburn  11057: =item B<$middle> Student's middle name
1.286     matthew  11058: 
1.957     raeburn  11059: =item B<$last> Student's last name
1.286     matthew  11060: 
1.957     raeburn  11061: =item B<$gene> Student's generation
1.286     matthew  11062: 
1.957     raeburn  11063: =item B<$usec> Student's section in course
1.286     matthew  11064: 
                   11065: =item B<$end> Unix time of the roles expiration
                   11066: 
                   11067: =item B<$start> Unix time of the roles start date
                   11068: 
                   11069: =item B<$forceid> If defined, allow $uid to be changed
                   11070: 
                   11071: =item B<$desiredhome> server to use as home server for student
                   11072: 
1.957     raeburn  11073: =item B<$email> Student's permanent e-mail address
                   11074: 
                   11075: =item B<$type> Type of enrollment (auto or manual)
                   11076: 
1.963     raeburn  11077: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11078: 
                   11079: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11080: 
1.963     raeburn  11081: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11082: 
1.963     raeburn  11083: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11084: 
1.963     raeburn  11085: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11086: 
1.286     matthew  11087: =back
1.297     matthew  11088: 
                   11089: =item *
                   11090: 
                   11091: modify_student_enrollment
                   11092: 
                   11093: Change a students enrollment status in a class.  The environment variable
                   11094: 'role.request.course' must be defined for this function to proceed.
                   11095: 
                   11096: Inputs:
                   11097: 
                   11098: =over 4
                   11099: 
                   11100: =item $udom, students domain
                   11101: 
                   11102: =item $uname, students name
                   11103: 
                   11104: =item $uid, students user id
                   11105: 
                   11106: =item $first, students first name
                   11107: 
                   11108: =item $middle
                   11109: 
                   11110: =item $last
                   11111: 
                   11112: =item $gene
                   11113: 
                   11114: =item $usec
                   11115: 
                   11116: =item $end
                   11117: 
                   11118: =item $start
                   11119: 
1.957     raeburn  11120: =item $type
                   11121: 
                   11122: =item $locktype
                   11123: 
                   11124: =item $cid
                   11125: 
                   11126: =item $selfenroll
                   11127: 
                   11128: =item $context
                   11129: 
1.297     matthew  11130: =back
                   11131: 
1.191     harris41 11132: 
                   11133: =item *
                   11134: 
1.243     albertel 11135: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11136: custom role; give a custom role to a user for the level given by URL.  Specify
                   11137: name and domain of role author, and role name
1.191     harris41 11138: 
                   11139: =item *
                   11140: 
1.243     albertel 11141: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11142: 
                   11143: =item *
                   11144: 
1.243     albertel 11145: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11146: 
                   11147: =back
                   11148: 
                   11149: =head2 Course Infomation
                   11150: 
                   11151: =over 4
1.191     harris41 11152: 
                   11153: =item *
                   11154: 
1.1118    foxr     11155: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11156: specified course id, including all environment settings for the
                   11157: course, the description of the course will be in the hash under the
                   11158: key 'description'
1.191     harris41 11159: 
1.1118    foxr     11160: $options is an optional parameter that if supplied is a hash reference that controls
                   11161: what how this function works.  It has the following key/values:
                   11162: 
                   11163: =over 4
                   11164: 
                   11165: =item freshen_cache
                   11166: 
                   11167: If defined, and the environment cache for the course is valid, it is 
                   11168: returned in the returned hash.
                   11169: 
                   11170: =item one_time
                   11171: 
                   11172: If defined, the last cache time is set to _now_
                   11173: 
                   11174: =item user
                   11175: 
                   11176: If defined, the supplied username is used instead of the current user.
                   11177: 
                   11178: 
                   11179: =back
                   11180: 
1.191     harris41 11181: =item *
                   11182: 
1.624     albertel 11183: resdata($name,$domain,$type,@which) : request for current parameter
                   11184: setting for a specific $type, where $type is either 'course' or 'user',
                   11185: @what should be a list of parameters to ask about. This routine caches
                   11186: answers for 5 minutes.
1.243     albertel 11187: 
1.877     foxr     11188: =item *
                   11189: 
                   11190: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11191: data base, returning a hash that is keyed by the resource name and has
                   11192: values that are the resource value.  I believe that the timestamps and
                   11193: versions are also returned.
                   11194: 
                   11195: 
1.243     albertel 11196: =back
                   11197: 
                   11198: =head2 Course Modification
                   11199: 
                   11200: =over 4
1.191     harris41 11201: 
                   11202: =item *
                   11203: 
1.243     albertel 11204: writecoursepref($courseid,%prefs) : write preferences (environment
                   11205: database) for a course
1.191     harris41 11206: 
                   11207: =item *
                   11208: 
1.1011    raeburn  11209: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11210: 
                   11211: =item *
                   11212: 
1.1038    raeburn  11213: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11214: 
                   11215: =back
                   11216: 
                   11217: =head2 Resource Subroutines
                   11218: 
                   11219: =over 4
1.191     harris41 11220: 
                   11221: =item *
                   11222: 
1.243     albertel 11223: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11224: 
                   11225: =item *
                   11226: 
1.243     albertel 11227: repcopy($filename) : subscribes to the requested file, and attempts to
                   11228: replicate from the owning library server, Might return
1.607     raeburn  11229: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11230: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11231: resource. Expects the local filesystem pathname
                   11232: (/home/httpd/html/res/....)
                   11233: 
                   11234: =back
                   11235: 
                   11236: =head2 Resource Information
                   11237: 
                   11238: =over 4
1.191     harris41 11239: 
                   11240: =item *
                   11241: 
1.243     albertel 11242: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11243: a vairety of different possible values, $varname should be a request
                   11244: string, and the other parameters can be used to specify who and what
                   11245: one is asking about.
                   11246: 
                   11247: Possible values for $varname are environment.lastname (or other item
                   11248: from the envirnment hash), user.name (or someother aspect about the
                   11249: user), resource.0.maxtries (or some other part and parameter of a
                   11250: resource)
1.204     albertel 11251: 
                   11252: =item *
                   11253: 
1.243     albertel 11254: directcondval($number) : get current value of a condition; reads from a state
                   11255: string
1.204     albertel 11256: 
                   11257: =item *
                   11258: 
1.243     albertel 11259: condval($condidx) : value of condition index based on state
1.204     albertel 11260: 
                   11261: =item *
                   11262: 
1.243     albertel 11263: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11264: resource's metadata, $what should be either a specific key, or either
                   11265: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11266: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11267: 
                   11268: this function automatically caches all requests
1.191     harris41 11269: 
                   11270: =item *
                   11271: 
1.243     albertel 11272: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11273: network of library servers; returns file handle of where SQL and regex results
                   11274: will be stored for query
1.191     harris41 11275: 
                   11276: =item *
                   11277: 
1.243     albertel 11278: symbread($filename) : return symbolic list entry (filename argument optional);
                   11279: returns the data handle
1.191     harris41 11280: 
                   11281: =item *
                   11282: 
1.243     albertel 11283: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11284: a possible symb for the URL in $thisfn, and if is an encryypted
                   11285: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11286: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11287: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11288: 
1.191     harris41 11289: 
                   11290: =item *
                   11291: 
1.243     albertel 11292: symbclean($symb) : removes versions numbers from a symb, returns the
                   11293: cleaned symb
1.191     harris41 11294: 
                   11295: =item *
                   11296: 
1.243     albertel 11297: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11298: course map, user must be in a course for it to work.
1.191     harris41 11299: 
                   11300: =item *
                   11301: 
1.243     albertel 11302: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11303: 
                   11304: =item *
                   11305: 
1.243     albertel 11306: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11307: a random seed, all arguments are optional, if they aren't sent it uses the
                   11308: environment to derive them. Note: if symb isn't sent and it can't get one
                   11309: from &symbread it will use the current time as its return value
1.191     harris41 11310: 
                   11311: =item *
                   11312: 
1.243     albertel 11313: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11314: unfakeable, receipt
1.191     harris41 11315: 
                   11316: =item *
                   11317: 
1.620     albertel 11318: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11319: 
                   11320: =item *
                   11321: 
1.243     albertel 11322: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11323: 
                   11324: =item *
                   11325: 
1.243     albertel 11326: 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 11327: 
                   11328: =item *
                   11329: 
1.243     albertel 11330: 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 11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11335: 
                   11336: =item *
                   11337: 
1.243     albertel 11338: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11339: forcing spreadsheet to reevaluate the resource scores next time.
                   11340: 
                   11341: =back
                   11342: 
                   11343: =head2 Storing/Retreiving Data
                   11344: 
                   11345: =over 4
1.191     harris41 11346: 
                   11347: =item *
                   11348: 
1.243     albertel 11349: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11350: for this url; hashref needs to be given and should be a \%hashname; the
                   11351: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11352: be derived from the env
1.191     harris41 11353: 
                   11354: =item *
                   11355: 
1.243     albertel 11356: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11357: uses critical subroutine
1.191     harris41 11358: 
                   11359: =item *
                   11360: 
1.243     albertel 11361: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11362: all args are optional
1.191     harris41 11363: 
                   11364: =item *
                   11365: 
1.717     albertel 11366: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11367: dumps the complete (or key matching regexp) namespace into a hash
                   11368: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11369: normally &store()ed into
                   11370: 
                   11371: $range should be either an integer '100' (give me the first 100
                   11372:                                            matching records)
                   11373:               or be  two integers sperated by a - with no spaces
                   11374:                  '30-50' (give me the 30th through the 50th matching
                   11375:                           records)
                   11376: 
                   11377: 
                   11378: =item *
                   11379: 
                   11380: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11381: replaces a &store() version of data with a replacement set of data
                   11382: for a particular resource in a namespace passed in the $storehash hash 
                   11383: reference
                   11384: 
                   11385: =item *
                   11386: 
1.243     albertel 11387: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11388: works very similar to store/cstore, but all data is stored in a
                   11389: temporary location and can be reset using tmpreset, $storehash should
                   11390: be a hash reference, returns nothing on success
1.191     harris41 11391: 
                   11392: =item *
                   11393: 
1.243     albertel 11394: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11395: similar to restore, but all data is stored in a temporary location and
                   11396: can be reset using tmpreset. Returns a hash of values on success,
                   11397: error string otherwise.
1.191     harris41 11398: 
                   11399: =item *
                   11400: 
1.243     albertel 11401: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11402: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11403: 
                   11404: =item *
                   11405: 
1.243     albertel 11406: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11407: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11408: 
                   11409: =item *
                   11410: 
1.243     albertel 11411: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11412: namesp ($udom and $uname are optional)
1.191     harris41 11413: 
                   11414: =item *
                   11415: 
1.702     albertel 11416: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11417: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11418: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11419: 
1.702     albertel 11420: $range should be either an integer '100' (give me the first 100
                   11421:                                            matching records)
                   11422:               or be  two integers sperated by a - with no spaces
                   11423:                  '30-50' (give me the 30th through the 50th matching
                   11424:                           records)
1.449     matthew  11425: =item *
                   11426: 
                   11427: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11428: $store can be a scalar, an array reference, or if the amount to be 
                   11429: incremented is > 1, a hash reference.
                   11430: 
                   11431: ($udom and $uname are optional)
1.191     harris41 11432: 
                   11433: =item *
                   11434: 
1.243     albertel 11435: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11436: ($udom and $uname are optional)
1.191     harris41 11437: 
                   11438: =item *
                   11439: 
1.243     albertel 11440: cput($namespace,$storehash,$udom,$uname) : critical put
                   11441: ($udom and $uname are optional)
1.191     harris41 11442: 
                   11443: =item *
                   11444: 
1.748     albertel 11445: newput($namespace,$storehash,$udom,$uname) :
                   11446: 
                   11447: Attempts to store the items in the $storehash, but only if they don't
                   11448: currently exist, if this succeeds you can be certain that you have 
                   11449: successfully created a new key value pair in the $namespace db.
                   11450: 
                   11451: 
                   11452: Args:
                   11453:  $namespace: name of database to store values to
                   11454:  $storehash: hashref to store to the db
                   11455:  $udom: (optional) domain of user containing the db
                   11456:  $uname: (optional) name of user caontaining the db
                   11457: 
                   11458: Returns:
                   11459:  'ok' -> succeeded in storing all keys of $storehash
                   11460:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11461:                         least <key> already existed in the db (other
                   11462:                         requested keys may also already exist)
1.967     bisitz   11463:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11464:  'con_lost' -> unable to contact request server
                   11465:  'refused' -> action was not allowed by remote machine
                   11466: 
                   11467: 
                   11468: =item *
                   11469: 
1.243     albertel 11470: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11471: reference filled in from namesp (encrypts the return communication)
                   11472: ($udom and $uname are optional)
1.191     harris41 11473: 
                   11474: =item *
                   11475: 
1.243     albertel 11476: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11477: critical subroutine
                   11478: 
1.806     raeburn  11479: =item *
                   11480: 
1.860     raeburn  11481: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11482: array reference filled in from namespace found in domain level on either
                   11483: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11484: 
                   11485: =item *
                   11486: 
1.860     raeburn  11487: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11488: domain level either on specified domain server ($uhome) or primary domain 
                   11489: server ($udom and $uhome are optional)
1.806     raeburn  11490: 
1.943     raeburn  11491: =item * 
                   11492: 
                   11493: get_domain_defaults($target_domain) : returns hash with defaults for
                   11494: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11495: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11496: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11497: Values are retrieved from cache (if current), or from domain's configuration.db
                   11498: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11499: or lonTabs/domain.tab. 
                   11500: 
                   11501: %domdefaults = &get_auth_defaults($target_domain);
                   11502: 
1.243     albertel 11503: =back
                   11504: 
                   11505: =head2 Network Status Functions
                   11506: 
                   11507: =over 4
1.191     harris41 11508: 
                   11509: =item *
                   11510: 
                   11511: dirlist($uri) : return directory list based on URI
                   11512: 
                   11513: =item *
                   11514: 
1.243     albertel 11515: spareserver() : find server with least workload from spare.tab
                   11516: 
1.986     foxr     11517: 
                   11518: =item *
                   11519: 
                   11520: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11521: if there is no corresponding loncapa host.
                   11522: 
1.243     albertel 11523: =back
                   11524: 
1.986     foxr     11525: 
1.243     albertel 11526: =head2 Apache Request
                   11527: 
                   11528: =over 4
1.191     harris41 11529: 
                   11530: =item *
                   11531: 
1.243     albertel 11532: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11533: localhost, posts hash
                   11534: 
                   11535: =back
                   11536: 
                   11537: =head2 Data to String to Data
                   11538: 
                   11539: =over 4
1.191     harris41 11540: 
                   11541: =item *
                   11542: 
1.243     albertel 11543: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11544: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11545: 
                   11546: =item *
                   11547: 
1.243     albertel 11548: hashref2str($hashref) : convert a hashref into a string complete with
                   11549: escaping and '=' and '&' separators, supports elements that are
                   11550: arrayrefs and hashrefs
1.191     harris41 11551: 
                   11552: =item *
                   11553: 
1.243     albertel 11554: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11555: with escaping and '&' separators, supports elements that are arrayrefs
                   11556: and hashrefs
1.191     harris41 11557: 
                   11558: =item *
                   11559: 
1.243     albertel 11560: str2hash($string) : convert string to hash using unescaping and
                   11561: splitting on '=' and '&', supports elements that are arrayrefs and
                   11562: hashrefs
1.191     harris41 11563: 
                   11564: =item *
                   11565: 
1.243     albertel 11566: str2array($string) : convert string to hash using unescaping and
                   11567: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11568: 
                   11569: =back
                   11570: 
                   11571: =head2 Logging Routines
                   11572: 
                   11573: 
                   11574: These routines allow one to make log messages in the lonnet.log and
                   11575: lonnet.perm logfiles.
1.191     harris41 11576: 
1.1119    foxr     11577: =over 4
                   11578: 
1.191     harris41 11579: =item *
                   11580: 
1.243     albertel 11581: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11582: 
                   11583: =item *
                   11584: 
1.243     albertel 11585: logthis() : append message to the normal lonnet.log file, it gets
                   11586: preiodically rolled over and deleted.
1.191     harris41 11587: 
                   11588: =item *
                   11589: 
1.243     albertel 11590: logperm() : append a permanent message to lonnet.perm.log, this log
                   11591: file never gets deleted by any automated portion of the system, only
                   11592: messages of critical importance should go in here.
                   11593: 
1.1119    foxr     11594: 
1.243     albertel 11595: =back
                   11596: 
                   11597: =head2 General File Helper Routines
                   11598: 
                   11599: =over 4
1.191     harris41 11600: 
                   11601: =item *
                   11602: 
1.481     raeburn  11603: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11604: (a) files in /uploaded
                   11605:   (i) If a local copy of the file exists - 
                   11606:       compares modification date of local copy with last-modified date for 
                   11607:       definitive version stored on home server for course. If local copy is 
                   11608:       stale, requests a new version from the home server and stores it. 
                   11609:       If the original has been removed from the home server, then local copy 
                   11610:       is unlinked.
                   11611:   (ii) If local copy does not exist -
                   11612:       requests the file from the home server and stores it. 
                   11613:   
                   11614:   If $caller is 'uploadrep':  
                   11615:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11616:     for request for files originally uploaded via DOCS. 
                   11617:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11618:   
                   11619:   Otherwise:
                   11620:      This indicates a call from the content generation phase of the request.
                   11621:      -  returns the entire contents of the file or -1.
                   11622:      
                   11623: (b) files in /res
                   11624:    - returns the entire contents of a file or -1; 
                   11625:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11626: 
1.712     albertel 11627: 
                   11628: =item *
                   11629: 
                   11630: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11631:                   reference
                   11632: 
                   11633: returns either a stat() list of data about the file or an empty list
                   11634: if the file doesn't exist or couldn't find out about it (connection
                   11635: problems or user unknown)
                   11636: 
1.191     harris41 11637: =item *
                   11638: 
1.243     albertel 11639: filelocation($dir,$file) : returns file system location of a file
                   11640: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11641: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11642: and a file of ../bob will become /a/bob)
1.191     harris41 11643: 
                   11644: =item *
                   11645: 
                   11646: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11647: filelocation except for hrefs
                   11648: 
                   11649: =item *
                   11650: 
                   11651: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11652: 
1.243     albertel 11653: =back
                   11654: 
1.608     albertel 11655: =head2 Usererfile file routines (/uploaded*)
                   11656: 
                   11657: =over 4
                   11658: 
                   11659: =item *
                   11660: 
                   11661: userfileupload(): main rotine for putting a file in a user or course's
                   11662:                   filespace, arguments are,
                   11663: 
1.620     albertel 11664:  formname - required - this is the name of the element in $env where the
1.608     albertel 11665:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11666:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11667:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11668:  context - if coursedoc, store the file in the course of the active role
                   11669:              of the current user; 
                   11670:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11671:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11672:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11673:          if undefined, it will be placed in "unknown"
                   11674: 
                   11675:  (This routine calls clean_filename() to remove any dangerous
                   11676:  characters from the filename, and then calls finuserfileupload() to
                   11677:  complete the transaction)
                   11678: 
                   11679:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11680:  and /adm/notfound.html if unsuccessful
                   11681: 
                   11682: =item *
                   11683: 
                   11684: clean_filename(): routine for cleaing a filename up for storage in
                   11685:                  userfile space, argument is:
                   11686: 
                   11687:  filename - proposed filename
                   11688: 
                   11689: returns: the new clean filename
                   11690: 
                   11691: =item *
                   11692: 
1.1090    raeburn  11693: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11694: userspace, probably shouldn't be called directly
                   11695: 
                   11696:   docuname: username or courseid of destination for the file
                   11697:   docudom: domain of user/course of destination for the file
                   11698:   formname: same as for userfileupload()
1.1090    raeburn  11699:   fname: filename (including subdirectories) for the file
                   11700:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11701:   allfiles: reference to hash used to store objects found by parser
                   11702:   codebase: reference to hash used for codebases of java objects found by parser
                   11703:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11704:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11705:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11706:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11707:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11708:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11709:   mimetype: reference to scalar to accommodate mime type determined
                   11710:             from File::MMagic if $parser = parse.
1.608     albertel 11711: 
                   11712:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11713:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11714:  was 'overwrite').
                   11715:  
1.608     albertel 11716: 
                   11717: =item *
                   11718: 
                   11719: renameuserfile(): renames an existing userfile to a new name
                   11720: 
                   11721:   Args:
                   11722:    docuname: username or courseid of destination for the file
                   11723:    docudom: domain of user/course of destination for the file
                   11724:    old: current file name (including any subdirs under userfiles)
                   11725:    new: desired file name (including any subdirs under userfiles)
                   11726: 
                   11727: =item *
                   11728: 
                   11729: mkdiruserfile(): creates a directory is a userfiles dir
                   11730: 
                   11731:   Args:
                   11732:    docuname: username or courseid of destination for the file
                   11733:    docudom: domain of user/course of destination for the file
                   11734:    dir: dir to create (including any subdirs under userfiles)
                   11735: 
                   11736: =item *
                   11737: 
                   11738: removeuserfile(): removes a file that exists in userfiles
                   11739: 
                   11740:   Args:
                   11741:    docuname: username or courseid of destination for the file
                   11742:    docudom: domain of user/course of destination for the file
                   11743:    fname: filname to delete (including any subdirs under userfiles)
                   11744: 
                   11745: =item *
                   11746: 
                   11747: removeuploadedurl(): convience function for removeuserfile()
                   11748: 
                   11749:   Args:
                   11750:    url:  a full /uploaded/... url to delete
                   11751: 
1.747     albertel 11752: =item * 
                   11753: 
                   11754: get_portfile_permissions():
                   11755:   Args:
                   11756:     domain: domain of user or course contain the portfolio files
                   11757:     user: name of user or num of course contain the portfolio files
                   11758:   Returns:
                   11759:     hashref of a dump of the proper file_permissions.db
                   11760:    
                   11761: 
                   11762: =item * 
                   11763: 
                   11764: get_access_controls():
                   11765: 
                   11766: Args:
                   11767:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11768:   group: (optional) the group you want the files associated with
                   11769:   file: (optional) the file you want access info on
                   11770: 
                   11771: Returns:
1.749     raeburn  11772:     a hash (keys are file names) of hashes containing
                   11773:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11774:         values are XML containing access control settings (see below) 
1.747     albertel 11775: 
                   11776: Internal notes:
                   11777: 
1.749     raeburn  11778:  access controls are stored in file_permissions.db as key=value pairs.
                   11779:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11780:         where scope -> public,guest,course,group,domains or users.
                   11781:               end -> UNIX time for end of access (0 -> no end date)
                   11782:               start -> UNIX time for start of access
                   11783: 
                   11784:     value -> XML description of access control
                   11785:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11786:             <start></start>
                   11787:             <end></end>
                   11788: 
                   11789:             <password></password>  for scope type = guest
                   11790: 
                   11791:             <domain></domain>     for scope type = course or group
                   11792:             <number></number>
                   11793:             <roles id="">
                   11794:              <role></role>
                   11795:              <access></access>
                   11796:              <section></section>
                   11797:              <group></group>
                   11798:             </roles>
                   11799: 
                   11800:             <dom></dom>         for scope type = domains
                   11801: 
                   11802:             <users>             for scope type = users
                   11803:              <user>
                   11804:               <uname></uname>
                   11805:               <udom></udom>
                   11806:              </user>
                   11807:             </users>
                   11808:            </scope> 
                   11809:               
                   11810:  Access data is also aggregated for each file in an additional key=value pair:
                   11811:  key -> path to file/file_name\0accesscontrol 
                   11812:  value -> reference to hash
                   11813:           hash contains key = value pairs
                   11814:           where key = uniqueID:scope_end_start
                   11815:                 value = UNIX time record was last updated
                   11816: 
                   11817:           Used to improve speed of look-ups of access controls for each file.  
                   11818:  
                   11819:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11820: 
                   11821: modify_access_controls():
                   11822: 
                   11823: Modifies access controls for a portfolio file
                   11824: Args
                   11825: 1. file name
                   11826: 2. reference to hash of required changes,
                   11827: 3. domain
                   11828: 4. username
                   11829:   where domain,username are the domain of the portfolio owner 
                   11830:   (either a user or a course) 
                   11831: 
                   11832: Returns:
                   11833: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11834: 2. result of deletions ('ok' or 'error', with error message).
                   11835: 3. reference to hash of any new or updated access controls.
                   11836: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11837:    key = integer (inbound ID)
                   11838:    value = uniqueID  
1.747     albertel 11839: 
1.608     albertel 11840: =back
                   11841: 
1.243     albertel 11842: =head2 HTTP Helper Routines
                   11843: 
                   11844: =over 4
                   11845: 
1.191     harris41 11846: =item *
                   11847: 
                   11848: escape() : unpack non-word characters into CGI-compatible hex codes
                   11849: 
                   11850: =item *
                   11851: 
                   11852: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11853: 
1.243     albertel 11854: =back
                   11855: 
                   11856: =head1 PRIVATE SUBROUTINES
                   11857: 
                   11858: =head2 Underlying communication routines (Shouldn't call)
                   11859: 
                   11860: =over 4
                   11861: 
                   11862: =item *
                   11863: 
                   11864: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11865: 
                   11866: =item *
                   11867: 
                   11868: reply() : uses subreply to send a message to remote machine, logs all failures
                   11869: 
                   11870: =item *
                   11871: 
                   11872: critical() : passes a critical message to another server; if cannot
                   11873: get through then place message in connection buffer directory and
                   11874: returns con_delayed, if incapable of saving message, returns
                   11875: con_failed
                   11876: 
                   11877: =item *
                   11878: 
                   11879: reconlonc() : tries to reconnect lonc client processes.
                   11880: 
                   11881: =back
                   11882: 
                   11883: =head2 Resource Access Logging
                   11884: 
                   11885: =over 4
                   11886: 
                   11887: =item *
                   11888: 
                   11889: flushcourselogs() : flush (save) buffer logs and access logs
                   11890: 
                   11891: =item *
                   11892: 
                   11893: courselog($what) : save message for course in hash
                   11894: 
                   11895: =item *
                   11896: 
                   11897: courseacclog($what) : save message for course using &courselog().  Perform
                   11898: special processing for specific resource types (problems, exams, quizzes, etc).
                   11899: 
1.191     harris41 11900: =item *
                   11901: 
                   11902: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11903: as a PerlChildExitHandler
1.243     albertel 11904: 
                   11905: =back
                   11906: 
                   11907: =head2 Other
                   11908: 
                   11909: =over 4
                   11910: 
                   11911: =item *
                   11912: 
                   11913: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11914: 
                   11915: =back
                   11916: 
                   11917: =cut
1.877     foxr     11918: 

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