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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1128  ! raeburn     4: # $Id: lonnet.pm,v 1.1127 2011/08/09 00:54:48 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) = @_;
1.1126    raeburn  1145:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1146:     my @hosts = &current_machine_ids();
                   1147:     foreach my $lonhost (@hosts) {
                   1148:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1149:             $dom_in_use = $dom;
                   1150:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1151:             last;
                   1152:         }
                   1153:     }
1.1126    raeburn  1154:     if ($dom_in_use ne '') {
                   1155:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1156:     }
                   1157:     if (ref($result) ne 'HASH') {
                   1158:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1159:         $dom_in_use = &host_domain($lonhost_in_use);
                   1160:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1161:         if (ref($result) ne 'HASH') {
                   1162:             $result = \%spareid;
                   1163:         }
                   1164:     }
                   1165:     return $result;
                   1166: }
                   1167: 
                   1168: sub spares_for_offload  {
                   1169:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1170:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1171:     if (defined($cached)) {
                   1172:         return $result;
                   1173:     } else {
1.1126    raeburn  1174:         my $cachetime = 60*60*24;
                   1175:         my %domconfig =
                   1176:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1177:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1178:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1179:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1180:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1181:                 }
                   1182:             }
                   1183:         }
                   1184:     }
1.1126    raeburn  1185:     return;
1.1123    raeburn  1186: }
                   1187: 
1.1127    raeburn  1188: sub internet_dom_servers {
                   1189:     my ($dom) = @_;
                   1190:     my (%uniqservers,%servers);
                   1191:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1192:     my @machinedoms = &machine_domains($primaryserver);
                   1193:     foreach my $mdom (@machinedoms) {
                   1194:         my %currservers = %servers;
                   1195:         my %server = &get_servers($mdom);
                   1196:         %servers = (%currservers,%server);
                   1197:     }
                   1198:     my %by_hostname;
                   1199:     foreach my $id (keys(%servers)) {
                   1200:         push(@{$by_hostname{$servers{$id}}},$id);
                   1201:     }
                   1202:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1203:         if (@{$by_hostname{$hostname}} > 1) {
                   1204:             my $match = 0;
                   1205:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1206:                 if (&host_domain($id) eq $dom) {
                   1207:                     $uniqservers{$id} = $hostname;
                   1208:                     $match = 1;
                   1209:                 }
                   1210:             }
                   1211:             unless ($match) {
                   1212:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1213:             }
                   1214:         } else {
                   1215:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1216:         }
                   1217:     }
                   1218:     return %uniqservers;
                   1219: }
                   1220: 
1.1       albertel 1221: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1222: 
1.599     albertel 1223: my %homecache;
1.1       albertel 1224: sub homeserver {
1.230     stredwic 1225:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1226:     my $index="$uname:$udom";
1.426     albertel 1227: 
1.599     albertel 1228:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1229: 
                   1230:     my %servers = &get_servers($udom,'library');
                   1231:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1232:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1233: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1234: 
                   1235: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1236: 	if ($answer eq 'found') {
                   1237: 	    delete($badServerCache{$tryserver}); 
                   1238: 	    return $homecache{$index}=$tryserver;
                   1239: 	} elsif ($answer eq 'no_host') {
                   1240: 	    $badServerCache{$tryserver}=1;
                   1241: 	}
1.1       albertel 1242:     }    
                   1243:     return 'no_host';
1.70      www      1244: }
                   1245: 
                   1246: # ------------------------------------- Find the usernames behind a list of IDs
                   1247: 
                   1248: sub idget {
                   1249:     my ($udom,@ids)=@_;
                   1250:     my %returnhash=();
                   1251:     
1.841     albertel 1252:     my %servers = &get_servers($udom,'library');
                   1253:     foreach my $tryserver (keys(%servers)) {
                   1254: 	my $idlist=join('&',@ids);
                   1255: 	$idlist=~tr/A-Z/a-z/; 
                   1256: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1257: 	my @answer=();
                   1258: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1259: 	    @answer=split(/\&/,$reply);
                   1260: 	}                    ;
                   1261: 	my $i;
                   1262: 	for ($i=0;$i<=$#ids;$i++) {
                   1263: 	    if ($answer[$i]) {
                   1264: 		$returnhash{$ids[$i]}=$answer[$i];
                   1265: 	    } 
                   1266: 	}
                   1267:     } 
1.70      www      1268:     return %returnhash;
                   1269: }
                   1270: 
                   1271: # ------------------------------------- Find the IDs behind a list of usernames
                   1272: 
                   1273: sub idrget {
                   1274:     my ($udom,@unames)=@_;
                   1275:     my %returnhash=();
1.800     albertel 1276:     foreach my $uname (@unames) {
                   1277:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1278:     }
1.70      www      1279:     return %returnhash;
                   1280: }
                   1281: 
                   1282: # ------------------------------- Store away a list of names and associated IDs
                   1283: 
                   1284: sub idput {
                   1285:     my ($udom,%ids)=@_;
                   1286:     my %servers=();
1.800     albertel 1287:     foreach my $uname (keys(%ids)) {
                   1288: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1289:         my $uhom=&homeserver($uname,$udom);
1.70      www      1290:         if ($uhom ne 'no_host') {
1.800     albertel 1291:             my $id=&escape($ids{$uname});
1.70      www      1292:             $id=~tr/A-Z/a-z/;
1.800     albertel 1293:             my $esc_unam=&escape($uname);
1.70      www      1294: 	    if ($servers{$uhom}) {
1.800     albertel 1295: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1296:             } else {
1.800     albertel 1297:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1298:             }
                   1299:         }
1.191     harris41 1300:     }
1.800     albertel 1301:     foreach my $server (keys(%servers)) {
                   1302:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1303:     }
1.344     www      1304: }
                   1305: 
1.1023    raeburn  1306: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1307: sub dump_dom {
1.1023    raeburn  1308:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1309:     if (!$udom) {
                   1310:         $udom=$env{'user.domain'};
                   1311:     }
                   1312:     my %returnhash;
1.1023    raeburn  1313:     if ($udom) {
                   1314:         my $uname = &get_domainconfiguser($udom);
                   1315:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1316:     }
                   1317:     return %returnhash;
                   1318: }
                   1319: 
1.1023    raeburn  1320: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1321: 
                   1322: sub get_dom {
1.860     raeburn  1323:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1324:     my $items='';
                   1325:     foreach my $item (@$storearr) {
                   1326:         $items.=&escape($item).'&';
                   1327:     }
                   1328:     $items=~s/\&$//;
1.860     raeburn  1329:     if (!$udom) {
                   1330:         $udom=$env{'user.domain'};
                   1331:         if (defined(&domain($udom,'primary'))) {
                   1332:             $uhome=&domain($udom,'primary');
                   1333:         } else {
1.874     albertel 1334:             undef($uhome);
1.860     raeburn  1335:         }
                   1336:     } else {
                   1337:         if (!$uhome) {
                   1338:             if (defined(&domain($udom,'primary'))) {
                   1339:                 $uhome=&domain($udom,'primary');
                   1340:             }
                   1341:         }
                   1342:     }
                   1343:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1344:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1345:         my %returnhash;
1.875     albertel 1346:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1347:             return %returnhash;
                   1348:         }
1.806     raeburn  1349:         my @pairs=split(/\&/,$rep);
                   1350:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1351:             return @pairs;
                   1352:         }
                   1353:         my $i=0;
                   1354:         foreach my $item (@$storearr) {
                   1355:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1356:             $i++;
                   1357:         }
                   1358:         return %returnhash;
                   1359:     } else {
1.880     banghart 1360:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1361:     }
                   1362: }
                   1363: 
                   1364: # -------------------------------------------- put items in domain db files 
                   1365: 
                   1366: sub put_dom {
1.860     raeburn  1367:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1368:     if (!$udom) {
                   1369:         $udom=$env{'user.domain'};
                   1370:         if (defined(&domain($udom,'primary'))) {
                   1371:             $uhome=&domain($udom,'primary');
                   1372:         } else {
1.874     albertel 1373:             undef($uhome);
1.860     raeburn  1374:         }
                   1375:     } else {
                   1376:         if (!$uhome) {
                   1377:             if (defined(&domain($udom,'primary'))) {
                   1378:                 $uhome=&domain($udom,'primary');
                   1379:             }
                   1380:         }
                   1381:     } 
                   1382:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1383:         my $items='';
                   1384:         foreach my $item (keys(%$storehash)) {
                   1385:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1386:         }
                   1387:         $items=~s/\&$//;
                   1388:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1389:     } else {
1.860     raeburn  1390:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1391:     }
                   1392: }
                   1393: 
1.1023    raeburn  1394: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1395: sub newput_dom {
1.1023    raeburn  1396:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1397:     my $result;
                   1398:     if (!$udom) {
                   1399:         $udom=$env{'user.domain'};
                   1400:     }
1.1023    raeburn  1401:     if ($udom) {
                   1402:         my $uname = &get_domainconfiguser($udom);
                   1403:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1404:     }
                   1405:     return $result;
                   1406: }
                   1407: 
1.1023    raeburn  1408: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1409: sub del_dom {
1.1023    raeburn  1410:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1411:     if (ref($storearr) eq 'ARRAY') {
                   1412:         if (!$udom) {
                   1413:             $udom=$env{'user.domain'};
                   1414:         }
1.1023    raeburn  1415:         if ($udom) {
                   1416:             my $uname = &get_domainconfiguser($udom); 
                   1417:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1418:         }
                   1419:     }
                   1420: }
                   1421: 
1.1023    raeburn  1422: # ----------------------------------construct domainconfig user for a domain 
                   1423: sub get_domainconfiguser {
                   1424:     my ($udom) = @_;
                   1425:     return $udom.'-domainconfig';
                   1426: }
                   1427: 
1.837     raeburn  1428: sub retrieve_inst_usertypes {
                   1429:     my ($udom) = @_;
                   1430:     my (%returnhash,@order);
1.989     raeburn  1431:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1432:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1433:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1434:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1435:         @order = @{$domdefs{'inststatusorder'}};
                   1436:     } else {
                   1437:         if (defined(&domain($udom,'primary'))) {
                   1438:             my $uhome=&domain($udom,'primary');
                   1439:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1440:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1441:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1442:                 return (\%returnhash,\@order);
                   1443:             }
                   1444:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1445:             my @pairs=split(/\&/,$hashitems);
                   1446:             foreach my $item (@pairs) {
                   1447:                 my ($key,$value)=split(/=/,$item,2);
                   1448:                 $key = &unescape($key);
                   1449:                 next if ($key =~ /^error: 2 /);
                   1450:                 $returnhash{$key}=&thaw_unescape($value);
                   1451:             }
                   1452:             my @esc_order = split(/\&/,$orderitems);
                   1453:             foreach my $item (@esc_order) {
                   1454:                 push(@order,&unescape($item));
                   1455:             }
                   1456:         } else {
                   1457:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1458:         }
                   1459:     }
                   1460:     return (\%returnhash,\@order);
                   1461: }
                   1462: 
1.868     raeburn  1463: sub is_domainimage {
                   1464:     my ($url) = @_;
                   1465:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1466:         if (&domain($1) ne '') {
                   1467:             return '1';
                   1468:         }
                   1469:     }
                   1470:     return;
                   1471: }
                   1472: 
1.899     raeburn  1473: sub inst_directory_query {
                   1474:     my ($srch) = @_;
                   1475:     my $udom = $srch->{'srchdomain'};
                   1476:     my %results;
                   1477:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1478:     my $outcome;
1.899     raeburn  1479:     if ($homeserver ne '') {
1.904     albertel 1480: 	my $queryid=&reply("querysend:instdirsearch:".
                   1481: 			   &escape($srch->{'srchby'}).':'.
                   1482: 			   &escape($srch->{'srchterm'}).':'.
                   1483: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1484: 	my $host=&hostname($homeserver);
                   1485: 	if ($queryid !~/^\Q$host\E\_/) {
                   1486: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1487: 	    return;
                   1488: 	}
                   1489: 	my $response = &get_query_reply($queryid);
                   1490: 	my $maxtries = 5;
                   1491: 	my $tries = 1;
                   1492: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1493: 	    $response = &get_query_reply($queryid);
                   1494: 	    $tries ++;
                   1495: 	}
                   1496: 
                   1497:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1498:             if ($response eq 'unavailable') {
                   1499:                 $outcome = $response;
                   1500:             } else {
                   1501:                 $outcome = 'ok';
                   1502:                 my @matches = split(/\n/,$response);
                   1503:                 foreach my $match (@matches) {
                   1504:                     my ($key,$value) = split(/=/,$match);
                   1505:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1506:                 }
1.899     raeburn  1507:             }
                   1508:         }
                   1509:     }
1.909     raeburn  1510:     return ($outcome,%results);
1.899     raeburn  1511: }
                   1512: 
                   1513: sub usersearch {
                   1514:     my ($srch) = @_;
                   1515:     my $dom = $srch->{'srchdomain'};
                   1516:     my %results;
                   1517:     my %libserv = &all_library();
                   1518:     my $query = 'usersearch';
                   1519:     foreach my $tryserver (keys(%libserv)) {
                   1520:         if (&host_domain($tryserver) eq $dom) {
                   1521:             my $host=&hostname($tryserver);
                   1522:             my $queryid=
1.911     raeburn  1523:                 &reply("querysend:".&escape($query).':'.
                   1524:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1525:                        &escape($srch->{'srchtype'}).':'.
                   1526:                        &escape($srch->{'srchterm'}),$tryserver);
                   1527:             if ($queryid !~/^\Q$host\E\_/) {
                   1528:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1529:                 next;
1.899     raeburn  1530:             }
                   1531:             my $reply = &get_query_reply($queryid);
                   1532:             my $maxtries = 1;
                   1533:             my $tries = 1;
                   1534:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1535:                 $reply = &get_query_reply($queryid);
                   1536:                 $tries ++;
                   1537:             }
                   1538:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1539:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1540:             } else {
1.911     raeburn  1541:                 my @matches;
                   1542:                 if ($reply =~ /\n/) {
                   1543:                     @matches = split(/\n/,$reply);
                   1544:                 } else {
                   1545:                     @matches = split(/\&/,$reply);
                   1546:                 }
1.899     raeburn  1547:                 foreach my $match (@matches) {
                   1548:                     my ($uname,$udom,%userhash);
1.911     raeburn  1549:                     foreach my $entry (split(/:/,$match)) {
                   1550:                         my ($key,$value) =
                   1551:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1552:                         $userhash{$key} = $value;
                   1553:                         if ($key eq 'username') {
                   1554:                             $uname = $value;
                   1555:                         } elsif ($key eq 'domain') {
                   1556:                             $udom = $value;
1.911     raeburn  1557:                         }
1.899     raeburn  1558:                     }
                   1559:                     $results{$uname.':'.$udom} = \%userhash;
                   1560:                 }
                   1561:             }
                   1562:         }
                   1563:     }
                   1564:     return %results;
                   1565: }
                   1566: 
1.912     raeburn  1567: sub get_instuser {
                   1568:     my ($udom,$uname,$id) = @_;
                   1569:     my $homeserver = &domain($udom,'primary');
                   1570:     my ($outcome,%results);
                   1571:     if ($homeserver ne '') {
                   1572:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1573:                            &escape($id).':'.&escape($udom),$homeserver);
                   1574:         my $host=&hostname($homeserver);
                   1575:         if ($queryid !~/^\Q$host\E\_/) {
                   1576:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1577:             return;
                   1578:         }
                   1579:         my $response = &get_query_reply($queryid);
                   1580:         my $maxtries = 5;
                   1581:         my $tries = 1;
                   1582:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1583:             $response = &get_query_reply($queryid);
                   1584:             $tries ++;
                   1585:         }
                   1586:         if (!&error($response) && $response ne 'refused') {
                   1587:             if ($response eq 'unavailable') {
                   1588:                 $outcome = $response;
                   1589:             } else {
                   1590:                 $outcome = 'ok';
                   1591:                 my @matches = split(/\n/,$response);
                   1592:                 foreach my $match (@matches) {
                   1593:                     my ($key,$value) = split(/=/,$match);
                   1594:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1595:                 }
                   1596:             }
                   1597:         }
                   1598:     }
                   1599:     my %userinfo;
                   1600:     if (ref($results{$uname}) eq 'HASH') {
                   1601:         %userinfo = %{$results{$uname}};
                   1602:     } 
                   1603:     return ($outcome,%userinfo);
                   1604: }
                   1605: 
                   1606: sub inst_rulecheck {
1.923     raeburn  1607:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1608:     my %returnhash;
                   1609:     if ($udom ne '') {
                   1610:         if (ref($rules) eq 'ARRAY') {
                   1611:             @{$rules} = map {&escape($_);} (@{$rules});
                   1612:             my $rulestr = join(':',@{$rules});
                   1613:             my $homeserver=&domain($udom,'primary');
                   1614:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1615:                 my $response;
                   1616:                 if ($item eq 'username') {                
                   1617:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1618:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1619:                                               $homeserver));
1.923     raeburn  1620:                 } elsif ($item eq 'id') {
                   1621:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1622:                                               ':'.&escape($id).':'.$rulestr,
                   1623:                                               $homeserver));
1.945     raeburn  1624:                 } elsif ($item eq 'selfcreate') {
                   1625:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1626:                                                &escape($udom).':'.&escape($uname).
                   1627:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1628:                 }
1.912     raeburn  1629:                 if ($response ne 'refused') {
                   1630:                     my @pairs=split(/\&/,$response);
                   1631:                     foreach my $item (@pairs) {
                   1632:                         my ($key,$value)=split(/=/,$item,2);
                   1633:                         $key = &unescape($key);
                   1634:                         next if ($key =~ /^error: 2 /);
                   1635:                         $returnhash{$key}=&thaw_unescape($value);
                   1636:                     }
                   1637:                 }
                   1638:             }
                   1639:         }
                   1640:     }
                   1641:     return %returnhash;
                   1642: }
                   1643: 
                   1644: sub inst_userrules {
1.923     raeburn  1645:     my ($udom,$check) = @_;
1.912     raeburn  1646:     my (%ruleshash,@ruleorder);
                   1647:     if ($udom ne '') {
                   1648:         my $homeserver=&domain($udom,'primary');
                   1649:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1650:             my $response;
                   1651:             if ($check eq 'id') {
                   1652:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1653:                                  $homeserver);
1.943     raeburn  1654:             } elsif ($check eq 'email') {
                   1655:                 $response=&reply('instemailrules:'.&escape($udom),
                   1656:                                  $homeserver);
1.923     raeburn  1657:             } else {
                   1658:                 $response=&reply('instuserrules:'.&escape($udom),
                   1659:                                  $homeserver);
                   1660:             }
1.912     raeburn  1661:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1662:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1663:                 ($response ne 'no_such_host')) {
                   1664:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1665:                 my @pairs=split(/\&/,$hashitems);
                   1666:                 foreach my $item (@pairs) {
                   1667:                     my ($key,$value)=split(/=/,$item,2);
                   1668:                     $key = &unescape($key);
                   1669:                     next if ($key =~ /^error: 2 /);
                   1670:                     $ruleshash{$key}=&thaw_unescape($value);
                   1671:                 }
                   1672:                 my @esc_order = split(/\&/,$orderitems);
                   1673:                 foreach my $item (@esc_order) {
                   1674:                     push(@ruleorder,&unescape($item));
                   1675:                 }
                   1676:             }
                   1677:         }
                   1678:     }
                   1679:     return (\%ruleshash,\@ruleorder);
                   1680: }
                   1681: 
1.976     raeburn  1682: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1683: 
                   1684: sub get_domain_defaults {
                   1685:     my ($domain) = @_;
                   1686:     my $cachetime = 60*60*24;
                   1687:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1688:     if (defined($cached)) {
                   1689:         if (ref($result) eq 'HASH') {
                   1690:             return %{$result};
                   1691:         }
                   1692:     }
                   1693:     my %domdefaults;
                   1694:     my %domconfig =
1.989     raeburn  1695:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1696:                                   'requestcourses','inststatus',
1.1073    raeburn  1697:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1698:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1699:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1700:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1701:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1702:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1703:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1704:     } else {
                   1705:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1706:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1707:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1708:     }
1.976     raeburn  1709:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1710:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1711:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1712:         } else {
                   1713:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1714:         } 
                   1715:         my @usertools = ('aboutme','blog','portfolio');
                   1716:         foreach my $item (@usertools) {
                   1717:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1718:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1719:             }
                   1720:         }
                   1721:     }
1.985     raeburn  1722:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1723:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1724:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1725:         }
                   1726:     }
1.989     raeburn  1727:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1728:         foreach my $item ('inststatustypes','inststatusorder') {
                   1729:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1730:         }
                   1731:     }
1.1047    raeburn  1732:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1733:         foreach my $item ('canuse_pdfforms') {
                   1734:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1735:         }
                   1736:     }
1.1073    raeburn  1737:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1738:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1739:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1740:         }
                   1741:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1742:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1743:         }
                   1744:     }
1.943     raeburn  1745:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1746:                                   $cachetime);
                   1747:     return %domdefaults;
                   1748: }
                   1749: 
1.344     www      1750: # --------------------------------------------------- Assign a key to a student
                   1751: 
                   1752: sub assign_access_key {
1.364     www      1753: #
                   1754: # a valid key looks like uname:udom#comments
                   1755: # comments are being appended
                   1756: #
1.498     www      1757:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1758:     $kdom=
1.620     albertel 1759:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1760:     $knum=
1.620     albertel 1761:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1762:     $cdom=
1.620     albertel 1763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1764:     $cnum=
1.620     albertel 1765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1766:     $udom=$env{'user.name'} unless (defined($udom));
                   1767:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1768:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1769:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1770:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1771:                                                   # assigned to this person
                   1772:                                                   # - this should not happen,
1.345     www      1773:                                                   # unless something went wrong
                   1774:                                                   # the first time around
                   1775: # ready to assign
1.364     www      1776:         $logentry=$1.'; '.$logentry;
1.496     www      1777:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1778:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1779: # key now belongs to user
1.346     www      1780: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1781:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1782:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1783:                 return 'ok';
                   1784:             } else {
                   1785:                 return 
                   1786:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1787: 	    }
                   1788:         } else {
                   1789:             return 'error: Could not assign key, try again later.';
                   1790:         }
1.364     www      1791:     } elsif (!$existing{$ckey}) {
1.345     www      1792: # the key does not exist
                   1793: 	return 'error: The key does not exist';
                   1794:     } else {
                   1795: # the key is somebody else's
                   1796: 	return 'error: The key is already in use';
                   1797:     }
1.344     www      1798: }
                   1799: 
1.364     www      1800: # ------------------------------------------ put an additional comment on a key
                   1801: 
                   1802: sub comment_access_key {
                   1803: #
                   1804: # a valid key looks like uname:udom#comments
                   1805: # comments are being appended
                   1806: #
                   1807:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1808:     $cdom=
1.620     albertel 1809:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1810:     $cnum=
1.620     albertel 1811:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1812:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1813:     if ($existing{$ckey}) {
                   1814:         $existing{$ckey}.='; '.$logentry;
                   1815: # ready to assign
1.367     www      1816:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1817:                                                  $cdom,$cnum) eq 'ok') {
                   1818: 	    return 'ok';
                   1819:         } else {
                   1820: 	    return 'error: Count not store comment.';
                   1821:         }
                   1822:     } else {
                   1823: # the key does not exist
                   1824: 	return 'error: The key does not exist';
                   1825:     }
                   1826: }
                   1827: 
1.344     www      1828: # ------------------------------------------------------ Generate a set of keys
                   1829: 
                   1830: sub generate_access_keys {
1.364     www      1831:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1832:     $cdom=
1.620     albertel 1833:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1834:     $cnum=
1.620     albertel 1835:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1836:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1837:     unless (($cdom) && ($cnum)) { return 0; }
                   1838:     if ($number>10000) { return 0; }
                   1839:     sleep(2); # make sure don't get same seed twice
                   1840:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1841:     my $total=0;
                   1842:     for (my $i=1;$i<=$number;$i++) {
                   1843:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1844:                   sprintf("%lx",int(100000*rand)).'-'.
                   1845:                   sprintf("%lx",int(100000*rand));
                   1846:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1847:        $newkey=~s/0/h/g; # and also 0 and O
                   1848:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1849:        if ($existing{$newkey}) {
                   1850:            $i--;
                   1851:        } else {
1.364     www      1852: 	  if (&put('accesskeys',
                   1853:               { $newkey => '# generated '.localtime().
1.620     albertel 1854:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1855:                            '; '.$logentry },
                   1856: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1857:               $total++;
                   1858: 	  }
                   1859:        }
                   1860:     }
1.620     albertel 1861:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1862:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1863:     return $total;
                   1864: }
                   1865: 
                   1866: # ------------------------------------------------------- Validate an accesskey
                   1867: 
                   1868: sub validate_access_key {
                   1869:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1870:     $cdom=
1.620     albertel 1871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1872:     $cnum=
1.620     albertel 1873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1874:     $udom=$env{'user.domain'} unless (defined($udom));
                   1875:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1876:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1877:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1878: }
                   1879: 
                   1880: # ------------------------------------- Find the section of student in a course
1.652     albertel 1881: sub devalidate_getsection_cache {
                   1882:     my ($udom,$unam,$courseid)=@_;
                   1883:     my $hashid="$udom:$unam:$courseid";
                   1884:     &devalidate_cache_new('getsection',$hashid);
                   1885: }
1.298     matthew  1886: 
1.815     albertel 1887: sub courseid_to_courseurl {
                   1888:     my ($courseid) = @_;
                   1889:     #already url style courseid
                   1890:     return $courseid if ($courseid =~ m{^/});
                   1891: 
                   1892:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1893: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1894: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1895: 	return "/$cdom/$cnum";
                   1896:     }
                   1897: 
                   1898:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1899:     if (exists($courseinfo{'num'})) {
                   1900: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1901:     }
                   1902: 
                   1903:     return undef;
                   1904: }
                   1905: 
1.298     matthew  1906: sub getsection {
                   1907:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1908:     my $cachetime=1800;
1.551     albertel 1909: 
                   1910:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1911:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1912:     if (defined($cached)) { return $result; }
                   1913: 
1.298     matthew  1914:     my %Pending; 
                   1915:     my %Expired;
                   1916:     #
                   1917:     # Each role can either have not started yet (pending), be active, 
                   1918:     #    or have expired.
                   1919:     #
                   1920:     # If there is an active role, we are done.
                   1921:     #
                   1922:     # If there is more than one role which has not started yet, 
                   1923:     #     choose the one which will start sooner
                   1924:     # If there is one role which has not started yet, return it.
                   1925:     #
                   1926:     # If there is more than one expired role, choose the one which ended last.
                   1927:     # If there is a role which has expired, return it.
                   1928:     #
1.815     albertel 1929:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1930:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1931:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1932:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1933:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1934:         my $section=$1;
                   1935:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1936:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1937:         my $now=time;
1.548     albertel 1938:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1939:             $Expired{$end}=$section;
                   1940:             next;
                   1941:         }
1.548     albertel 1942:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1943:             $Pending{$start}=$section;
                   1944:             next;
                   1945:         }
1.599     albertel 1946:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1947:     }
                   1948:     #
                   1949:     # Presumedly there will be few matching roles from the above
                   1950:     # loop and the sorting time will be negligible.
                   1951:     if (scalar(keys(%Pending))) {
                   1952:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1953:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1954:     } 
                   1955:     if (scalar(keys(%Expired))) {
                   1956:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1957:         my $time = pop(@sorted);
1.599     albertel 1958:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1959:     }
1.599     albertel 1960:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1961: }
1.70      www      1962: 
1.599     albertel 1963: sub save_cache {
                   1964:     &purge_remembered();
1.722     albertel 1965:     #&Apache::loncommon::validate_page();
1.620     albertel 1966:     undef(%env);
1.780     albertel 1967:     undef($env_loaded);
1.599     albertel 1968: }
1.452     albertel 1969: 
1.599     albertel 1970: my $to_remember=-1;
                   1971: my %remembered;
                   1972: my %accessed;
                   1973: my $kicks=0;
                   1974: my $hits=0;
1.849     albertel 1975: sub make_key {
                   1976:     my ($name,$id) = @_;
1.872     albertel 1977:     if (length($id) > 65 
                   1978: 	&& length(&escape($id)) > 200) {
                   1979: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1980:     }
1.849     albertel 1981:     return &escape($name.':'.$id);
                   1982: }
                   1983: 
1.599     albertel 1984: sub devalidate_cache_new {
                   1985:     my ($name,$id,$debug) = @_;
                   1986:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1987:     $id=&make_key($name,$id);
1.599     albertel 1988:     $memcache->delete($id);
                   1989:     delete($remembered{$id});
                   1990:     delete($accessed{$id});
                   1991: }
                   1992: 
                   1993: sub is_cached_new {
                   1994:     my ($name,$id,$debug) = @_;
1.849     albertel 1995:     $id=&make_key($name,$id);
1.599     albertel 1996:     if (exists($remembered{$id})) {
                   1997: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1998: 	$accessed{$id}=[&gettimeofday()];
                   1999: 	$hits++;
                   2000: 	return ($remembered{$id},1);
                   2001:     }
                   2002:     my $value = $memcache->get($id);
                   2003:     if (!(defined($value))) {
                   2004: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2005: 	return (undef,undef);
1.416     albertel 2006:     }
1.599     albertel 2007:     if ($value eq '__undef__') {
                   2008: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2009: 	$value=undef;
                   2010:     }
                   2011:     &make_room($id,$value,$debug);
                   2012:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2013:     return ($value,1);
                   2014: }
                   2015: 
                   2016: sub do_cache_new {
                   2017:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2018:     $id=&make_key($name,$id);
1.599     albertel 2019:     my $setvalue=$value;
                   2020:     if (!defined($setvalue)) {
                   2021: 	$setvalue='__undef__';
                   2022:     }
1.623     albertel 2023:     if (!defined($time) ) {
                   2024: 	$time=600;
                   2025:     }
1.599     albertel 2026:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2027:     my $result = $memcache->set($id,$setvalue,$time);
                   2028:     if (! $result) {
1.872     albertel 2029: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2030: 	$memcache->disconnect_all();
1.872     albertel 2031:     }
1.600     albertel 2032:     # need to make a copy of $value
1.919     albertel 2033:     &make_room($id,$value,$debug);
1.599     albertel 2034:     return $value;
                   2035: }
                   2036: 
                   2037: sub make_room {
                   2038:     my ($id,$value,$debug)=@_;
1.919     albertel 2039: 
                   2040:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2041:                                     : $value;
1.599     albertel 2042:     if ($to_remember<0) { return; }
                   2043:     $accessed{$id}=[&gettimeofday()];
                   2044:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2045:     my $to_kick;
                   2046:     my $max_time=0;
                   2047:     foreach my $other (keys(%accessed)) {
                   2048: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2049: 	    $to_kick=$other;
                   2050: 	    $max_time=&tv_interval($accessed{$other});
                   2051: 	}
                   2052:     }
                   2053:     delete($remembered{$to_kick});
                   2054:     delete($accessed{$to_kick});
                   2055:     $kicks++;
                   2056:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2057:     return;
                   2058: }
                   2059: 
1.599     albertel 2060: sub purge_remembered {
1.604     albertel 2061:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2062:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2063:     undef(%remembered);
                   2064:     undef(%accessed);
1.428     albertel 2065: }
1.70      www      2066: # ------------------------------------- Read an entry from a user's environment
                   2067: 
                   2068: sub userenvironment {
                   2069:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2070:     my $items;
                   2071:     foreach my $item (@what) {
                   2072:         $items.=&escape($item).'&';
                   2073:     }
                   2074:     $items=~s/\&$//;
1.70      www      2075:     my %returnhash=();
1.1009    raeburn  2076:     my $uhome = &homeserver($unam,$udom);
                   2077:     unless ($uhome eq 'no_host') {
                   2078:         my @answer=split(/\&/, 
                   2079:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2080:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2081:             return %returnhash;
                   2082:         }
1.1009    raeburn  2083:         my $i;
                   2084:         for ($i=0;$i<=$#what;$i++) {
                   2085: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2086:         }
1.70      www      2087:     }
                   2088:     return %returnhash;
1.1       albertel 2089: }
                   2090: 
1.617     albertel 2091: # ---------------------------------------------------------- Get a studentphoto
                   2092: sub studentphoto {
                   2093:     my ($udom,$unam,$ext) = @_;
                   2094:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2095:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2096:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2097:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2098:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2099:             } else {
                   2100:                 my ($result,$perm_reqd)=
1.707     albertel 2101: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2102:                 if ($result eq 'ok') {
                   2103:                     if (!($perm_reqd eq 'yes')) {
                   2104:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2105:                     }
                   2106:                 }
                   2107:             }
                   2108:         }
                   2109:     } else {
                   2110:         my ($result,$perm_reqd) = 
1.707     albertel 2111: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2112:         if ($result eq 'ok') {
                   2113:             if (!($perm_reqd eq 'yes')) {
                   2114:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2115:             }
                   2116:         }
                   2117:     }
                   2118:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2119: }
                   2120: 
                   2121: sub retrievestudentphoto {
                   2122:     my ($udom,$unam,$ext,$type) = @_;
                   2123:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2124:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2125:     if ($ret eq 'ok') {
                   2126:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2127:         if ($type eq 'thumbnail') {
                   2128:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2129:         }
                   2130:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2131:         return $tokenurl;
                   2132:     } else {
                   2133:         if ($type eq 'thumbnail') {
                   2134:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2135:         } else { 
                   2136:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2137:         }
1.617     albertel 2138:     }
                   2139: }
                   2140: 
1.263     www      2141: # -------------------------------------------------------------------- New chat
                   2142: 
                   2143: sub chatsend {
1.724     raeburn  2144:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2145:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2146:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2147:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2148:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2149: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2150: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2151: }
                   2152: 
                   2153: # ------------------------------------------ Find current version of a resource
                   2154: 
                   2155: sub getversion {
                   2156:     my $fname=&clutter(shift);
                   2157:     unless ($fname=~/^\/res\//) { return -1; }
                   2158:     return &currentversion(&filelocation('',$fname));
                   2159: }
                   2160: 
                   2161: sub currentversion {
                   2162:     my $fname=shift;
                   2163:     my $author=$fname;
                   2164:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2165:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2166:     my $home=&homeserver($uname,$udom);
1.292     www      2167:     if ($home eq 'no_host') { 
                   2168:         return -1; 
                   2169:     }
1.1112    www      2170:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2171:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2172: 	return -1;
                   2173:     }
1.1112    www      2174:     return $answer;
1.263     www      2175: }
                   2176: 
1.1111    www      2177: #
                   2178: # Return special version number of resource if set by override, empty otherwise
                   2179: #
                   2180: sub usedversion {
                   2181:     my $fname=shift;
                   2182:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2183:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2184:     if ($urlversion) { return $urlversion; }
                   2185:     return '';
                   2186: }
                   2187: 
1.1       albertel 2188: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2189: 
1.1       albertel 2190: sub subscribe {
                   2191:     my $fname=shift;
1.761     raeburn  2192:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2193:     $fname=~s/[\n\r]//g;
1.1       albertel 2194:     my $author=$fname;
                   2195:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2196:     my ($udom,$uname)=split(/\//,$author);
                   2197:     my $home=homeserver($uname,$udom);
1.335     albertel 2198:     if ($home eq 'no_host') {
                   2199:         return 'not_found';
1.1       albertel 2200:     }
                   2201:     my $answer=reply("sub:$fname",$home);
1.64      www      2202:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2203: 	$answer.=' by '.$home;
                   2204:     }
1.1       albertel 2205:     return $answer;
                   2206: }
                   2207:     
1.8       www      2208: # -------------------------------------------------------------- Replicate file
                   2209: 
                   2210: sub repcopy {
                   2211:     my $filename=shift;
1.23      www      2212:     $filename=~s/\/+/\//g;
1.607     raeburn  2213:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2214:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2215:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2216: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2217: 	return &repcopy_userfile($filename);
                   2218:     }
1.532     albertel 2219:     $filename=~s/[\n\r]//g;
1.8       www      2220:     my $transname="$filename.in.transfer";
1.828     www      2221: # FIXME: this should flock
1.607     raeburn  2222:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2223:     my $remoteurl=subscribe($filename);
1.64      www      2224:     if ($remoteurl =~ /^con_lost by/) {
                   2225: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2226:            return 'unavailable';
1.8       www      2227:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2228: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2229: 	   return 'not_found';
1.64      www      2230:     } elsif ($remoteurl =~ /^rejected by/) {
                   2231: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2232:            return 'forbidden';
1.20      www      2233:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2234:            return 'ok';
1.8       www      2235:     } else {
1.290     www      2236:         my $author=$filename;
                   2237:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2238:         my ($udom,$uname)=split(/\//,$author);
                   2239:         my $home=homeserver($uname,$udom);
                   2240:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2241:            my @parts=split(/\//,$filename);
                   2242:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2243:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2244:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2245: 	       return 'bad_request';
1.8       www      2246:            }
                   2247:            my $count;
                   2248:            for ($count=5;$count<$#parts;$count++) {
                   2249:                $path.="/$parts[$count]";
                   2250:                if ((-e $path)!=1) {
                   2251: 		   mkdir($path,0777);
                   2252:                }
                   2253:            }
                   2254:            my $ua=new LWP::UserAgent;
                   2255:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2256:            my $response=$ua->request($request,$transname);
                   2257:            if ($response->is_error()) {
                   2258: 	       unlink($transname);
                   2259:                my $message=$response->status_line;
1.672     albertel 2260:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2261:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2262:                return 'unavailable';
1.8       www      2263:            } else {
1.16      www      2264: 	       if ($remoteurl!~/\.meta$/) {
                   2265:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2266:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2267:                   if ($mresponse->is_error()) {
                   2268: 		      unlink($filename.'.meta');
                   2269:                       &logthis(
1.672     albertel 2270:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2271:                   }
                   2272: 	       }
1.8       www      2273:                rename($transname,$filename);
1.607     raeburn  2274:                return 'ok';
1.8       www      2275:            }
1.290     www      2276:        }
1.8       www      2277:     }
1.330     www      2278: }
                   2279: 
                   2280: # ------------------------------------------------ Get server side include body
                   2281: sub ssi_body {
1.381     albertel 2282:     my ($filelink,%form)=@_;
1.606     matthew  2283:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2284:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2285:     }
1.953     www      2286:     my $output='';
                   2287:     my $response;
1.980     raeburn  2288:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2289:        ($output,$response)=&externalssi($filelink);
1.953     www      2290:     } else {
1.1004    droeschl 2291:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2292:        $filelink .= 'inhibitmenu=yes';
1.953     www      2293:        ($output,$response)=&ssi($filelink,%form);
                   2294:     }
1.778     albertel 2295:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2296:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2297:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2298:     if (wantarray) {
                   2299:         return ($output, $response);
                   2300:     } else {
                   2301:         return $output;
                   2302:     }
1.8       www      2303: }
                   2304: 
1.15      www      2305: # --------------------------------------------------------- Server Side Include
                   2306: 
1.782     albertel 2307: sub absolute_url {
                   2308:     my ($host_name) = @_;
                   2309:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2310:     if ($host_name eq '') {
                   2311: 	$host_name = $ENV{'SERVER_NAME'};
                   2312:     }
                   2313:     return $protocol.$host_name;
                   2314: }
                   2315: 
1.942     foxr     2316: #
                   2317: #   Server side include.
                   2318: # Parameters:
                   2319: #  fn     Possibly encrypted resource name/id.
                   2320: #  form   Hash that describes how the rendering should be done
                   2321: #         and other things.
1.944     foxr     2322: # Returns:
1.950     raeburn  2323: #   Scalar context: The content of the response.
                   2324: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2325: #     
1.15      www      2326: sub ssi {
                   2327: 
1.944     foxr     2328:     my ($fn,%form)=@_;
1.15      www      2329:     my $ua=new LWP::UserAgent;
1.23      www      2330:     my $request;
1.711     albertel 2331: 
                   2332:     $form{'no_update_last_known'}=1;
1.895     albertel 2333:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2334:     if (%form) {
1.782     albertel 2335:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2336:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2337:     } else {
1.782     albertel 2338:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2339:     }
                   2340: 
1.15      www      2341:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2342:     my $response=$ua->request($request);
                   2343: 
1.944     foxr     2344:     if (wantarray) {
                   2345: 	return ($response->content, $response);
                   2346:     } else {
                   2347: 	return $response->content;
1.942     foxr     2348:     }
1.324     www      2349: }
                   2350: 
                   2351: sub externalssi {
                   2352:     my ($url)=@_;
                   2353:     my $ua=new LWP::UserAgent;
                   2354:     my $request=new HTTP::Request('GET',$url);
                   2355:     my $response=$ua->request($request);
1.954     raeburn  2356:     if (wantarray) {
                   2357:         return ($response->content, $response);
                   2358:     } else {
                   2359:         return $response->content;
                   2360:     }
1.15      www      2361: }
1.254     www      2362: 
1.492     albertel 2363: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2364: 
                   2365: sub allowuploaded {
                   2366:     my ($srcurl,$url)=@_;
                   2367:     $url=&clutter(&declutter($url));
                   2368:     my $dir=$url;
                   2369:     $dir=~s/\/[^\/]+$//;
                   2370:     my %httpref=();
                   2371:     my $httpurl=&hreflocation('',$url);
                   2372:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2373:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2374: }
1.477     raeburn  2375: 
1.478     albertel 2376: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2377: # input: action, courseID, current domain, intended
1.637     raeburn  2378: #        path to file, source of file, instruction to parse file for objects,
                   2379: #        ref to hash for embedded objects,
                   2380: #        ref to hash for codebase of java objects.
1.1095    raeburn  2381: #        reference to scalar to accommodate mime type determined
                   2382: #          from File::MMagic if $parser = parse.
1.637     raeburn  2383: #
1.485     raeburn  2384: # output: url to file (if action was uploaddoc), 
                   2385: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2386: #
1.478     albertel 2387: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2388: # course.
1.477     raeburn  2389: #
1.478     albertel 2390: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2391: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2392: #          course's home server.
1.477     raeburn  2393: #
1.478     albertel 2394: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2395: #          be copied from $source (current location) to 
                   2396: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2397: #         and will then be copied to
                   2398: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2399: #         course's home server.
1.485     raeburn  2400: #
1.481     raeburn  2401: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2402: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2403: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2404: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2405: #         in course's home server.
1.637     raeburn  2406: #
1.477     raeburn  2407: 
                   2408: sub process_coursefile {
1.1095    raeburn  2409:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2410:         $mimetype)=@_;
1.477     raeburn  2411:     my $fetchresult;
1.638     albertel 2412:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2413:     if ($action eq 'propagate') {
1.638     albertel 2414:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2415: 			     $home);
1.481     raeburn  2416:     } else {
1.477     raeburn  2417:         my $fpath = '';
                   2418:         my $fname = $file;
1.478     albertel 2419:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2420:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2421:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2422:         if ($action eq 'copy') {
                   2423:             if ($source eq '') {
                   2424:                 $fetchresult = 'no source file';
                   2425:                 return $fetchresult;
                   2426:             } else {
                   2427:                 my $destination = $filepath.'/'.$fname;
                   2428:                 rename($source,$destination);
                   2429:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2430:                                  $home);
1.481     raeburn  2431:             }
                   2432:         } elsif ($action eq 'uploaddoc') {
                   2433:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2434:             print $fh $env{'form.'.$source};
1.481     raeburn  2435:             close($fh);
1.637     raeburn  2436:             if ($parser eq 'parse') {
1.1024    raeburn  2437:                 my $mm = new File::MMagic;
1.1095    raeburn  2438:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2439:                 if ($type eq 'text/html') {
1.1024    raeburn  2440:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2441:                     unless ($parse_result eq 'ok') {
                   2442:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2443:                     }
1.637     raeburn  2444:                 }
1.1095    raeburn  2445:                 if (ref($mimetype)) {
                   2446:                     $$mimetype = $type;
                   2447:                 } 
1.637     raeburn  2448:             }
1.477     raeburn  2449:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2450:                                  $home);
1.481     raeburn  2451:             if ($fetchresult eq 'ok') {
                   2452:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2453:             } else {
                   2454:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2455:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2456:                 return '/adm/notfound.html';
                   2457:             }
1.477     raeburn  2458:         }
                   2459:     }
1.485     raeburn  2460:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2461:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2462:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2463:     }
                   2464:     return $fetchresult;
                   2465: }
                   2466: 
1.637     raeburn  2467: sub build_filepath {
                   2468:     my ($fpath) = @_;
                   2469:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2470:     unless ($fpath eq '') {
                   2471:         my @parts=split('/',$fpath);
                   2472:         foreach my $part (@parts) {
                   2473:             $filepath.= '/'.$part;
                   2474:             if ((-e $filepath)!=1) {
                   2475:                 mkdir($filepath,0777);
                   2476:             }
                   2477:         }
                   2478:     }
                   2479:     return $filepath;
                   2480: }
                   2481: 
                   2482: sub store_edited_file {
1.638     albertel 2483:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2484:     my $file = $primary_url;
                   2485:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2486:     my $fpath = '';
                   2487:     my $fname = $file;
                   2488:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2489:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2490:     my $filepath = &build_filepath($fpath);
                   2491:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2492:     print $fh $content;
                   2493:     close($fh);
1.638     albertel 2494:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2495:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2496: 			  $home);
1.637     raeburn  2497:     if ($$fetchresult eq 'ok') {
                   2498:         return '/uploaded/'.$fpath.'/'.$fname;
                   2499:     } else {
1.638     albertel 2500:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2501: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2502:         return '/adm/notfound.html';
                   2503:     }
                   2504: }
                   2505: 
1.531     albertel 2506: sub clean_filename {
1.831     albertel 2507:     my ($fname,$args)=@_;
1.315     www      2508: # Replace Windows backslashes by forward slashes
1.257     www      2509:     $fname=~s/\\/\//g;
1.831     albertel 2510:     if (!$args->{'keep_path'}) {
                   2511:         # Get rid of everything but the actual filename
                   2512: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2513:     }
1.315     www      2514: # Replace spaces by underscores
                   2515:     $fname=~s/\s+/\_/g;
                   2516: # Replace all other weird characters by nothing
1.831     albertel 2517:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2518: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2519: # numbers
                   2520:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2521:     return $fname;
                   2522: }
1.1051    raeburn  2523: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2524: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2525: # image with the same aspect ratio as the original, but with dimensions which do 
                   2526: # not exceed $resizewidth and $resizeheight.
                   2527:  
1.984     neumanie 2528: sub resizeImage {
1.1051    raeburn  2529:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2530:     my $ima = Image::Magick->new;
                   2531:     my $resized;
                   2532:     if (-e $img_path) {
                   2533:         $ima->Read($img_path);
                   2534:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2535:             my $width = $ima->Get('width');
                   2536:             my $height = $ima->Get('height');
                   2537:             if ($width > $resizewidth) {
                   2538: 	        my $factor = $width/$resizewidth;
                   2539:                 my $newheight = $height/$factor;
                   2540:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2541:                 $resized = 1;
                   2542:             }
                   2543:         }
                   2544:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2545:             my $width = $ima->Get('width');
                   2546:             my $height = $ima->Get('height');
                   2547:             if ($height > $resizeheight) {
                   2548:                 my $factor = $height/$resizeheight;
                   2549:                 my $newwidth = $width/$factor;
                   2550:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2551:                 $resized = 1;
                   2552:             }
                   2553:         }
                   2554:         if ($resized) {
                   2555:             $ima->Write($img_path);
                   2556:         }
                   2557:     }
                   2558:     return;
1.977     amueller 2559: }
                   2560: 
1.608     albertel 2561: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2562: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2563: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2564: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2565: #                                    canceloverwrite, or ''. 
                   2566: #                   if 'coursedoc': upload to the current course
                   2567: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2568: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2569: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2570: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2571: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2572: #        $allfiles - reference to hash for embedded objects
                   2573: #        $codebase - reference to hash for codebase of java objects
                   2574: #        $desuname - username for permanent storage of uploaded file
                   2575: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2576: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2577: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2578: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2579: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2580: #        $mimetype - reference to scalar to accommodate mime type determined
                   2581: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2582: # 
1.686     albertel 2583: # output: url of file in userspace, or error: <message> 
                   2584: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2585: 
1.531     albertel 2586: sub userfileupload {
1.1090    raeburn  2587:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2588:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2589:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2590:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2591:     $fname=&clean_filename($fname);
1.1090    raeburn  2592:     # See if there is anything left
1.257     www      2593:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2594:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2595:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2596:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2597:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2598:         my $now = time;
1.1090    raeburn  2599:         my $filepath;
1.1095    raeburn  2600:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2601:              $filepath = 'tmp/helprequests/'.$now;
                   2602:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2603:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2604:                          '_'.$env{'user.domain'}.'/pending';
                   2605:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2606:             my ($docuname,$docudom);
                   2607:             if ($destudom) {
                   2608:                 $docudom = $destudom;
                   2609:             } else {
                   2610:                 $docudom = $env{'user.domain'};
                   2611:             }
                   2612:             if ($destuname) {
                   2613:                 $docuname = $destuname;
                   2614:             } else {
                   2615:                 $docuname = $env{'user.name'};
                   2616:             }
                   2617:             if (exists($env{'form.group'})) {
                   2618:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2619:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2620:             }
                   2621:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2622:             if ($context eq 'canceloverwrite') {
                   2623:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2624:                 if (-e  $tempfile) {
                   2625:                     my @info = stat($tempfile);
                   2626:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2627:                         unlink($tempfile);
                   2628:                     }
                   2629:                 }
                   2630:                 return;
1.523     raeburn  2631:             }
                   2632:         }
1.1090    raeburn  2633:         # Create the directory if not present
1.741     raeburn  2634:         my @parts=split(/\//,$filepath);
                   2635:         my $fullpath = $perlvar{'lonDaemons'};
                   2636:         for (my $i=0;$i<@parts;$i++) {
                   2637:             $fullpath .= '/'.$parts[$i];
                   2638:             if ((-e $fullpath)!=1) {
                   2639:                 mkdir($fullpath,0777);
                   2640:             }
                   2641:         }
                   2642:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2643:         print $fh $env{'form.'.$formname};
                   2644:         close($fh);
1.1090    raeburn  2645:         if ($context eq 'existingfile') {
                   2646:             my @info = stat($fullpath.'/'.$fname);
                   2647:             return ($fullpath.'/'.$fname,$info[9]);
                   2648:         } else {
                   2649:             return $fullpath.'/'.$fname;
                   2650:         }
1.523     raeburn  2651:     }
1.995     raeburn  2652:     if ($subdir eq 'scantron') {
                   2653:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2654:     } else {
1.995     raeburn  2655:         $fname="$subdir/$fname";
                   2656:     }
1.1090    raeburn  2657:     if ($context eq 'coursedoc') {
1.638     albertel 2658: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2659: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2660:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2661:             return &finishuserfileupload($docuname,$docudom,
                   2662: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2663: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2664:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2665:         } else {
1.620     albertel 2666:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2667:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2668: 				       $fname,$formname,$parser,
1.1095    raeburn  2669: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2670:         }
1.719     banghart 2671:     } elsif (defined($destuname)) {
                   2672:         my $docuname=$destuname;
                   2673:         my $docudom=$destudom;
1.860     raeburn  2674: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2675: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2676:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2677:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2678:     } else {
1.638     albertel 2679:         my $docuname=$env{'user.name'};
                   2680:         my $docudom=$env{'user.domain'};
1.714     raeburn  2681:         if (exists($env{'form.group'})) {
                   2682:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2683:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2684:         }
1.860     raeburn  2685: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2686: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2687:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2688:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2689:     }
1.271     www      2690: }
                   2691: 
                   2692: sub finishuserfileupload {
1.860     raeburn  2693:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2694:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2695:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2696:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2697:   
1.860     raeburn  2698:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2699:     $file=$fname;
                   2700:     if ($fname=~m|/|) {
                   2701:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2702: 	$path.=$fnamepath.'/';
                   2703:     }
1.259     www      2704:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2705:     my $count;
                   2706:     for ($count=4;$count<=$#parts;$count++) {
                   2707:         $filepath.="/$parts[$count]";
                   2708:         if ((-e $filepath)!=1) {
                   2709: 	    mkdir($filepath,0777);
                   2710:         }
                   2711:     }
1.984     neumanie 2712: 
1.258     www      2713: # Save the file
                   2714:     {
1.701     albertel 2715: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2716: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2717: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2718: 	    return '/adm/notfound.html';
                   2719: 	}
1.1090    raeburn  2720:         if ($context eq 'overwrite') {
1.1117    foxr     2721:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2722:             my $target = $filepath.'/'.$file;
                   2723:             if (-e $source) {
                   2724:                 my @info = stat($source);
                   2725:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2726:                     unless (&File::Copy::move($source,$target)) {
                   2727:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2728:                         return "Moving from $source failed";
                   2729:                     }
                   2730:                 } else {
                   2731:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2732:                 }
                   2733:             } else {
                   2734:                 return "Temporary file: $source missing";
                   2735:             }
                   2736:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2737: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2738: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2739: 	    return '/adm/notfound.html';
                   2740: 	}
1.570     albertel 2741: 	close(FH);
1.1051    raeburn  2742:         if ($resizewidth && $resizeheight) {
                   2743:             my $mm = new File::MMagic;
                   2744:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2745:             if ($mime_type =~ m{^image/}) {
                   2746: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2747:             }  
1.977     amueller 2748: 	}
1.258     www      2749:     }
1.637     raeburn  2750:     if ($parser eq 'parse') {
1.1024    raeburn  2751:         my $mm = new File::MMagic;
1.1095    raeburn  2752:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2753:         if ($type eq 'text/html') {
1.1024    raeburn  2754:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2755:                                                        $allfiles,$codebase);
                   2756:             unless ($parse_result eq 'ok') {
                   2757:                 &logthis('Failed to parse '.$filepath.$file.
                   2758: 	   	         ' for embedded media: '.$parse_result); 
                   2759:             }
1.637     raeburn  2760:         }
1.1095    raeburn  2761:         if (ref($mimetype)) {
                   2762:             $$mimetype = $type;
                   2763:         }
1.637     raeburn  2764:     }
1.860     raeburn  2765:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2766:         my $input = $filepath.'/'.$file;
                   2767:         my $output = $filepath.'/'.'tn-'.$file;
                   2768:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2769:         system("convert -sample $thumbsize $input $output");
                   2770:         if (-e $filepath.'/'.'tn-'.$file) {
                   2771:             $fetchthumb  = 1; 
                   2772:         }
                   2773:     }
1.858     raeburn  2774:  
1.259     www      2775: # Notify homeserver to grep it
                   2776: #
1.984     neumanie 2777:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2778:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2779:     if ($fetchresult eq 'ok') {
1.860     raeburn  2780:         if ($fetchthumb) {
                   2781:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2782:             if ($thumbresult ne 'ok') {
                   2783:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2784:                          $docuhome.': '.$thumbresult);
                   2785:             }
                   2786:         }
1.259     www      2787: #
1.258     www      2788: # Return the URL to it
1.494     albertel 2789:         return '/uploaded/'.$path.$file;
1.263     www      2790:     } else {
1.494     albertel 2791:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2792: 		 ': '.$fetchresult);
1.263     www      2793:         return '/adm/notfound.html';
1.858     raeburn  2794:     }
1.493     albertel 2795: }
                   2796: 
1.637     raeburn  2797: sub extract_embedded_items {
1.961     raeburn  2798:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2799:     my @state = ();
                   2800:     my %javafiles = (
                   2801:                       codebase => '',
                   2802:                       code => '',
                   2803:                       archive => ''
                   2804:                     );
                   2805:     my %mediafiles = (
                   2806:                       src => '',
                   2807:                       movie => '',
                   2808:                      );
1.648     raeburn  2809:     my $p;
                   2810:     if ($content) {
                   2811:         $p = HTML::LCParser->new($content);
                   2812:     } else {
1.961     raeburn  2813:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2814:     }
1.641     albertel 2815:     while (my $t=$p->get_token()) {
1.640     albertel 2816: 	if ($t->[0] eq 'S') {
                   2817: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2818: 	    push(@state, $tagname);
1.648     raeburn  2819:             if (lc($tagname) eq 'allow') {
                   2820:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2821:             }
1.640     albertel 2822: 	    if (lc($tagname) eq 'img') {
                   2823: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2824: 	    }
1.886     albertel 2825: 	    if (lc($tagname) eq 'a') {
                   2826: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2827: 	    }
1.645     raeburn  2828:             if (lc($tagname) eq 'script') {
                   2829:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2830:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2831:                 } else {
                   2832:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2833:                 }
                   2834:             }
                   2835:             if (lc($tagname) eq 'link') {
                   2836:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2837:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2838:                 }
                   2839:             }
1.640     albertel 2840: 	    if (lc($tagname) eq 'object' ||
                   2841: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2842: 		foreach my $item (keys(%javafiles)) {
                   2843: 		    $javafiles{$item} = '';
                   2844: 		}
                   2845: 	    }
                   2846: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2847: 		my $name = lc($attr->{'name'});
                   2848: 		foreach my $item (keys(%javafiles)) {
                   2849: 		    if ($name eq $item) {
                   2850: 			$javafiles{$item} = $attr->{'value'};
                   2851: 			last;
                   2852: 		    }
                   2853: 		}
                   2854: 		foreach my $item (keys(%mediafiles)) {
                   2855: 		    if ($name eq $item) {
                   2856: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2857: 			last;
                   2858: 		    }
                   2859: 		}
                   2860: 	    }
                   2861: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2862: 		foreach my $item (keys(%javafiles)) {
                   2863: 		    if ($attr->{$item}) {
                   2864: 			$javafiles{$item} = $attr->{$item};
                   2865: 			last;
                   2866: 		    }
                   2867: 		}
                   2868: 		foreach my $item (keys(%mediafiles)) {
                   2869: 		    if ($attr->{$item}) {
                   2870: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2871: 			last;
                   2872: 		    }
                   2873: 		}
                   2874: 	    }
                   2875: 	} elsif ($t->[0] eq 'E') {
                   2876: 	    my ($tagname) = ($t->[1]);
                   2877: 	    if ($javafiles{'codebase'} ne '') {
                   2878: 		$javafiles{'codebase'} .= '/';
                   2879: 	    }  
                   2880: 	    if (lc($tagname) eq 'applet' ||
                   2881: 		lc($tagname) eq 'object' ||
                   2882: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2883: 		) {
                   2884: 		foreach my $item (keys(%javafiles)) {
                   2885: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2886: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2887: 			&add_filetype($allfiles,$file,$item);
                   2888: 		    }
                   2889: 		}
                   2890: 	    } 
                   2891: 	    pop @state;
                   2892: 	}
                   2893:     }
1.637     raeburn  2894:     return 'ok';
                   2895: }
                   2896: 
1.639     albertel 2897: sub add_filetype {
                   2898:     my ($allfiles,$file,$type)=@_;
                   2899:     if (exists($allfiles->{$file})) {
                   2900: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2901: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2902: 	}
                   2903:     } else {
                   2904: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2905:     }
                   2906: }
                   2907: 
1.493     albertel 2908: sub removeuploadedurl {
1.984     neumanie 2909:     my ($url)=@_;	
                   2910:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2911:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2912: }
                   2913: 
                   2914: sub removeuserfile {
                   2915:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2916:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2917:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2918:     if ($result eq 'ok') {	
1.798     raeburn  2919:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2920:             my $metafile = $fname.'.meta';
                   2921:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2922: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2923:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2924:             my $sqlresult = 
1.823     albertel 2925:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2926:                                         'portfolio_metadata',$group,
                   2927:                                         'delete');
1.798     raeburn  2928:         }
                   2929:     }
                   2930:     return $result;
1.257     www      2931: }
1.15      www      2932: 
1.530     albertel 2933: sub mkdiruserfile {
                   2934:     my ($docuname,$docudom,$dir)=@_;
                   2935:     my $home=&homeserver($docuname,$docudom);
                   2936:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2937: }
                   2938: 
1.531     albertel 2939: sub renameuserfile {
                   2940:     my ($docuname,$docudom,$old,$new)=@_;
                   2941:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2942:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2943:                         &escape("$old").':'.&escape("$new"),$home);
                   2944:     if ($result eq 'ok') {
                   2945:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2946:             my $oldmeta = $old.'.meta';
                   2947:             my $newmeta = $new.'.meta';
                   2948:             my $metaresult = 
                   2949:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2950: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2951:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2952:             my $sqlresult = 
1.823     albertel 2953:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2954:                                         'portfolio_metadata',$group,
                   2955:                                         'delete');
1.798     raeburn  2956:         }
                   2957:     }
                   2958:     return $result;
1.531     albertel 2959: }
                   2960: 
1.14      www      2961: # ------------------------------------------------------------------------- Log
                   2962: 
                   2963: sub log {
                   2964:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2965:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2966: }
                   2967: 
                   2968: # ------------------------------------------------------------------ Course Log
1.352     www      2969: #
                   2970: # This routine flushes several buffers of non-mission-critical nature
                   2971: #
1.157     www      2972: 
                   2973: sub flushcourselogs {
1.352     www      2974:     &logthis('Flushing log buffers');
                   2975: #
                   2976: # course logs
                   2977: # This is a log of all transactions in a course, which can be used
                   2978: # for data mining purposes
                   2979: #
                   2980: # It also collects the courseid database, which lists last transaction
                   2981: # times and course titles for all courseids
                   2982: #
                   2983:     my %courseidbuffer=();
1.921     raeburn  2984:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2985:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2986: 		          &escape($courselogs{$crsid}),
                   2987: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2988: 	    delete $courselogs{$crsid};
                   2989:         } else {
                   2990:             &logthis('Failed to flush log buffer for '.$crsid);
                   2991:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2992:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2993:                         " exceeded maximum size, deleting.</font>");
                   2994:                delete $courselogs{$crsid};
                   2995:             }
1.352     www      2996:         }
1.920     raeburn  2997:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2998:             'description' => $coursedescrbuf{$crsid},
                   2999:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3000:             'type'        => $coursetypebuf{$crsid},
                   3001:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3002:         };
1.191     harris41 3003:     }
1.352     www      3004: #
                   3005: # Write course id database (reverse lookup) to homeserver of courses 
                   3006: # Is used in pickcourse
                   3007: #
1.840     albertel 3008:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3009:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3010:                                     $courseidbuffer{$crs_home},
                   3011:                                     $crs_home,'timeonly');
1.352     www      3012:     }
                   3013: #
                   3014: # File accesses
                   3015: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3016: #
1.449     matthew  3017:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3018:         if ($entry =~ /___count$/) {
                   3019:             my ($dom,$name);
1.807     albertel 3020:             ($dom,$name,undef)=
1.811     albertel 3021: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3022:             if (! defined($dom) || $dom eq '' || 
                   3023:                 ! defined($name) || $name eq '') {
1.620     albertel 3024:                 my $cid = $env{'request.course.id'};
                   3025:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3026:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3027:             }
1.450     matthew  3028:             my $value = $accesshash{$entry};
                   3029:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3030:             my %temphash=($url => $value);
1.449     matthew  3031:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3032:             if ($result eq 'ok') {
                   3033:                 delete $accesshash{$entry};
                   3034:             } elsif ($result eq 'unknown_cmd') {
                   3035:                 # Target server has old code running on it.
1.450     matthew  3036:                 my %temphash=($entry => $value);
1.449     matthew  3037:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3038:                     delete $accesshash{$entry};
                   3039:                 }
                   3040:             }
                   3041:         } else {
1.811     albertel 3042:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3043:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3044:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3045:                 delete $accesshash{$entry};
                   3046:             }
1.185     www      3047:         }
1.191     harris41 3048:     }
1.352     www      3049: #
                   3050: # Roles
                   3051: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3052: #
1.800     albertel 3053:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3054:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3055: 	    split(/\:/,$entry);
                   3056:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3057:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3058:                 $rudom,$runame) eq 'ok') {
                   3059: 	    delete $userrolehash{$entry};
                   3060:         }
                   3061:     }
1.662     raeburn  3062: #
                   3063: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3064: #
                   3065:     my %domrolebuffer = ();
1.1000    raeburn  3066:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3067:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3068:         if ($domrolebuffer{$rudom}) {
                   3069:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3070:                       '='.&escape($domainrolehash{$entry});
                   3071:         } else {
                   3072:             $domrolebuffer{$rudom}.=&escape($entry).
                   3073:                       '='.&escape($domainrolehash{$entry});
                   3074:         }
                   3075:         delete $domainrolehash{$entry};
                   3076:     }
                   3077:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3078: 	my %servers = &get_servers($dom,'library');
                   3079: 	foreach my $tryserver (keys(%servers)) {
                   3080: 	    unless (&reply('domroleput:'.$dom.':'.
                   3081: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3082: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3083: 	    }
1.662     raeburn  3084:         }
                   3085:     }
1.186     www      3086:     $dumpcount++;
1.157     www      3087: }
                   3088: 
                   3089: sub courselog {
                   3090:     my $what=shift;
1.158     www      3091:     $what=time.':'.$what;
1.620     albertel 3092:     unless ($env{'request.course.id'}) { return ''; }
                   3093:     $coursedombuf{$env{'request.course.id'}}=
                   3094:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3095:     $coursenumbuf{$env{'request.course.id'}}=
                   3096:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3097:     $coursehombuf{$env{'request.course.id'}}=
                   3098:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3099:     $coursedescrbuf{$env{'request.course.id'}}=
                   3100:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3101:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3102:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3103:     $courseownerbuf{$env{'request.course.id'}}=
                   3104:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3105:     $coursetypebuf{$env{'request.course.id'}}=
                   3106:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3107:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3108: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3109:     } else {
1.620     albertel 3110: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3111:     }
1.620     albertel 3112:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3113: 	&flushcourselogs();
                   3114:     }
1.158     www      3115: }
                   3116: 
                   3117: sub courseacclog {
                   3118:     my $fnsymb=shift;
1.620     albertel 3119:     unless ($env{'request.course.id'}) { return ''; }
                   3120:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3121:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3122:         $what.=':POST';
1.583     matthew  3123:         # FIXME: Probably ought to escape things....
1.800     albertel 3124: 	foreach my $key (keys(%env)) {
                   3125:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3126:                 my $formitem = $1;
                   3127:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3128:                     $what.=':'.$formitem.'='.$env{$key};
                   3129:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3130:                     $what.=':'.$formitem.'='.$env{$key};
                   3131:                 }
1.158     www      3132:             }
1.191     harris41 3133:         }
1.583     matthew  3134:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3135:         # FIXME: We should not be depending on a form parameter that someone
                   3136:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3137:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3138:             $what.= ':POST';
                   3139:             # FIXME: Probably ought to escape things....
                   3140:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3141:                                  'crsdiscuss') {
1.620     albertel 3142:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3143:             }
                   3144:         }
1.158     www      3145:     }
                   3146:     &courselog($what);
1.149     www      3147: }
                   3148: 
1.185     www      3149: sub countacc {
                   3150:     my $url=&declutter(shift);
1.458     matthew  3151:     return if (! defined($url) || $url eq '');
1.620     albertel 3152:     unless ($env{'request.course.id'}) { return ''; }
                   3153:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3154:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3155:     $accesshash{$key}++;
1.185     www      3156: }
1.349     www      3157: 
1.361     www      3158: sub linklog {
                   3159:     my ($from,$to)=@_;
                   3160:     $from=&declutter($from);
                   3161:     $to=&declutter($to);
                   3162:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3163:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3164: }
                   3165:   
1.349     www      3166: sub userrolelog {
                   3167:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3168:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3169:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3170:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3171:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3172:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3173:        $userrolehash
                   3174:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3175:                     =$tend.':'.$tstart;
1.662     raeburn  3176:     }
1.898     albertel 3177:     if (($env{'request.role'} =~ /dc\./) &&
                   3178: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3179: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3180: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3181:          ($trole=~/^co/))) {
1.898     albertel 3182:        $userrolehash
                   3183:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3184:                     =$tend.':'.$tstart;
                   3185:     }
1.662     raeburn  3186:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3187:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3188:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3189:         ($trole=~/^sc/)) {
                   3190:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3191:        $domainrolehash
                   3192:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3193:                     = $tend.':'.$tstart;
                   3194:     }
1.351     www      3195: }
                   3196: 
1.957     raeburn  3197: sub courserolelog {
                   3198:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3199:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3200:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3201:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3202:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3203:         ($trole eq 'co')) {
1.957     raeburn  3204:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3205:             my $cdom = $1;
                   3206:             my $cnum = $2;
                   3207:             my $sec = $3;
                   3208:             my $namespace = 'rolelog';
                   3209:             my %storehash = (
                   3210:                                role    => $trole,
                   3211:                                start   => $tstart,
                   3212:                                end     => $tend,
                   3213:                                selfenroll => $selfenroll,
                   3214:                                context    => $context,
                   3215:                             );
                   3216:             if ($trole eq 'gr') {
                   3217:                 $namespace = 'groupslog';
                   3218:                 $storehash{'group'} = $sec;
                   3219:             } else {
                   3220:                 $storehash{'section'} = $sec;
                   3221:             }
                   3222:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3223:             if (($trole ne 'st') || ($sec ne '')) {
                   3224:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3225:             }
1.957     raeburn  3226:         }
                   3227:     }
                   3228:     return;
                   3229: }
                   3230: 
1.351     www      3231: sub get_course_adv_roles {
1.948     raeburn  3232:     my ($cid,$codes) = @_;
1.620     albertel 3233:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3234:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3235:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3236:     my %nothide=();
1.800     albertel 3237:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3238:         if ($user !~ /:/) {
                   3239: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3240:         } else {
                   3241:             $nothide{$user}=1;
                   3242:         }
1.470     www      3243:     }
1.351     www      3244:     my %returnhash=();
                   3245:     my %dumphash=
                   3246:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3247:     my $now=time;
1.997     raeburn  3248:     my %privileged;
1.1000    raeburn  3249:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3250: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3251:         if (($tstart) && ($tstart<0)) { next; }
                   3252:         if (($tend) && ($tend<$now)) { next; }
                   3253:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3254:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3255: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3256:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3257:             my %dompersonnel =
1.998     raeburn  3258:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3259:             $privileged{$domain} = {};
                   3260:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3261:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3262:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3263:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3264:                         $privileged{$udom}{$uname} = 1;
                   3265:                     }
                   3266:                 }
                   3267:             }
                   3268:         }
                   3269:         if ((exists($privileged{$domain}{$username})) && 
                   3270:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3271: 	if ($role eq 'cr') { next; }
1.948     raeburn  3272:         if ($codes) {
                   3273:             if ($section) { $role .= ':'.$section; }
                   3274:             if ($returnhash{$role}) {
                   3275:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3276:             } else {
                   3277:                 $returnhash{$role}=$username.':'.$domain;
                   3278:             }
1.351     www      3279:         } else {
1.988     raeburn  3280:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3281:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3282:             if ($returnhash{$key}) {
                   3283: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3284:             } else {
                   3285:                 $returnhash{$key}=$username.':'.$domain;
                   3286:             }
1.351     www      3287:         }
1.948     raeburn  3288:     }
1.400     www      3289:     return %returnhash;
                   3290: }
                   3291: 
                   3292: sub get_my_roles {
1.937     raeburn  3293:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3294:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3295:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3296:     my (%dumphash,%nothide);
1.1086    raeburn  3297:     if ($context eq 'userroles') {
                   3298:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3299:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3300:     } else {
                   3301:         %dumphash=
1.400     www      3302:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3303:         if ($hidepriv) {
                   3304:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3305:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3306:                 if ($user !~ /:/) {
                   3307:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3308:                 } else {
                   3309:                     $nothide{$user} = 1;
                   3310:                 }
                   3311:             }
                   3312:         }
1.858     raeburn  3313:     }
1.400     www      3314:     my %returnhash=();
                   3315:     my $now=time;
1.999     raeburn  3316:     my %privileged;
1.800     albertel 3317:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3318:         my ($role,$tend,$tstart);
                   3319:         if ($context eq 'userroles') {
                   3320: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3321:         } else {
                   3322:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3323:         }
1.400     www      3324:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3325:         my $status = 'active';
1.939     raeburn  3326:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3327:             $status = 'previous';
                   3328:         } 
                   3329:         if (($tstart) && ($now<$tstart)) {
                   3330:             $status = 'future';
                   3331:         }
                   3332:         if (ref($types) eq 'ARRAY') {
                   3333:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3334:                 next;
                   3335:             } 
                   3336:         } else {
                   3337:             if ($status ne 'active') {
                   3338:                 next;
                   3339:             }
                   3340:         }
1.867     raeburn  3341:         my ($rolecode,$username,$domain,$section,$area);
                   3342:         if ($context eq 'userroles') {
                   3343:             ($area,$rolecode) = split(/_/,$entry);
                   3344:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3345:         } else {
                   3346:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3347:         }
1.832     raeburn  3348:         if (ref($roledoms) eq 'ARRAY') {
                   3349:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3350:                 next;
                   3351:             }
                   3352:         }
                   3353:         if (ref($roles) eq 'ARRAY') {
                   3354:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3355:                 if ($role =~ /^cr\//) {
                   3356:                     if (!grep(/^cr$/,@{$roles})) {
                   3357:                         next;
                   3358:                     }
1.1104    raeburn  3359:                 } elsif ($role =~ /^gr\//) {
                   3360:                     if (!grep(/^gr$/,@{$roles})) {
                   3361:                         next;
                   3362:                     }
1.922     raeburn  3363:                 } else {
                   3364:                     next;
                   3365:                 }
1.832     raeburn  3366:             }
1.867     raeburn  3367:         }
1.937     raeburn  3368:         if ($hidepriv) {
1.999     raeburn  3369:             if ($context eq 'userroles') {
                   3370:                 if ((&privileged($username,$domain)) &&
                   3371:                     (!$nothide{$username.':'.$domain})) {
                   3372:                     next;
                   3373:                 }
                   3374:             } else {
                   3375:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3376:                     my %dompersonnel =
                   3377:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3378:                     $privileged{$domain} = {};
                   3379:                     if (keys(%dompersonnel)) {
                   3380:                         foreach my $server (keys(%dompersonnel)) {
                   3381:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3382:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3383:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3384:                                     $privileged{$udom}{$uname} = $trole;
                   3385:                                 }
                   3386:                             }
                   3387:                         }
                   3388:                     }
                   3389:                 }
                   3390:                 if (exists($privileged{$domain}{$username})) {
                   3391:                     if (!$nothide{$username.':'.$domain}) {
                   3392:                         next;
                   3393:                     }
                   3394:                 }
1.937     raeburn  3395:             }
                   3396:         }
1.933     raeburn  3397:         if ($withsec) {
                   3398:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3399:                 $tstart.':'.$tend;
                   3400:         } else {
                   3401:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3402:         }
1.832     raeburn  3403:     }
1.373     www      3404:     return %returnhash;
1.399     www      3405: }
                   3406: 
                   3407: # ----------------------------------------------------- Frontpage Announcements
                   3408: #
                   3409: #
                   3410: 
                   3411: sub postannounce {
                   3412:     my ($server,$text)=@_;
1.844     albertel 3413:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3414:     unless ($text=~/\w/) { $text=''; }
                   3415:     return &reply('setannounce:'.&escape($text),$server);
                   3416: }
                   3417: 
                   3418: sub getannounce {
1.448     albertel 3419: 
                   3420:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3421: 	my $announcement='';
1.800     albertel 3422: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3423: 	close($fh);
1.399     www      3424: 	if ($announcement=~/\w/) { 
                   3425: 	    return 
                   3426:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3427:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3428: 	} else {
                   3429: 	    return '';
                   3430: 	}
                   3431:     } else {
                   3432: 	return '';
                   3433:     }
1.351     www      3434: }
1.353     www      3435: 
                   3436: # ---------------------------------------------------------- Course ID routines
                   3437: # Deal with domain's nohist_courseid.db files
                   3438: #
                   3439: 
                   3440: sub courseidput {
1.921     raeburn  3441:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3442:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3443:     my $outcome;
                   3444:     if ($caller eq 'timeonly') {
                   3445:         my $cids = '';
                   3446:         foreach my $item (keys(%$storehash)) {
                   3447:             $cids.=&escape($item).'&';
                   3448:         }
                   3449:         $cids=~s/\&$//;
                   3450:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3451:                           $coursehome);       
                   3452:     } else {
                   3453:         my $items = '';
                   3454:         foreach my $item (keys(%$storehash)) {
                   3455:             $items.= &escape($item).'='.
                   3456:                      &freeze_escape($$storehash{$item}).'&';
                   3457:         }
                   3458:         $items=~s/\&$//;
                   3459:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3460:                           $coursehome);
1.918     raeburn  3461:     }
                   3462:     if ($outcome eq 'unknown_cmd') {
                   3463:         my $what;
                   3464:         foreach my $cid (keys(%$storehash)) {
                   3465:             $what .= &escape($cid).'=';
1.921     raeburn  3466:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3467:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3468:             }
                   3469:             $what =~ s/\:$/&/;
                   3470:         }
                   3471:         $what =~ s/\&$//;  
                   3472:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3473:     } else {
                   3474:         return $outcome;
                   3475:     }
1.353     www      3476: }
                   3477: 
                   3478: sub courseiddump {
1.921     raeburn  3479:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3480:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3481:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3482:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3483:     my $as_hash = 1;
                   3484:     my %returnhash;
                   3485:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3486:     my %libserv = &all_library();
                   3487:     foreach my $tryserver (keys(%libserv)) {
                   3488:         if ( (  $hostidflag == 1 
                   3489: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3490: 	     || (!defined($hostidflag)) ) {
                   3491: 
1.918     raeburn  3492: 	    if (($domfilter eq '') ||
                   3493: 		(&host_domain($tryserver) eq $domfilter)) {
                   3494:                 my $rep = 
                   3495:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3496:                          $sincefilter.':'.&escape($descfilter).':'.
                   3497:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3498:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3499:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3500:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3501:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3502:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3503:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3504:                          &escape($creationcontext).':'.$domcloner,
                   3505:                          $tryserver);
1.918     raeburn  3506:                 my @pairs=split(/\&/,$rep);
                   3507:                 foreach my $item (@pairs) {
                   3508:                     my ($key,$value)=split(/\=/,$item,2);
                   3509:                     $key = &unescape($key);
                   3510:                     next if ($key =~ /^error: 2 /);
                   3511:                     my $result = &thaw_unescape($value);
                   3512:                     if (ref($result) eq 'HASH') {
                   3513:                         $returnhash{$key}=$result;
                   3514:                     } else {
1.921     raeburn  3515:                         my @responses = split(/:/,$value);
                   3516:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3517:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3518:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3519:                         }
1.1008    raeburn  3520:                     }
1.353     www      3521:                 }
                   3522:             }
                   3523:         }
                   3524:     }
                   3525:     return %returnhash;
                   3526: }
                   3527: 
1.1055    raeburn  3528: sub courselastaccess {
                   3529:     my ($cdom,$cnum,$hostidref) = @_;
                   3530:     my %returnhash;
                   3531:     if ($cdom && $cnum) {
                   3532:         my $chome = &homeserver($cnum,$cdom);
                   3533:         if ($chome ne 'no_host') {
                   3534:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3535:             &extract_lastaccess(\%returnhash,$rep);
                   3536:         }
                   3537:     } else {
                   3538:         if (!$cdom) { $cdom=''; }
                   3539:         my %libserv = &all_library();
                   3540:         foreach my $tryserver (keys(%libserv)) {
                   3541:             if (ref($hostidref) eq 'ARRAY') {
                   3542:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3543:             } 
                   3544:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3545:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3546:                 &extract_lastaccess(\%returnhash,$rep);
                   3547:             }
                   3548:         }
                   3549:     }
                   3550:     return %returnhash;
                   3551: }
                   3552: 
                   3553: sub extract_lastaccess {
                   3554:     my ($returnhash,$rep) = @_;
                   3555:     if (ref($returnhash) eq 'HASH') {
                   3556:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3557:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3558:                  $rep eq '') {
                   3559:             my @pairs=split(/\&/,$rep);
                   3560:             foreach my $item (@pairs) {
                   3561:                 my ($key,$value)=split(/\=/,$item,2);
                   3562:                 $key = &unescape($key);
                   3563:                 next if ($key =~ /^error: 2 /);
                   3564:                 $returnhash->{$key} = &thaw_unescape($value);
                   3565:             }
                   3566:         }
                   3567:     }
                   3568:     return;
                   3569: }
                   3570: 
1.658     raeburn  3571: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3572: 
                   3573: sub dcmailput {
1.685     raeburn  3574:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3575:     my $status = &Apache::lonnet::critical(
1.740     www      3576:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3577:        &escape($message),$server);
1.662     raeburn  3578:     return $status;
                   3579: }
                   3580: 
1.658     raeburn  3581: sub dcmaildump {
                   3582:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3583:     my %returnhash=();
1.846     albertel 3584: 
                   3585:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3586:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3587:                                                          &escape($enddate).':';
                   3588: 	my @esc_senders=map { &escape($_)} @$senders;
                   3589: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3590: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3591:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3592:             if (($key) && ($value)) {
                   3593:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3594:             }
                   3595:         }
                   3596:     }
                   3597:     return %returnhash;
                   3598: }
1.662     raeburn  3599: # ---------------------------------------------------------- Domain roles
                   3600: 
                   3601: sub get_domain_roles {
                   3602:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3603:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3604:         $startdate = '.';
                   3605:     }
1.1018    raeburn  3606:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3607:         $enddate = '.';
                   3608:     }
1.922     raeburn  3609:     my $rolelist;
                   3610:     if (ref($roles) eq 'ARRAY') {
                   3611:         $rolelist = join(':',@{$roles});
                   3612:     }
1.662     raeburn  3613:     my %personnel = ();
1.841     albertel 3614: 
                   3615:     my %servers = &get_servers($dom,'library');
                   3616:     foreach my $tryserver (keys(%servers)) {
                   3617: 	%{$personnel{$tryserver}}=();
                   3618: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3619: 					    &escape($startdate).':'.
                   3620: 					    &escape($enddate).':'.
                   3621: 					    &escape($rolelist), $tryserver))) {
                   3622: 	    my ($key,$value) = split(/\=/,$line,2);
                   3623: 	    if (($key) && ($value)) {
                   3624: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3625: 	    }
                   3626: 	}
1.662     raeburn  3627:     }
                   3628:     return %personnel;
                   3629: }
1.658     raeburn  3630: 
1.1057    www      3631: # ----------------------------------------------------------- Interval timing 
1.149     www      3632: 
1.504     albertel 3633: sub get_first_access {
                   3634:     my ($type,$argsymb)=@_;
1.790     albertel 3635:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3636:     if ($argsymb) { $symb=$argsymb; }
                   3637:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3638:     if ($type eq 'course') {
                   3639: 	$res='course';
                   3640:     } elsif ($type eq 'map') {
1.588     albertel 3641: 	$res=&symbread($map);
                   3642:     } else {
                   3643: 	$res=$symb;
                   3644:     }
                   3645:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3646:     return $times{"$courseid\0$res"};
1.504     albertel 3647: }
                   3648: 
                   3649: sub set_first_access {
                   3650:     my ($type)=@_;
1.790     albertel 3651:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3652:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3653:     if ($type eq 'course') {
                   3654: 	$res='course';
                   3655:     } elsif ($type eq 'map') {
1.588     albertel 3656: 	$res=&symbread($map);
                   3657:     } else {
                   3658: 	$res=$symb;
                   3659:     }
                   3660:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3661:     if (!$firstaccess) {
1.588     albertel 3662: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3663:     }
                   3664:     return 'already_set';
1.504     albertel 3665: }
                   3666: 
1.110     www      3667: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3668: 
                   3669: sub expirespread {
                   3670:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3671:     my $cid=$env{'request.course.id'}; 
1.110     www      3672:     if ($cid) {
                   3673:        my $now=time;
                   3674:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3675:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3676:                             $env{'course.'.$cid.'.num'}.
1.110     www      3677: 	        	    ':nohist_expirationdates:'.
                   3678:                             &escape($key).'='.$now,
1.620     albertel 3679:                             $env{'course.'.$cid.'.home'})
1.110     www      3680:     }
                   3681:     return 'ok';
1.14      www      3682: }
                   3683: 
1.109     www      3684: # ----------------------------------------------------- Devalidate Spreadsheets
                   3685: 
                   3686: sub devalidate {
1.325     www      3687:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3688:     my $cid=$env{'request.course.id'}; 
1.109     www      3689:     if ($cid) {
1.391     matthew  3690:         # delete the stored spreadsheets for
                   3691:         # - the student level sheet of this user in course's homespace
                   3692:         # - the assessment level sheet for this resource 
                   3693:         #   for this user in user's homespace
1.553     albertel 3694: 	# - current conditional state info
1.325     www      3695: 	my $key=$uname.':'.$udom.':';
1.109     www      3696:         my $status=
1.299     matthew  3697: 	    &del('nohist_calculatedsheets',
1.391     matthew  3698: 		 [$key.'studentcalc:'],
1.620     albertel 3699: 		 $env{'course.'.$cid.'.domain'},
                   3700: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3701: 		.' '.
                   3702: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3703: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3704:         unless ($status eq 'ok ok') {
                   3705:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3706:                     $uname.' at '.$udom.' for '.
1.109     www      3707: 		    $symb.': '.$status);
1.133     albertel 3708:         }
1.553     albertel 3709: 	&delenv('user.state.'.$cid);
1.109     www      3710:     }
                   3711: }
                   3712: 
1.265     albertel 3713: sub get_scalar {
                   3714:     my ($string,$end) = @_;
                   3715:     my $value;
                   3716:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3717: 	$value = $1;
                   3718:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3719: 	$value = $1;
                   3720:     }
                   3721:     return &unescape($value);
                   3722: }
                   3723: 
                   3724: sub array2str {
                   3725:   my (@array) = @_;
                   3726:   my $result=&arrayref2str(\@array);
                   3727:   $result=~s/^__ARRAY_REF__//;
                   3728:   $result=~s/__END_ARRAY_REF__$//;
                   3729:   return $result;
                   3730: }
                   3731: 
1.204     albertel 3732: sub arrayref2str {
                   3733:   my ($arrayref) = @_;
1.265     albertel 3734:   my $result='__ARRAY_REF__';
1.204     albertel 3735:   foreach my $elem (@$arrayref) {
1.265     albertel 3736:     if(ref($elem) eq 'ARRAY') {
                   3737:       $result.=&arrayref2str($elem).'&';
                   3738:     } elsif(ref($elem) eq 'HASH') {
                   3739:       $result.=&hashref2str($elem).'&';
                   3740:     } elsif(ref($elem)) {
                   3741:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3742:     } else {
                   3743:       $result.=&escape($elem).'&';
                   3744:     }
                   3745:   }
                   3746:   $result=~s/\&$//;
1.265     albertel 3747:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3748:   return $result;
                   3749: }
                   3750: 
1.168     albertel 3751: sub hash2str {
1.204     albertel 3752:   my (%hash) = @_;
                   3753:   my $result=&hashref2str(\%hash);
1.265     albertel 3754:   $result=~s/^__HASH_REF__//;
                   3755:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3756:   return $result;
                   3757: }
                   3758: 
                   3759: sub hashref2str {
                   3760:   my ($hashref)=@_;
1.265     albertel 3761:   my $result='__HASH_REF__';
1.800     albertel 3762:   foreach my $key (sort(keys(%$hashref))) {
                   3763:     if (ref($key) eq 'ARRAY') {
                   3764:       $result.=&arrayref2str($key).'=';
                   3765:     } elsif (ref($key) eq 'HASH') {
                   3766:       $result.=&hashref2str($key).'=';
                   3767:     } elsif (ref($key)) {
1.265     albertel 3768:       $result.='=';
1.800     albertel 3769:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3770:     } else {
1.800     albertel 3771: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3772:     }
                   3773: 
1.800     albertel 3774:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3775:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3776:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3777:       $result.=&hashref2str($hashref->{$key}).'&';
                   3778:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3779:        $result.='&';
1.800     albertel 3780:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3781:     } else {
1.800     albertel 3782:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3783:     }
                   3784:   }
1.168     albertel 3785:   $result=~s/\&$//;
1.265     albertel 3786:   $result .= '__END_HASH_REF__';
1.168     albertel 3787:   return $result;
                   3788: }
                   3789: 
                   3790: sub str2hash {
1.265     albertel 3791:     my ($string)=@_;
                   3792:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3793:     return %$hash;
                   3794: }
                   3795: 
                   3796: sub str2hashref {
1.168     albertel 3797:   my ($string) = @_;
1.265     albertel 3798: 
                   3799:   my %hash;
                   3800: 
                   3801:   if($string !~ /^__HASH_REF__/) {
                   3802:       if (! ($string eq '' || !defined($string))) {
                   3803: 	  $hash{'error'}='Not hash reference';
                   3804:       }
                   3805:       return (\%hash, $string);
                   3806:   }
                   3807: 
                   3808:   $string =~ s/^__HASH_REF__//;
                   3809: 
                   3810:   while($string !~ /^__END_HASH_REF__/) {
                   3811:       #key
                   3812:       my $key='';
                   3813:       if($string =~ /^__HASH_REF__/) {
                   3814:           ($key, $string)=&str2hashref($string);
                   3815:           if(defined($key->{'error'})) {
                   3816:               $hash{'error'}='Bad data';
                   3817:               return (\%hash, $string);
                   3818:           }
                   3819:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3820:           ($key, $string)=&str2arrayref($string);
                   3821:           if($key->[0] eq 'Array reference error') {
                   3822:               $hash{'error'}='Bad data';
                   3823:               return (\%hash, $string);
                   3824:           }
                   3825:       } else {
                   3826:           $string =~ s/^(.*?)=//;
1.267     albertel 3827: 	  $key=&unescape($1);
1.265     albertel 3828:       }
                   3829:       $string =~ s/^=//;
                   3830: 
                   3831:       #value
                   3832:       my $value='';
                   3833:       if($string =~ /^__HASH_REF__/) {
                   3834:           ($value, $string)=&str2hashref($string);
                   3835:           if(defined($value->{'error'})) {
                   3836:               $hash{'error'}='Bad data';
                   3837:               return (\%hash, $string);
                   3838:           }
                   3839:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3840:           ($value, $string)=&str2arrayref($string);
                   3841:           if($value->[0] eq 'Array reference error') {
                   3842:               $hash{'error'}='Bad data';
                   3843:               return (\%hash, $string);
                   3844:           }
                   3845:       } else {
                   3846: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3847:       }
                   3848:       $string =~ s/^&//;
                   3849: 
                   3850:       $hash{$key}=$value;
1.204     albertel 3851:   }
1.265     albertel 3852: 
                   3853:   $string =~ s/^__END_HASH_REF__//;
                   3854: 
                   3855:   return (\%hash, $string);
1.204     albertel 3856: }
                   3857: 
                   3858: sub str2array {
1.265     albertel 3859:     my ($string)=@_;
                   3860:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3861:     return @$array;
                   3862: }
                   3863: 
                   3864: sub str2arrayref {
1.204     albertel 3865:   my ($string) = @_;
1.265     albertel 3866:   my @array;
                   3867: 
                   3868:   if($string !~ /^__ARRAY_REF__/) {
                   3869:       if (! ($string eq '' || !defined($string))) {
                   3870: 	  $array[0]='Array reference error';
                   3871:       }
                   3872:       return (\@array, $string);
                   3873:   }
                   3874: 
                   3875:   $string =~ s/^__ARRAY_REF__//;
                   3876: 
                   3877:   while($string !~ /^__END_ARRAY_REF__/) {
                   3878:       my $value='';
                   3879:       if($string =~ /^__HASH_REF__/) {
                   3880:           ($value, $string)=&str2hashref($string);
                   3881:           if(defined($value->{'error'})) {
                   3882:               $array[0] ='Array reference error';
                   3883:               return (\@array, $string);
                   3884:           }
                   3885:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3886:           ($value, $string)=&str2arrayref($string);
                   3887:           if($value->[0] eq 'Array reference error') {
                   3888:               $array[0] ='Array reference error';
                   3889:               return (\@array, $string);
                   3890:           }
                   3891:       } else {
                   3892: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3893:       }
                   3894:       $string =~ s/^&//;
                   3895: 
                   3896:       push(@array, $value);
1.191     harris41 3897:   }
1.265     albertel 3898: 
                   3899:   $string =~ s/^__END_ARRAY_REF__//;
                   3900: 
                   3901:   return (\@array, $string);
1.168     albertel 3902: }
                   3903: 
1.167     albertel 3904: # -------------------------------------------------------------------Temp Store
                   3905: 
1.168     albertel 3906: sub tmpreset {
                   3907:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3908:   if (!$symb) {
                   3909:     $symb=&symbread();
1.620     albertel 3910:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3911:   }
                   3912:   $symb=escape($symb);
                   3913: 
1.620     albertel 3914:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3915:   $namespace=~s/\//\_/g;
                   3916:   $namespace=~s/\W//g;
                   3917: 
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.1117    foxr     3923:   my $path=LONCAPA::tempdir();
1.168     albertel 3924:   my %hash;
                   3925:   if (tie(%hash,'GDBM_File',
                   3926: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3927: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3928:     foreach my $key (keys(%hash)) {
1.180     albertel 3929:       if ($key=~ /:$symb/) {
1.168     albertel 3930: 	delete($hash{$key});
                   3931:       }
                   3932:     }
                   3933:   }
                   3934: }
                   3935: 
1.167     albertel 3936: sub tmpstore {
1.168     albertel 3937:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3938: 
                   3939:   if (!$symb) {
                   3940:     $symb=&symbread();
1.620     albertel 3941:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3942:   }
                   3943:   $symb=escape($symb);
                   3944: 
                   3945:   if (!$namespace) {
                   3946:     # I don't think we would ever want to store this for a course.
                   3947:     # it seems this will only be used if we don't have a course.
1.620     albertel 3948:     #$namespace=$env{'request.course.id'};
1.168     albertel 3949:     #if (!$namespace) {
1.620     albertel 3950:       $namespace=$env{'request.state'};
1.168     albertel 3951:     #}
                   3952:   }
                   3953:   $namespace=~s/\//\_/g;
                   3954:   $namespace=~s/\W//g;
1.620     albertel 3955:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3956:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3957:   if ($domain eq 'public' && $stuname eq 'public') {
                   3958:       $stuname=$ENV{'REMOTE_ADDR'};
                   3959:   }
1.168     albertel 3960:   my $now=time;
                   3961:   my %hash;
1.1117    foxr     3962:   my $path=LONCAPA::tempdir();
1.168     albertel 3963:   if (tie(%hash,'GDBM_File',
                   3964: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3965: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3966:     $hash{"version:$symb"}++;
                   3967:     my $version=$hash{"version:$symb"};
                   3968:     my $allkeys=''; 
                   3969:     foreach my $key (keys(%$storehash)) {
                   3970:       $allkeys.=$key.':';
1.591     albertel 3971:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3972:     }
                   3973:     $hash{"$version:$symb:timestamp"}=$now;
                   3974:     $allkeys.='timestamp';
                   3975:     $hash{"$version:keys:$symb"}=$allkeys;
                   3976:     if (untie(%hash)) {
                   3977:       return 'ok';
                   3978:     } else {
                   3979:       return "error:$!";
                   3980:     }
                   3981:   } else {
                   3982:     return "error:$!";
                   3983:   }
                   3984: }
1.167     albertel 3985: 
1.168     albertel 3986: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3987: 
1.168     albertel 3988: sub tmprestore {
                   3989:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3990: 
1.168     albertel 3991:   if (!$symb) {
                   3992:     $symb=&symbread();
1.620     albertel 3993:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3994:   }
                   3995:   $symb=escape($symb);
                   3996: 
1.620     albertel 3997:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3998: 
1.620     albertel 3999:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4000:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4001:   if ($domain eq 'public' && $stuname eq 'public') {
                   4002:       $stuname=$ENV{'REMOTE_ADDR'};
                   4003:   }
1.168     albertel 4004:   my %returnhash;
                   4005:   $namespace=~s/\//\_/g;
                   4006:   $namespace=~s/\W//g;
                   4007:   my %hash;
1.1117    foxr     4008:   my $path=LONCAPA::tempdir();
1.168     albertel 4009:   if (tie(%hash,'GDBM_File',
                   4010: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4011: 	  &GDBM_READER(),0640)) {
1.168     albertel 4012:     my $version=$hash{"version:$symb"};
                   4013:     $returnhash{'version'}=$version;
                   4014:     my $scope;
                   4015:     for ($scope=1;$scope<=$version;$scope++) {
                   4016:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4017:       my @keys=split(/:/,$vkeys);
                   4018:       my $key;
                   4019:       $returnhash{"$scope:keys"}=$vkeys;
                   4020:       foreach $key (@keys) {
1.591     albertel 4021: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4022: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4023:       }
                   4024:     }
1.168     albertel 4025:     if (!(untie(%hash))) {
                   4026:       return "error:$!";
                   4027:     }
                   4028:   } else {
                   4029:     return "error:$!";
                   4030:   }
                   4031:   return %returnhash;
1.167     albertel 4032: }
                   4033: 
1.9       www      4034: # ----------------------------------------------------------------------- Store
                   4035: 
                   4036: sub store {
1.124     www      4037:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4038:     my $home='';
                   4039: 
1.168     albertel 4040:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4041: 
1.213     www      4042:     $symb=&symbclean($symb);
1.122     albertel 4043:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4044: 
1.620     albertel 4045:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4046:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4047: 
                   4048:     &devalidate($symb,$stuname,$domain);
1.109     www      4049: 
                   4050:     $symb=escape($symb);
1.187     www      4051:     if (!$namespace) { 
1.620     albertel 4052:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4053:           return ''; 
                   4054:        } 
                   4055:     }
1.620     albertel 4056:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4057: 
                   4058:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4059:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4060: 
1.12      www      4061:     my $namevalue='';
1.800     albertel 4062:     foreach my $key (keys(%$storehash)) {
                   4063:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4064:     }
1.12      www      4065:     $namevalue=~s/\&$//;
1.187     www      4066:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4067:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4068: }
                   4069: 
1.47      www      4070: # -------------------------------------------------------------- Critical Store
                   4071: 
                   4072: sub cstore {
1.124     www      4073:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4074:     my $home='';
                   4075: 
1.168     albertel 4076:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4077: 
1.213     www      4078:     $symb=&symbclean($symb);
1.122     albertel 4079:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4080: 
1.620     albertel 4081:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4082:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4083: 
                   4084:     &devalidate($symb,$stuname,$domain);
1.109     www      4085: 
                   4086:     $symb=escape($symb);
1.187     www      4087:     if (!$namespace) { 
1.620     albertel 4088:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4089:           return ''; 
                   4090:        } 
                   4091:     }
1.620     albertel 4092:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4093: 
                   4094:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4095:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4096: 
1.47      www      4097:     my $namevalue='';
1.800     albertel 4098:     foreach my $key (keys(%$storehash)) {
                   4099:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4100:     }
1.47      www      4101:     $namevalue=~s/\&$//;
1.187     www      4102:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4103:     return critical
                   4104:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4105: }
                   4106: 
1.9       www      4107: # --------------------------------------------------------------------- Restore
                   4108: 
                   4109: sub restore {
1.124     www      4110:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4111:     my $home='';
                   4112: 
1.168     albertel 4113:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4114: 
1.122     albertel 4115:     if (!$symb) {
                   4116:       unless ($symb=escape(&symbread())) { return ''; }
                   4117:     } else {
1.213     www      4118:       $symb=&escape(&symbclean($symb));
1.122     albertel 4119:     }
1.188     www      4120:     if (!$namespace) { 
1.620     albertel 4121:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4122:           return ''; 
                   4123:        } 
                   4124:     }
1.620     albertel 4125:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4126:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4127:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4128:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4129: 
1.12      www      4130:     my %returnhash=();
1.800     albertel 4131:     foreach my $line (split(/\&/,$answer)) {
                   4132: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4133:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4134:     }
1.75      www      4135:     my $version;
                   4136:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4137:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4138:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4139:        }
1.75      www      4140:     }
1.13      www      4141:     return %returnhash;
1.34      www      4142: }
                   4143: 
                   4144: # ---------------------------------------------------------- Course Description
1.1118    foxr     4145: #
                   4146: #  
1.34      www      4147: 
                   4148: sub coursedescription {
1.731     albertel 4149:     my ($courseid,$args)=@_;
1.34      www      4150:     $courseid=~s/^\///;
1.49      www      4151:     $courseid=~s/\_/\//g;
1.34      www      4152:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4153:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4154:     my $normalid=$cdomain.'_'.$cnum;
                   4155:     # need to always cache even if we get errors otherwise we keep 
                   4156:     # trying and trying and trying to get the course description.
                   4157:     my %envhash=();
                   4158:     my %returnhash=();
1.731     albertel 4159:     
                   4160:     my $expiretime=600;
                   4161:     if ($env{'request.course.id'} eq $normalid) {
                   4162: 	$expiretime=120;
                   4163:     }
                   4164: 
                   4165:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4166:     if (!$args->{'freshen_cache'}
                   4167: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4168: 	foreach my $key (keys(%env)) {
                   4169: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4170: 	    my ($setting) = $1;
                   4171: 	    $returnhash{$setting} = $env{$key};
                   4172: 	}
                   4173: 	return %returnhash;
                   4174:     }
                   4175: 
1.1118    foxr     4176:     # get the data again
                   4177: 
1.731     albertel 4178:     if (!$args->{'one_time'}) {
                   4179: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4180:     }
1.811     albertel 4181: 
1.34      www      4182:     if ($chome ne 'no_host') {
1.302     albertel 4183:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4184:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4185: 	   my $username = $env{'user.name'}; # Defult username
                   4186: 	   if(defined $args->{'user'}) {
                   4187: 	       $username = $args->{'user'};
                   4188: 	   }
1.129     albertel 4189:            $returnhash{'home'}= $chome;
                   4190: 	   $returnhash{'domain'} = $cdomain;
                   4191: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4192:            if (!defined($returnhash{'type'})) {
                   4193:                $returnhash{'type'} = 'Course';
                   4194:            }
1.130     albertel 4195:            while (my ($name,$value) = each %returnhash) {
1.53      www      4196:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4197:            }
1.270     www      4198:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4199:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4200: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4201:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4202:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4203:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4204:        }
                   4205:     }
1.731     albertel 4206:     if (!$args->{'one_time'}) {
1.949     raeburn  4207: 	&appenv(\%envhash);
1.731     albertel 4208:     }
1.302     albertel 4209:     return %returnhash;
1.461     www      4210: }
                   4211: 
1.1080    raeburn  4212: sub update_released_required {
                   4213:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4214:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4215:         $cid = $env{'request.course.id'};
                   4216:         $cdom = $env{'course.'.$cid.'.domain'};
                   4217:         $cnum = $env{'course.'.$cid.'.num'};
                   4218:         $chome = $env{'course.'.$cid.'.home'};
                   4219:     }
                   4220:     if ($needsrelease) {
                   4221:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4222:         my $needsupdate;
                   4223:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4224:             $needsupdate = 1;
                   4225:         } else {
                   4226:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4227:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4228:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4229:                 $needsupdate = 1;
                   4230:             }
                   4231:         }
                   4232:         if ($needsupdate) {
                   4233:             my %needshash = (
                   4234:                              'internal.releaserequired' => $needsrelease,
                   4235:                             );
                   4236:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4237:             if ($putresult eq 'ok') {
                   4238:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4239:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4240:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4241:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4242:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4243:                 }
                   4244:             }
                   4245:         }
                   4246:     }
                   4247:     return;
                   4248: }
                   4249: 
1.461     www      4250: # -------------------------------------------------See if a user is privileged
                   4251: 
                   4252: sub privileged {
                   4253:     my ($username,$domain)=@_;
                   4254:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4255: 			&homeserver($username,$domain));
1.1033    raeburn  4256:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4257:         ($rolesdump =~ /^error:/)) {
                   4258:         return 0;
                   4259:     }
1.461     www      4260:     my $now=time;
                   4261:     if ($rolesdump ne '') {
1.800     albertel 4262:         foreach my $entry (split(/&/,$rolesdump)) {
                   4263: 	    if ($entry!~/^rolesdef_/) {
                   4264: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4265: 		$area=~s/\_\w\w$//;
                   4266: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4267: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4268: 		    my $active=1;
                   4269: 		    if ($tend) {
                   4270: 			if ($tend<$now) { $active=0; }
                   4271: 		    }
                   4272: 		    if ($tstart) {
                   4273: 			if ($tstart>$now) { $active=0; }
                   4274: 		    }
                   4275: 		    if ($active) { return 1; }
                   4276: 		}
                   4277: 	    }
                   4278: 	}
                   4279:     }
                   4280:     return 0;
1.9       www      4281: }
1.1       albertel 4282: 
1.103     harris41 4283: # -------------------------------------------------------- Get user privileges
1.11      www      4284: 
                   4285: sub rolesinit {
                   4286:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4287:     my $now=time;
                   4288:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4289:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4290:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4291:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4292:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4293:         return \%userroles;
                   4294:     }
1.11      www      4295:     my %allroles=();
1.678     raeburn  4296:     my %allgroups=();   
1.11      www      4297: 
                   4298:     if ($rolesdump ne '') {
1.800     albertel 4299:         foreach my $entry (split(/&/,$rolesdump)) {
                   4300: 	  if ($entry!~/^rolesdef_/) {
                   4301:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4302: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4303:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4304: 	    if ($role=~/^cr/) { 
1.807     albertel 4305: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4306: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4307: 		    ($tend,$tstart)=split('_',$trest);
                   4308: 		} else {
                   4309: 		    $trole=$role;
                   4310: 		}
1.678     raeburn  4311:             } elsif ($role =~ m|^gr/|) {
                   4312:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4313:                 next if ($tstart eq '-1');
1.678     raeburn  4314:                 ($trole,$group_privs) = split(/\//,$trole);
                   4315:                 $group_privs = &unescape($group_privs);
1.587     albertel 4316: 	    } else {
                   4317: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4318: 	    }
1.743     albertel 4319: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4320: 					 $username);
                   4321: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4322:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4323:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4324:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4325: 		my $spec=$trole.'.'.$area;
                   4326: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4327: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4328:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4329:                 } elsif ($trole eq 'gr') {
                   4330:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4331: 		} else {
1.567     raeburn  4332:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4333: 		}
1.12      www      4334:             }
1.662     raeburn  4335:           }
1.191     harris41 4336:         }
1.743     albertel 4337:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4338:         $userroles{'user.adv'}    = $adv;
                   4339: 	$userroles{'user.author'} = $author;
1.620     albertel 4340:         $env{'user.adv'}=$adv;
1.11      www      4341:     }
1.743     albertel 4342:     return \%userroles;  
1.11      www      4343: }
                   4344: 
1.567     raeburn  4345: sub set_arearole {
                   4346:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4347: # log the associated role with the area
                   4348:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4349:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4350: }
                   4351: 
                   4352: sub custom_roleprivs {
                   4353:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4354:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4355:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4356:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4357:         my ($rdummy,$roledef)=
                   4358:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4359:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4360:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4361:             if (defined($syspriv)) {
1.1043    raeburn  4362:                 if ($trest =~ /^$match_community$/) {
                   4363:                     $syspriv =~ s/bre\&S//; 
                   4364:                 }
1.567     raeburn  4365:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4366:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4367:             }
                   4368:             if ($tdomain ne '') {
                   4369:                 if (defined($dompriv)) {
                   4370:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4371:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4372:                 }
                   4373:                 if (($trest ne '') && (defined($coursepriv))) {
                   4374:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4375:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4376:                 }
                   4377:             }
                   4378:         }
                   4379:     }
                   4380: }
                   4381: 
1.678     raeburn  4382: sub group_roleprivs {
                   4383:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4384:     my $access = 1;
                   4385:     my $now = time;
                   4386:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4387:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4388:     if ($access) {
1.811     albertel 4389:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4390:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4391:     }
                   4392: }
1.567     raeburn  4393: 
                   4394: sub standard_roleprivs {
                   4395:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4396:     if (defined($pr{$trole.':s'})) {
                   4397:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4398:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4399:     }
                   4400:     if ($tdomain ne '') {
                   4401:         if (defined($pr{$trole.':d'})) {
                   4402:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4403:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4404:         }
                   4405:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4406:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4407:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4408:         }
                   4409:     }
                   4410: }
                   4411: 
                   4412: sub set_userprivs {
1.1064    raeburn  4413:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4414:     my $author=0;
                   4415:     my $adv=0;
1.678     raeburn  4416:     my %grouproles = ();
                   4417:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4418:         my @groupkeys; 
1.1000    raeburn  4419:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4420:             push(@groupkeys,$role);
                   4421:         }
                   4422:         if (ref($groups_roles) eq 'HASH') {
                   4423:             foreach my $key (keys(%{$groups_roles})) {
                   4424:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4425:                     push(@groupkeys,$key);
                   4426:                 }
                   4427:             }
                   4428:         }
                   4429:         if (@groupkeys > 0) {
                   4430:             foreach my $role (@groupkeys) {
                   4431:                 my ($trole,$area,$sec,$extendedarea);
                   4432:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4433:                     $trole = $1;
                   4434:                     $area = $2;
                   4435:                     $sec = $3;
                   4436:                     $extendedarea = $area.$sec;
                   4437:                     if (exists($$allgroups{$area})) {
                   4438:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4439:                             my $spec = $trole.'.'.$extendedarea;
                   4440:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4441:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4442:                         }
1.678     raeburn  4443:                     }
                   4444:                 }
                   4445:             }
                   4446:         }
                   4447:     }
1.800     albertel 4448:     foreach my $group (keys(%grouproles)) {
                   4449:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4450:     }
1.800     albertel 4451:     foreach my $role (keys(%{$allroles})) {
                   4452:         my %thesepriv;
1.941     raeburn  4453:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4454:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4455:             if ($item ne '') {
                   4456:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4457:                 if ($restrictions eq '') {
                   4458:                     $thesepriv{$privilege}='F';
                   4459:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4460:                     $thesepriv{$privilege}.=$restrictions;
                   4461:                 }
                   4462:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4463:             }
                   4464:         }
                   4465:         my $thesestr='';
1.1104    raeburn  4466:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4467: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4468: 	}
                   4469:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4470:     }
                   4471:     return ($author,$adv);
                   4472: }
                   4473: 
1.994     raeburn  4474: sub role_status {
1.1104    raeburn  4475:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4476:     my @pwhere = ();
                   4477:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4478:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4479:         unless (!defined($$role) || $$role eq '') {
                   4480:             $$where=join('.',@pwhere);
                   4481:             $$trolecode=$$role.'.'.$$where;
                   4482:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4483:             $$tstatus='is';
1.1104    raeburn  4484:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4485:                 $$tstatus='future';
1.1034    raeburn  4486:                 if ($$tstart<$now) {
                   4487:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4488:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4489:                             my (%allroles,%allgroups,$group_privs,
                   4490:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4491:                             my %userroles = (
                   4492:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4493:                             );
1.1064    raeburn  4494:                             @rolecodes = ('cm'); 
1.1002    raeburn  4495:                             my $spec=$$role.'.'.$$where;
                   4496:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4497:                             if ($$role =~ /^cr\//) {
                   4498:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4499:                                 push(@rolecodes,'cr');
1.1002    raeburn  4500:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4501:                                 push(@rolecodes,$$role);
1.1002    raeburn  4502:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4503:                                                     $env{'user.name'});
1.1064    raeburn  4504:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4505:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4506:                                 $group_privs = &unescape($group_privs);
                   4507:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4508:                                 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  4509:                                 &get_groups_roles($tdomain,$trest,
                   4510:                                                   \%course_roles,\@rolecodes,
                   4511:                                                   \%groups_roles);
1.1002    raeburn  4512:                             } else {
1.1064    raeburn  4513:                                 push(@rolecodes,$$role);
1.1002    raeburn  4514:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4515:                             }
1.1064    raeburn  4516:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4517:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4518:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4519:                         }
                   4520:                     }
1.1034    raeburn  4521:                     $$tstatus = 'is';
1.1002    raeburn  4522:                 }
1.994     raeburn  4523:             }
                   4524:             if ($$tend) {
1.1104    raeburn  4525:                 if ($$tend<$update) {
1.994     raeburn  4526:                     $$tstatus='expired';
                   4527:                 } elsif ($$tend<$now) {
                   4528:                     $$tstatus='will_not';
                   4529:                 }
                   4530:             }
                   4531:         }
                   4532:     }
                   4533: }
                   4534: 
1.1104    raeburn  4535: sub get_groups_roles {
                   4536:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4537:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4538:                   (ref($rolecodes) eq 'ARRAY') && 
                   4539:                   (ref($groups_roles) eq 'HASH')); 
                   4540:     if (keys(%{$cdom_courseroles}) > 0) {
                   4541:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4542:         if ($cdom ne '' && $cnum ne '') {
                   4543:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4544:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4545:                     my $crsrole = $1;
                   4546:                     my $crssec = $2;
                   4547:                     if ($crsrole =~ /^cr/) {
                   4548:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4549:                             push(@{$rolecodes},'cr');
                   4550:                         }
                   4551:                     } else {
                   4552:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4553:                             push(@{$rolecodes},$crsrole);
                   4554:                         }
                   4555:                     }
                   4556:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4557:                     if ($crssec ne '') {
                   4558:                         $rolekey .= "/$crssec";
                   4559:                     }
                   4560:                     $rolekey .= './';
                   4561:                     $groups_roles->{$rolekey} = $rolecodes;
                   4562:                 }
                   4563:             }
                   4564:         }
                   4565:     }
                   4566:     return;
                   4567: }
                   4568: 
                   4569: sub delete_env_groupprivs {
                   4570:     my ($where,$courseroles,$possroles) = @_;
                   4571:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4572:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4573:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4574:         %{$courseroles->{$udom}} =
                   4575:             &get_my_roles('','','userroles',['active'],
                   4576:                           $possroles,[$udom],1);
                   4577:     }
                   4578:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4579:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4580:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4581:             my $area = '/'.$cdom.'/'.$cnum;
                   4582:             my $privkey = "user.priv.$crsrole.$area";
                   4583:             if ($crssec ne '') {
                   4584:                 $privkey .= '/'.$crssec;
                   4585:             }
                   4586:             $privkey .= ".$area/$group";
                   4587:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4588:         }
                   4589:     }
                   4590:     return;
                   4591: }
                   4592: 
1.994     raeburn  4593: sub check_adhoc_privs {
1.1104    raeburn  4594:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4595:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4596:     if ($env{$cckey}) {
                   4597:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4598:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4599:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4600:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4601:         }
                   4602:     } else {
1.1088    raeburn  4603:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4604:     }
                   4605: }
                   4606: 
                   4607: sub set_adhoc_privileges {
                   4608: # role can be cc or ca
1.1088    raeburn  4609:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4610:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4611:     my $spec = $role.'.'.$area;
                   4612:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4613:                                   $env{'user.name'});
                   4614:     my %ccrole = ();
                   4615:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4616:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4617:     &appenv(\%userroles,[$role,'cm']);
                   4618:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4619:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4620:         &appenv( {'request.role'        => $spec,
                   4621:                   'request.role.domain' => $dcdom,
                   4622:                   'request.course.sec'  => ''
                   4623:                  }
                   4624:                );
                   4625:         my $tadv=0;
                   4626:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4627:         &appenv({'request.role.adv'    => $tadv});
                   4628:     }
1.994     raeburn  4629: }
                   4630: 
1.12      www      4631: # --------------------------------------------------------------- get interface
                   4632: 
                   4633: sub get {
1.131     albertel 4634:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4635:    my $items='';
1.800     albertel 4636:    foreach my $item (@$storearr) {
                   4637:        $items.=&escape($item).'&';
1.191     harris41 4638:    }
1.12      www      4639:    $items=~s/\&$//;
1.620     albertel 4640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4641:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4642:    my $uhome=&homeserver($uname,$udomain);
                   4643: 
1.133     albertel 4644:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4645:    my @pairs=split(/\&/,$rep);
1.273     albertel 4646:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4647:      return @pairs;
                   4648:    }
1.15      www      4649:    my %returnhash=();
1.42      www      4650:    my $i=0;
1.800     albertel 4651:    foreach my $item (@$storearr) {
                   4652:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4653:       $i++;
1.191     harris41 4654:    }
1.15      www      4655:    return %returnhash;
1.27      www      4656: }
                   4657: 
                   4658: # --------------------------------------------------------------- del interface
                   4659: 
                   4660: sub del {
1.133     albertel 4661:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4662:    my $items='';
1.800     albertel 4663:    foreach my $item (@$storearr) {
                   4664:        $items.=&escape($item).'&';
1.191     harris41 4665:    }
1.984     neumanie 4666: 
1.27      www      4667:    $items=~s/\&$//;
1.620     albertel 4668:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4669:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4670:    my $uhome=&homeserver($uname,$udomain);
                   4671:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4672: }
                   4673: 
                   4674: # -------------------------------------------------------------- dump interface
                   4675: 
                   4676: sub dump {
1.1086    raeburn  4677:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4678:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4679:     if (!$uname) { $uname=$env{'user.name'}; }
                   4680:     my $uhome=&homeserver($uname,$udomain);
                   4681:     if ($regexp) {
                   4682: 	$regexp=&escape($regexp);
                   4683:     } else {
                   4684: 	$regexp='.';
                   4685:     }
1.1086    raeburn  4686:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4687:     my @pairs=split(/\&/,$rep);
                   4688:     my %returnhash=();
1.1098    foxr     4689:     if (!($rep =~ /^error/ )) {
                   4690: 	foreach my $item (@pairs) {
                   4691: 	    my ($key,$value)=split(/=/,$item,2);
                   4692: 	    $key = &unescape($key);
                   4693: 	    next if ($key =~ /^error: 2 /);
                   4694: 	    $returnhash{$key}=&thaw_unescape($value);
                   4695: 	}
1.755     albertel 4696:     }
                   4697:     return %returnhash;
1.407     www      4698: }
                   4699: 
1.1098    foxr     4700: 
1.717     albertel 4701: # --------------------------------------------------------- dumpstore interface
                   4702: 
                   4703: sub dumpstore {
                   4704:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4705:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4706:    if (!$uname) { $uname=$env{'user.name'}; }
                   4707:    my $uhome=&homeserver($uname,$udomain);
                   4708:    if ($regexp) {
                   4709:        $regexp=&escape($regexp);
                   4710:    } else {
                   4711:        $regexp='.';
                   4712:    }
                   4713:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4714:    my @pairs=split(/\&/,$rep);
                   4715:    my %returnhash=();
                   4716:    foreach my $item (@pairs) {
                   4717:        my ($key,$value)=split(/=/,$item,2);
                   4718:        next if ($key =~ /^error: 2 /);
                   4719:        $returnhash{$key}=&thaw_unescape($value);
                   4720:    }
                   4721:    return %returnhash;
1.717     albertel 4722: }
                   4723: 
1.407     www      4724: # -------------------------------------------------------------- keys interface
                   4725: 
                   4726: sub getkeys {
                   4727:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4728:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4729:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4730:    my $uhome=&homeserver($uname,$udomain);
                   4731:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4732:    my @keyarray=();
1.800     albertel 4733:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4734:       next if ($key =~ /^error: 2 /);
1.800     albertel 4735:       push(@keyarray,&unescape($key));
1.407     www      4736:    }
                   4737:    return @keyarray;
1.318     matthew  4738: }
                   4739: 
1.319     matthew  4740: # --------------------------------------------------------------- currentdump
                   4741: sub currentdump {
1.328     matthew  4742:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4743:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4744:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4745:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4746:    my $uhome = &homeserver($sname,$sdom);
                   4747:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4748:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4749:    #
1.318     matthew  4750:    my %returnhash=();
1.319     matthew  4751:    #
                   4752:    if ($rep eq "unknown_cmd") { 
                   4753:        # an old lond will not know currentdump
                   4754:        # Do a dump and make it look like a currentdump
1.822     albertel 4755:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4756:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4757:        my %hash = @tmp;
                   4758:        @tmp=();
1.424     matthew  4759:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4760:    } else {
                   4761:        my @pairs=split(/\&/,$rep);
1.800     albertel 4762:        foreach my $pair (@pairs) {
                   4763:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4764:            my ($symb,$param) = split(/:/,$key);
                   4765:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4766:                                                         &thaw_unescape($value);
1.319     matthew  4767:        }
1.191     harris41 4768:    }
1.12      www      4769:    return %returnhash;
1.424     matthew  4770: }
                   4771: 
                   4772: sub convert_dump_to_currentdump{
                   4773:     my %hash = %{shift()};
                   4774:     my %returnhash;
                   4775:     # Code ripped from lond, essentially.  The only difference
                   4776:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4777:     # we might run in to problems with parameter names =~ /^v\./
                   4778:     while (my ($key,$value) = each(%hash)) {
                   4779:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4780: 	$symb  = &unescape($symb);
                   4781: 	$param = &unescape($param);
1.424     matthew  4782:         next if ($v eq 'version' || $symb eq 'keys');
                   4783:         next if (exists($returnhash{$symb}) &&
                   4784:                  exists($returnhash{$symb}->{$param}) &&
                   4785:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4786:         $returnhash{$symb}->{$param}=$value;
                   4787:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4788:     }
                   4789:     #
                   4790:     # Remove all of the keys in the hashes which keep track of
                   4791:     # the version of the parameter.
                   4792:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4793:         # use a foreach because we are going to delete from the hash.
                   4794:         foreach my $key (keys(%$param_hash)) {
                   4795:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4796:         }
                   4797:     }
                   4798:     return \%returnhash;
1.12      www      4799: }
                   4800: 
1.627     albertel 4801: # ------------------------------------------------------ critical inc interface
                   4802: 
                   4803: sub cinc {
                   4804:     return &inc(@_,'critical');
                   4805: }
                   4806: 
1.449     matthew  4807: # --------------------------------------------------------------- inc interface
                   4808: 
                   4809: sub inc {
1.627     albertel 4810:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4811:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4812:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4813:     my $uhome=&homeserver($uname,$udomain);
                   4814:     my $items='';
                   4815:     if (! ref($store)) {
                   4816:         # got a single value, so use that instead
                   4817:         $items = &escape($store).'=&';
                   4818:     } elsif (ref($store) eq 'SCALAR') {
                   4819:         $items = &escape($$store).'=&';        
                   4820:     } elsif (ref($store) eq 'ARRAY') {
                   4821:         $items = join('=&',map {&escape($_);} @{$store});
                   4822:     } elsif (ref($store) eq 'HASH') {
                   4823:         while (my($key,$value) = each(%{$store})) {
                   4824:             $items.= &escape($key).'='.&escape($value).'&';
                   4825:         }
                   4826:     }
                   4827:     $items=~s/\&$//;
1.627     albertel 4828:     if ($critical) {
                   4829: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4830:     } else {
                   4831: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4832:     }
1.449     matthew  4833: }
                   4834: 
1.12      www      4835: # --------------------------------------------------------------- put interface
                   4836: 
                   4837: sub put {
1.134     albertel 4838:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4839:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4840:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4841:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4842:    my $items='';
1.800     albertel 4843:    foreach my $item (keys(%$storehash)) {
                   4844:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4845:    }
1.12      www      4846:    $items=~s/\&$//;
1.134     albertel 4847:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4848: }
                   4849: 
1.631     albertel 4850: # ------------------------------------------------------------ newput interface
                   4851: 
                   4852: sub newput {
                   4853:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4855:    if (!$uname) { $uname=$env{'user.name'}; }
                   4856:    my $uhome=&homeserver($uname,$udomain);
                   4857:    my $items='';
                   4858:    foreach my $key (keys(%$storehash)) {
                   4859:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4860:    }
                   4861:    $items=~s/\&$//;
                   4862:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4863: }
                   4864: 
                   4865: # ---------------------------------------------------------  putstore interface
                   4866: 
1.524     raeburn  4867: sub putstore {
1.715     albertel 4868:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4869:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4870:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4871:    my $uhome=&homeserver($uname,$udomain);
                   4872:    my $items='';
1.715     albertel 4873:    foreach my $key (keys(%$storehash)) {
                   4874:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4875:    }
1.715     albertel 4876:    $items=~s/\&$//;
1.716     albertel 4877:    my $esc_symb=&escape($symb);
                   4878:    my $esc_v=&escape($version);
1.715     albertel 4879:    my $reply =
1.716     albertel 4880:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4881: 	      $uhome);
                   4882:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4883:        # gfall back to way things use to be done
1.715     albertel 4884:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4885: 			    $uname);
1.524     raeburn  4886:    }
1.715     albertel 4887:    return $reply;
                   4888: }
                   4889: 
                   4890: sub old_putstore {
1.716     albertel 4891:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4892:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4893:     if (!$uname) { $uname=$env{'user.name'}; }
                   4894:     my $uhome=&homeserver($uname,$udomain);
                   4895:     my %newstorehash;
1.800     albertel 4896:     foreach my $item (keys(%$storehash)) {
                   4897: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4898: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4899:     }
                   4900:     my $items='';
                   4901:     my %allitems = ();
1.800     albertel 4902:     foreach my $item (keys(%newstorehash)) {
                   4903: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4904: 	    my $key = $1.':keys:'.$2;
                   4905: 	    $allitems{$key} .= $3.':';
                   4906: 	}
1.800     albertel 4907: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4908:     }
1.800     albertel 4909:     foreach my $item (keys(%allitems)) {
                   4910: 	$allitems{$item} =~ s/\:$//;
                   4911: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4912:     }
                   4913:     $items=~s/\&$//;
                   4914:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4915: }
                   4916: 
1.47      www      4917: # ------------------------------------------------------ critical put interface
                   4918: 
                   4919: sub cput {
1.134     albertel 4920:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4921:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4922:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4923:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4924:    my $items='';
1.800     albertel 4925:    foreach my $item (keys(%$storehash)) {
                   4926:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4927:    }
1.47      www      4928:    $items=~s/\&$//;
1.134     albertel 4929:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4930: }
                   4931: 
                   4932: # -------------------------------------------------------------- eget interface
                   4933: 
                   4934: sub eget {
1.133     albertel 4935:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4936:    my $items='';
1.800     albertel 4937:    foreach my $item (@$storearr) {
                   4938:        $items.=&escape($item).'&';
1.191     harris41 4939:    }
1.12      www      4940:    $items=~s/\&$//;
1.620     albertel 4941:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4942:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4943:    my $uhome=&homeserver($uname,$udomain);
                   4944:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4945:    my @pairs=split(/\&/,$rep);
                   4946:    my %returnhash=();
1.42      www      4947:    my $i=0;
1.800     albertel 4948:    foreach my $item (@$storearr) {
                   4949:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4950:       $i++;
1.191     harris41 4951:    }
1.12      www      4952:    return %returnhash;
                   4953: }
                   4954: 
1.667     albertel 4955: # ------------------------------------------------------------ tmpput interface
                   4956: sub tmpput {
1.802     raeburn  4957:     my ($storehash,$server,$context)=@_;
1.667     albertel 4958:     my $items='';
1.800     albertel 4959:     foreach my $item (keys(%$storehash)) {
                   4960: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4961:     }
                   4962:     $items=~s/\&$//;
1.802     raeburn  4963:     if (defined($context)) {
                   4964:         $items .= ':'.&escape($context);
                   4965:     }
1.667     albertel 4966:     return &reply("tmpput:$items",$server);
                   4967: }
                   4968: 
                   4969: # ------------------------------------------------------------ tmpget interface
                   4970: sub tmpget {
1.688     albertel 4971:     my ($token,$server)=@_;
                   4972:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4973:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4974:     my %returnhash;
                   4975:     foreach my $item (split(/\&/,$rep)) {
                   4976: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4977:         next if ($key =~ /^error: 2 /);
1.667     albertel 4978: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4979:     }
                   4980:     return %returnhash;
                   4981: }
                   4982: 
1.1113    raeburn  4983: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4984: sub tmpdel {
                   4985:     my ($token,$server)=@_;
                   4986:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4987:     return &reply("tmpdel:$token",$server);
                   4988: }
                   4989: 
1.765     albertel 4990: # -------------------------------------------------- portfolio access checking
                   4991: 
                   4992: sub portfolio_access {
1.766     albertel 4993:     my ($requrl) = @_;
1.765     albertel 4994:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4995:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4996:     if ($result) {
                   4997:         my %setters;
                   4998:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4999:             my ($startblock,$endblock) =
                   5000:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5001:             if ($startblock && $endblock) {
                   5002:                 return 'B';
                   5003:             }
                   5004:         } else {
                   5005:             my ($startblock,$endblock) =
                   5006:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5007:             if ($startblock && $endblock) {
                   5008:                 return 'B';
                   5009:             }
                   5010:         }
                   5011:     }
1.765     albertel 5012:     if ($result eq 'ok') {
1.766     albertel 5013:        return 'F';
1.765     albertel 5014:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5015:        return 'A';
1.765     albertel 5016:     }
1.766     albertel 5017:     return '';
1.765     albertel 5018: }
                   5019: 
                   5020: sub get_portfolio_access {
1.767     albertel 5021:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5022: 
                   5023:     if (!ref($access_hash)) {
                   5024: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5025: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5026: 						   $file_name);
                   5027: 	$access_hash = $access_controls{$file_name};
                   5028:     }
                   5029: 
1.765     albertel 5030:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5031:     my $now = time;
                   5032:     if (ref($access_hash) eq 'HASH') {
                   5033:         foreach my $key (keys(%{$access_hash})) {
                   5034:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5035:             if ($start > $now) {
                   5036:                 next;
                   5037:             }
                   5038:             if ($end && $end<$now) {
                   5039:                 next;
                   5040:             }
                   5041:             if ($scope eq 'public') {
                   5042:                 $public = $key;
                   5043:                 last;
                   5044:             } elsif ($scope eq 'guest') {
                   5045:                 $guest = $key;
                   5046:             } elsif ($scope eq 'domains') {
                   5047:                 push(@domains,$key);
                   5048:             } elsif ($scope eq 'users') {
                   5049:                 push(@users,$key);
                   5050:             } elsif ($scope eq 'course') {
                   5051:                 push(@courses,$key);
                   5052:             } elsif ($scope eq 'group') {
                   5053:                 push(@groups,$key);
                   5054:             }
                   5055:         }
                   5056:         if ($public) {
                   5057:             return 'ok';
                   5058:         }
                   5059:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5060:             if ($guest) {
                   5061:                 return $guest;
                   5062:             }
                   5063:         } else {
                   5064:             if (@domains > 0) {
                   5065:                 foreach my $domkey (@domains) {
                   5066:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5067:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5068:                             return 'ok';
                   5069:                         }
                   5070:                     }
                   5071:                 }
                   5072:             }
                   5073:             if (@users > 0) {
                   5074:                 foreach my $userkey (@users) {
1.865     raeburn  5075:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5076:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5077:                             if (ref($item) eq 'HASH') {
                   5078:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5079:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5080:                                     return 'ok';
                   5081:                                 }
                   5082:                             }
                   5083:                         }
                   5084:                     } 
1.765     albertel 5085:                 }
                   5086:             }
                   5087:             my %roleshash;
                   5088:             my @courses_and_groups = @courses;
                   5089:             push(@courses_and_groups,@groups); 
                   5090:             if (@courses_and_groups > 0) {
                   5091:                 my (%allgroups,%allroles); 
                   5092:                 my ($start,$end,$role,$sec,$group);
                   5093:                 foreach my $envkey (%env) {
1.1060    raeburn  5094:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5095:                         my $cid = $2.'_'.$3; 
                   5096:                         if ($1 eq 'gr') {
                   5097:                             $group = $4;
                   5098:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5099:                         } else {
                   5100:                             if ($4 eq '') {
                   5101:                                 $sec = 'none';
                   5102:                             } else {
                   5103:                                 $sec = $4;
                   5104:                             }
                   5105:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5106:                         }
1.811     albertel 5107:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5108:                         my $cid = $2.'_'.$3;
                   5109:                         if ($4 eq '') {
                   5110:                             $sec = 'none';
                   5111:                         } else {
                   5112:                             $sec = $4;
                   5113:                         }
                   5114:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5115:                     }
                   5116:                 }
                   5117:                 if (keys(%allroles) == 0) {
                   5118:                     return;
                   5119:                 }
                   5120:                 foreach my $key (@courses_and_groups) {
                   5121:                     my %content = %{$$access_hash{$key}};
                   5122:                     my $cnum = $content{'number'};
                   5123:                     my $cdom = $content{'domain'};
                   5124:                     my $cid = $cdom.'_'.$cnum;
                   5125:                     if (!exists($allroles{$cid})) {
                   5126:                         next;
                   5127:                     }    
                   5128:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5129:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5130:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5131:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5132:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5133:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5134:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5135:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5136:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5137:                                         if (grep/^all$/,@sections) {
                   5138:                                             return 'ok';
                   5139:                                         } else {
                   5140:                                             if (grep/^$sec$/,@sections) {
                   5141:                                                 return 'ok';
                   5142:                                             }
                   5143:                                         }
                   5144:                                     }
                   5145:                                 }
                   5146:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5147:                                     if (grep/^none$/,@groups) {
                   5148:                                         return 'ok';
                   5149:                                     }
                   5150:                                 } else {
                   5151:                                     if (grep/^all$/,@groups) {
                   5152:                                         return 'ok';
                   5153:                                     } 
                   5154:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5155:                                         if (grep/^$group$/,@groups) {
                   5156:                                             return 'ok';
                   5157:                                         }
                   5158:                                     }
                   5159:                                 } 
                   5160:                             }
                   5161:                         }
                   5162:                     }
                   5163:                 }
                   5164:             }
                   5165:             if ($guest) {
                   5166:                 return $guest;
                   5167:             }
                   5168:         }
                   5169:     }
                   5170:     return;
                   5171: }
                   5172: 
                   5173: sub course_group_datechecker {
                   5174:     my ($dates,$now,$status) = @_;
                   5175:     my ($start,$end) = split(/\./,$dates);
                   5176:     if (!$start && !$end) {
                   5177:         return 'ok';
                   5178:     }
                   5179:     if (grep/^active$/,@{$status}) {
                   5180:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5181:             return 'ok';
                   5182:         }
                   5183:     }
                   5184:     if (grep/^previous$/,@{$status}) {
                   5185:         if ($end > $now ) {
                   5186:             return 'ok';
                   5187:         }
                   5188:     }
                   5189:     if (grep/^future$/,@{$status}) {
                   5190:         if ($start > $now) {
                   5191:             return 'ok';
                   5192:         }
                   5193:     }
                   5194:     return; 
                   5195: }
                   5196: 
                   5197: sub parse_portfolio_url {
                   5198:     my ($url) = @_;
                   5199: 
                   5200:     my ($type,$udom,$unum,$group,$file_name);
                   5201:     
1.823     albertel 5202:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5203: 	$type = 1;
                   5204:         $udom = $1;
                   5205:         $unum = $2;
                   5206:         $file_name = $3;
1.823     albertel 5207:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5208: 	$type = 2;
                   5209:         $udom = $1;
                   5210:         $unum = $2;
                   5211:         $group = $3;
                   5212:         $file_name = $3.'/'.$4;
                   5213:     }
                   5214:     if (wantarray) {
                   5215: 	return ($type,$udom,$unum,$file_name,$group);
                   5216:     }
                   5217:     return $type;
                   5218: }
                   5219: 
                   5220: sub is_portfolio_url {
                   5221:     my ($url) = @_;
                   5222:     return scalar(&parse_portfolio_url($url));
                   5223: }
                   5224: 
1.798     raeburn  5225: sub is_portfolio_file {
                   5226:     my ($file) = @_;
1.820     raeburn  5227:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5228:         return 1;
                   5229:     }
                   5230:     return;
                   5231: }
                   5232: 
1.976     raeburn  5233: sub usertools_access {
1.1084    raeburn  5234:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5235:     my ($access,%tools);
                   5236:     if ($context eq '') {
                   5237:         $context = 'tools';
                   5238:     }
                   5239:     if ($context eq 'requestcourses') {
                   5240:         %tools = (
                   5241:                       official   => 1,
                   5242:                       unofficial => 1,
1.1006    raeburn  5243:                       community  => 1,
1.985     raeburn  5244:                  );
                   5245:     } else {
                   5246:         %tools = (
                   5247:                       aboutme   => 1,
                   5248:                       blog      => 1,
                   5249:                       portfolio => 1,
                   5250:                  );
                   5251:     }
1.976     raeburn  5252:     return if (!defined($tools{$tool}));
                   5253: 
                   5254:     if ((!defined($udom)) || (!defined($uname))) {
                   5255:         $udom = $env{'user.domain'};
                   5256:         $uname = $env{'user.name'};
                   5257:     }
                   5258: 
1.978     raeburn  5259:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5260:         if ($action ne 'reload') {
1.985     raeburn  5261:             if ($context eq 'requestcourses') {
                   5262:                 return $env{'environment.canrequest.'.$tool};
                   5263:             } else {
                   5264:                 return $env{'environment.availabletools.'.$tool};
                   5265:             }
                   5266:         }
1.976     raeburn  5267:     }
                   5268: 
                   5269:     my ($toolstatus,$inststatus);
                   5270: 
1.985     raeburn  5271:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5272:          ($action ne 'reload')) {
                   5273:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5274:         $inststatus = $env{'environment.inststatus'};
                   5275:     } else {
1.1084    raeburn  5276:         if (ref($userenvref) eq 'HASH') {
                   5277:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5278:             $inststatus = $userenvref->{'inststatus'};
                   5279:         } else {
                   5280:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5281:             $toolstatus = $userenv{$context.'.'.$tool};
                   5282:             $inststatus = $userenv{'inststatus'};
                   5283:         }
1.976     raeburn  5284:     }
                   5285: 
                   5286:     if ($toolstatus ne '') {
                   5287:         if ($toolstatus) {
                   5288:             $access = 1;
                   5289:         } else {
                   5290:             $access = 0;
                   5291:         }
                   5292:         return $access;
                   5293:     }
                   5294: 
1.1084    raeburn  5295:     my ($is_adv,%domdef);
                   5296:     if (ref($is_advref) eq 'HASH') {
                   5297:         $is_adv = $is_advref->{'is_adv'};
                   5298:     } else {
                   5299:         $is_adv = &is_advanced_user($udom,$uname);
                   5300:     }
                   5301:     if (ref($domdefref) eq 'HASH') {
                   5302:         %domdef = %{$domdefref};
                   5303:     } else {
                   5304:         %domdef = &get_domain_defaults($udom);
                   5305:     }
1.976     raeburn  5306:     if (ref($domdef{$tool}) eq 'HASH') {
                   5307:         if ($is_adv) {
                   5308:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5309:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5310:                     $access = 1;
                   5311:                 } else {
                   5312:                     $access = 0;
                   5313:                 }
                   5314:                 return $access;
                   5315:             }
                   5316:         }
                   5317:         if ($inststatus ne '') {
                   5318:             my ($hasaccess,$hasnoaccess);
                   5319:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5320:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5321:                     if ($domdef{$tool}{$affiliation}) {
                   5322:                         $hasaccess = 1;
                   5323:                     } else {
                   5324:                         $hasnoaccess = 1;
                   5325:                     }
                   5326:                 }
                   5327:             }
                   5328:             if ($hasaccess || $hasnoaccess) {
                   5329:                 if ($hasaccess) {
                   5330:                     $access = 1;
                   5331:                 } elsif ($hasnoaccess) {
                   5332:                     $access = 0; 
                   5333:                 }
                   5334:                 return $access;
                   5335:             }
                   5336:         } else {
                   5337:             if ($domdef{$tool}{'default'} ne '') {
                   5338:                 if ($domdef{$tool}{'default'}) {
                   5339:                     $access = 1;
                   5340:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5341:                     $access = 0;
                   5342:                 }
                   5343:                 return $access;
                   5344:             }
                   5345:         }
                   5346:     } else {
1.985     raeburn  5347:         if ($context eq 'tools') {
                   5348:             $access = 1;
                   5349:         } else {
                   5350:             $access = 0;
                   5351:         }
1.976     raeburn  5352:         return $access;
                   5353:     }
                   5354: }
                   5355: 
1.1050    raeburn  5356: sub is_course_owner {
                   5357:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5358:     if (($udom eq '') || ($uname eq '')) {
                   5359:         $udom = $env{'user.domain'};
                   5360:         $uname = $env{'user.name'};
                   5361:     }
                   5362:     unless (($udom eq '') || ($uname eq '')) {
                   5363:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5364:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5365:                 return 1;
                   5366:             } else {
                   5367:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5368:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5369:                     return 1;
                   5370:                 }
                   5371:             }
                   5372:         }
                   5373:     }
                   5374:     return;
                   5375: }
                   5376: 
1.976     raeburn  5377: sub is_advanced_user {
                   5378:     my ($udom,$uname) = @_;
1.1085    raeburn  5379:     if ($udom ne '' && $uname ne '') {
                   5380:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128  ! raeburn  5381:             if (wantarray) {
        !          5382:                 return ($env{'user.adv'},$env{'user.author'});
        !          5383:             } else {
        !          5384:                 return $env{'user.adv'};
        !          5385:             }
1.1085    raeburn  5386:         }
                   5387:     }
1.976     raeburn  5388:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5389:     my %allroles;
1.1128  ! raeburn  5390:     my ($is_adv,$is_author);
1.976     raeburn  5391:     foreach my $role (keys(%roleshash)) {
                   5392:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5393:         my $area = '/'.$tdomain.'/'.$trest;
                   5394:         if ($sec ne '') {
                   5395:             $area .= '/'.$sec;
                   5396:         }
                   5397:         if (($area ne '') && ($trole ne '')) {
                   5398:             my $spec=$trole.'.'.$area;
                   5399:             if ($trole =~ /^cr\//) {
                   5400:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5401:             } elsif ($trole ne 'gr') {
                   5402:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5403:             }
1.1128  ! raeburn  5404:             if ($trole eq 'au') {
        !          5405:                 $is_author = 1;
        !          5406:             }
1.976     raeburn  5407:         }
                   5408:     }
                   5409:     foreach my $role (keys(%allroles)) {
                   5410:         last if ($is_adv);
                   5411:         foreach my $item (split(/:/,$allroles{$role})) {
                   5412:             if ($item ne '') {
                   5413:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5414:                 if ($privilege eq 'adv') {
                   5415:                     $is_adv = 1;
                   5416:                     last;
                   5417:                 }
                   5418:             }
                   5419:         }
                   5420:     }
1.1128  ! raeburn  5421:     if (wantarray) {
        !          5422:         return ($is_adv,$is_author);
        !          5423:     }
1.976     raeburn  5424:     return $is_adv;
                   5425: }
1.798     raeburn  5426: 
1.1035    raeburn  5427: sub check_can_request {
1.1036    raeburn  5428:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5429:     my $canreq = 0;
                   5430:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5431:     my @options = ('approval','validate','autolimit');
                   5432:     my $optregex = join('|',@options);
                   5433:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5434:         foreach my $type (@{$types}) {
                   5435:             if (&usertools_access($env{'user.name'},
                   5436:                                   $env{'user.domain'},
                   5437:                                   $type,undef,'requestcourses')) {
                   5438:                 $canreq ++;
1.1036    raeburn  5439:                 if (ref($request_domains) eq 'HASH') {
                   5440:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5441:                 }
1.1035    raeburn  5442:                 if ($dom eq $env{'user.domain'}) {
                   5443:                     $can_request->{$type} = 1;
                   5444:                 }
                   5445:             }
                   5446:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5447:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5448:                 if (@curr > 0) {
1.1036    raeburn  5449:                     foreach my $item (@curr) {
                   5450:                         if (ref($request_domains) eq 'HASH') {
                   5451:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5452:                             if ($otherdom ne '') {
                   5453:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5454:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5455:                                         push(@{$request_domains->{$type}},$otherdom);
                   5456:                                     }
                   5457:                                 } else {
                   5458:                                     push(@{$request_domains->{$type}},$otherdom);
                   5459:                                 }
                   5460:                             }
                   5461:                         }
                   5462:                     }
                   5463:                     unless($dom eq $env{'user.domain'}) {
                   5464:                         $canreq ++;
1.1035    raeburn  5465:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5466:                             $can_request->{$type} = 1;
                   5467:                         }
                   5468:                     }
                   5469:                 }
                   5470:             }
                   5471:         }
                   5472:     }
                   5473:     return $canreq;
                   5474: }
                   5475: 
1.341     www      5476: # ---------------------------------------------- Custom access rule evaluation
                   5477: 
                   5478: sub customaccess {
                   5479:     my ($priv,$uri)=@_;
1.807     albertel 5480:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5481:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5482:     $udom = &LONCAPA::clean_domain($udom);
                   5483:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5484:     my $access=0;
1.800     albertel 5485:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5486: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5487: 	if ($type eq 'user') {
                   5488: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5489: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5490: 		if ($tdom) {
                   5491: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5492: 		}
1.896     albertel 5493: 		if ($tuname) {
                   5494: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5495: 		}
                   5496: 		$access=($effect eq 'allow');
                   5497: 		last;
                   5498: 	    }
                   5499: 	} else {
                   5500: 	    if ($role) {
                   5501: 		if ($role ne $urole) { next; }
                   5502: 	    }
                   5503: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5504: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5505: 		if ($tdom) {
                   5506: 		    if ($tdom ne $udom) { next; }
                   5507: 		}
                   5508: 		if ($tcrs) {
                   5509: 		    if ($tcrs ne $ucrs) { next; }
                   5510: 		}
                   5511: 		if ($tsec) {
                   5512: 		    if ($tsec ne $usec) { next; }
                   5513: 		}
                   5514: 		$access=($effect eq 'allow');
                   5515: 		last;
                   5516: 	    }
                   5517: 	    if ($realm eq '' && $role eq '') {
                   5518: 		$access=($effect eq 'allow');
                   5519: 	    }
1.402     bowersj2 5520: 	}
1.341     www      5521:     }
                   5522:     return $access;
                   5523: }
                   5524: 
1.103     harris41 5525: # ------------------------------------------------- Check for a user privilege
1.12      www      5526: 
                   5527: sub allowed {
1.810     raeburn  5528:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5529:     my $ver_orguri=$uri;
1.439     www      5530:     $uri=&deversion($uri);
1.152     www      5531:     my $orguri=$uri;
1.52      www      5532:     $uri=&declutter($uri);
1.809     raeburn  5533: 
1.810     raeburn  5534:     if ($priv eq 'evb') {
                   5535: # Evade communication block restrictions for specified role in a course
                   5536:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5537:             return $1;
                   5538:         } else {
                   5539:             return;
                   5540:         }
                   5541:     }
                   5542: 
1.620     albertel 5543:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5544: # Free bre access to adm and meta resources
1.775     albertel 5545:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5546: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5547: 	&& ($priv eq 'bre')) {
1.14      www      5548: 	return 'F';
1.159     www      5549:     }
                   5550: 
1.545     banghart 5551: # Free bre access to user's own portfolio contents
1.714     raeburn  5552:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5553:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5554: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5555:         my %setters;
                   5556:         my ($startblock,$endblock) = 
                   5557:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5558:         if ($startblock && $endblock) {
                   5559:             return 'B';
                   5560:         } else {
                   5561:             return 'F';
                   5562:         }
1.545     banghart 5563:     }
                   5564: 
1.762     raeburn  5565: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5566:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5567:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5568:         if (exists($env{'request.course.id'})) {
                   5569:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5570:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5571:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5572:                 my $courseprivid=$env{'request.course.id'};
                   5573:                 $courseprivid=~s/\_/\//;
                   5574:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5575:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5576:                     return $1; 
1.762     raeburn  5577:                 } else {
                   5578:                     if ($env{'request.course.sec'}) {
                   5579:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5580:                     }
                   5581:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5582:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5583:                         return $2;
                   5584:                     }
1.714     raeburn  5585:                 }
                   5586:             }
                   5587:         }
                   5588:     }
                   5589: 
1.159     www      5590: # Free bre to public access
                   5591: 
                   5592:     if ($priv eq 'bre') {
1.238     www      5593:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5594: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5595:            return 'F'; 
                   5596:         }
1.238     www      5597:         if ($copyright eq 'priv') {
                   5598:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5599: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5600: 		return '';
                   5601:             }
                   5602:         }
                   5603:         if ($copyright eq 'domain') {
                   5604:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5605: 	    unless (($env{'user.domain'} eq $1) ||
                   5606:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5607: 		return '';
                   5608:             }
1.262     matthew  5609:         }
1.620     albertel 5610:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5611:             # Library role, so allow browsing of resources in this domain.
                   5612:             return 'F';
1.238     www      5613:         }
1.341     www      5614:         if ($copyright eq 'custom') {
                   5615: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5616:         }
1.14      www      5617:     }
1.264     matthew  5618:     # Domain coordinator is trying to create a course
1.620     albertel 5619:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5620:         # uri is the requested domain in this case.
                   5621:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5622:         # a role of dc for the domain in question.
1.620     albertel 5623:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5624:     }
1.29      www      5625: 
1.52      www      5626:     my $thisallowed='';
                   5627:     my $statecond=0;
                   5628:     my $courseprivid='';
                   5629: 
1.1039    raeburn  5630:     my $ownaccess;
1.1043    raeburn  5631:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5632:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5633:         if ($uri eq '') {
                   5634:             $ownaccess = 1;
                   5635:         } else {
                   5636:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5637:                 my $udom = $env{'user.domain'};
                   5638:                 my $uname = $env{'user.name'};
                   5639:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5640:                     $ownaccess = 1;
1.1040    raeburn  5641:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5642:                     unless ($uri =~ m{\.\./}) {
                   5643:                         $ownaccess = 1;
                   5644:                     }
                   5645:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5646:                     my $now = time;
                   5647:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5648:                         my $adom = $1;
                   5649:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5650:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5651:                                 my ($start,$end) = split('.',$env{$key});
                   5652:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5653:                                     $ownaccess = 1;
                   5654:                                     last;
                   5655:                                 }
                   5656:                             }
                   5657:                         }
                   5658:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5659:                         my $adom = $1;
                   5660:                         my $aname = $2;
1.1042    raeburn  5661:                         foreach my $role ('ca','aa') { 
                   5662:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5663:                                 my ($start,$end) =
                   5664:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5665:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5666:                                     $ownaccess = 1;
                   5667:                                     last;
                   5668:                                 }
1.1039    raeburn  5669:                             }
                   5670:                         }
                   5671:                     }
                   5672:                 }
                   5673:             }
                   5674:         }
                   5675:     }
                   5676: 
1.52      www      5677: # Course
                   5678: 
1.620     albertel 5679:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5680:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5681:             $thisallowed.=$1;
                   5682:         }
1.52      www      5683:     }
1.29      www      5684: 
1.52      www      5685: # Domain
                   5686: 
1.620     albertel 5687:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5688:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5689:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5690:             $thisallowed.=$1;
                   5691:         }
1.12      www      5692:     }
1.52      www      5693: 
                   5694: # Course: uri itself is a course
1.66      www      5695:     my $courseuri=$uri;
                   5696:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5697:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5698: 
1.620     albertel 5699:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5700:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5701:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5702:             $thisallowed.=$1;
                   5703:         }
1.12      www      5704:     }
1.29      www      5705: 
1.665     albertel 5706: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5707: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5708:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5709: 	$thisallowed='';
1.671     raeburn  5710:         my ($match)=&is_on_map($uri);
                   5711:         if ($match) {
                   5712:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5713:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5714:                 $thisallowed.=$1;
                   5715:             }
                   5716:         } else {
1.705     albertel 5717:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5718:             if ($refuri) {
                   5719:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5720:                     $thisallowed='F';
1.671     raeburn  5721:                 } else {
                   5722:                     $refuri=&declutter($refuri);
                   5723:                     my ($match) = &is_on_map($refuri);
                   5724:                     if ($match) {
                   5725:                         $thisallowed='F';
                   5726:                     }
1.669     raeburn  5727:                 }
1.671     raeburn  5728:             }
                   5729:         }
1.314     www      5730:     }
1.492     albertel 5731: 
1.766     albertel 5732:     if ($priv eq 'bre'
                   5733: 	&& $thisallowed ne 'F' 
                   5734: 	&& $thisallowed ne '2'
                   5735: 	&& &is_portfolio_url($uri)) {
                   5736: 	$thisallowed = &portfolio_access($uri);
                   5737:     }
                   5738:     
1.52      www      5739: # Full access at system, domain or course-wide level? Exit.
1.29      www      5740:     if ($thisallowed=~/F/) {
                   5741: 	return 'F';
                   5742:     }
                   5743: 
1.52      www      5744: # If this is generating or modifying users, exit with special codes
1.29      www      5745: 
1.643     www      5746:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5747: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5748: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5749: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5750: 	    unless ($auname) { return $thisallowed; }
                   5751: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5752: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5753: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5754: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5755: 	}
1.52      www      5756: 	return $thisallowed;
                   5757:     }
                   5758: #
1.103     harris41 5759: # Gathered so far: system, domain and course wide privileges
1.52      www      5760: #
                   5761: # Course: See if uri or referer is an individual resource that is part of 
                   5762: # the course
                   5763: 
1.620     albertel 5764:     if ($env{'request.course.id'}) {
1.232     www      5765: 
1.620     albertel 5766:        $courseprivid=$env{'request.course.id'};
                   5767:        if ($env{'request.course.sec'}) {
                   5768:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5769:        }
                   5770:        $courseprivid=~s/\_/\//;
                   5771:        my $checkreferer=1;
1.232     www      5772:        my ($match,$cond)=&is_on_map($uri);
                   5773:        if ($match) {
                   5774:            $statecond=$cond;
1.620     albertel 5775:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5776:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5777:                $thisallowed.=$1;
                   5778:                $checkreferer=0;
                   5779:            }
1.29      www      5780:        }
1.83      www      5781:        
1.148     www      5782:        if ($checkreferer) {
1.620     albertel 5783: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5784:             unless ($refuri) {
1.800     albertel 5785:                 foreach my $key (keys(%env)) {
                   5786: 		    if ($key=~/^httpref\..*\*/) {
                   5787: 			my $pattern=$key;
1.156     www      5788:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5789:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5790:                         $pattern=~s/\//\\\//g;
1.152     www      5791:                         if ($orguri=~/$pattern/) {
1.800     albertel 5792: 			    $refuri=$env{$key};
1.148     www      5793:                         }
                   5794:                     }
1.191     harris41 5795:                 }
1.148     www      5796:             }
1.232     www      5797: 
1.148     www      5798:          if ($refuri) { 
1.152     www      5799: 	  $refuri=&declutter($refuri);
1.232     www      5800:           my ($match,$cond)=&is_on_map($refuri);
                   5801:             if ($match) {
                   5802:               my $refstatecond=$cond;
1.620     albertel 5803:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5804:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5805:                   $thisallowed.=$1;
1.53      www      5806:                   $uri=$refuri;
                   5807:                   $statecond=$refstatecond;
1.52      www      5808:               }
                   5809:           }
1.148     www      5810:         }
1.29      www      5811:        }
1.52      www      5812:    }
1.29      www      5813: 
1.52      www      5814: #
1.103     harris41 5815: # Gathered now: all privileges that could apply, and condition number
1.52      www      5816: # 
                   5817: #
                   5818: # Full or no access?
                   5819: #
1.29      www      5820: 
1.52      www      5821:     if ($thisallowed=~/F/) {
                   5822: 	return 'F';
                   5823:     }
1.29      www      5824: 
1.52      www      5825:     unless ($thisallowed) {
                   5826:         return '';
                   5827:     }
1.29      www      5828: 
1.52      www      5829: # Restrictions exist, deal with them
                   5830: #
                   5831: #   C:according to course preferences
                   5832: #   R:according to resource settings
                   5833: #   L:unless locked
                   5834: #   X:according to user session state
                   5835: #
                   5836: 
                   5837: # Possibly locked functionality, check all courses
1.54      www      5838: # Locks might take effect only after 10 minutes cache expiration for other
                   5839: # courses, and 2 minutes for current course
1.52      www      5840: 
                   5841:     my $envkey;
                   5842:     if ($thisallowed=~/L/) {
1.1000    raeburn  5843:         foreach $envkey (keys(%env)) {
1.54      www      5844:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5845:                my $courseid=$2;
                   5846:                my $roleid=$1.'.'.$2;
1.92      www      5847:                $courseid=~s/^\///;
1.54      www      5848:                my $expiretime=600;
1.620     albertel 5849:                if ($env{'request.role'} eq $roleid) {
1.54      www      5850: 		  $expiretime=120;
                   5851:                }
                   5852: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5853:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5854:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5855: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5856:                }
1.620     albertel 5857:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5858:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5859: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5860:                        &log($env{'user.domain'},$env{'user.name'},
                   5861:                             $env{'user.home'},
1.57      www      5862:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5863:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5864:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5865: 		       return '';
                   5866:                    }
                   5867:                }
1.620     albertel 5868:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5869:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5870: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5871:                        &log($env{'user.domain'},$env{'user.name'},
                   5872:                             $env{'user.home'},
1.57      www      5873:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5874:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5875:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5876: 		       return '';
                   5877:                    }
                   5878:                }
                   5879: 	   }
1.29      www      5880:        }
1.52      www      5881:     }
                   5882:    
                   5883: #
                   5884: # Rest of the restrictions depend on selected course
                   5885: #
                   5886: 
1.620     albertel 5887:     unless ($env{'request.course.id'}) {
1.766     albertel 5888: 	if ($thisallowed eq 'A') {
                   5889: 	    return 'A';
1.814     raeburn  5890:         } elsif ($thisallowed eq 'B') {
                   5891:             return 'B';
1.766     albertel 5892: 	} else {
                   5893: 	    return '1';
                   5894: 	}
1.52      www      5895:     }
1.29      www      5896: 
1.52      www      5897: #
                   5898: # Now user is definitely in a course
                   5899: #
1.53      www      5900: 
                   5901: 
                   5902: # Course preferences
                   5903: 
                   5904:    if ($thisallowed=~/C/) {
1.620     albertel 5905:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5906:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5907:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5908: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5909: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5910: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5911: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5912: 			$env{'request.course.id'});
                   5913: 	   }
1.237     www      5914:            return '';
                   5915:        }
                   5916: 
1.620     albertel 5917:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5918: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5919: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5920: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5921: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5922: 			$env{'request.course.id'});
                   5923: 	   }
1.54      www      5924:            return '';
                   5925:        }
1.53      www      5926:    }
                   5927: 
                   5928: # Resource preferences
                   5929: 
                   5930:    if ($thisallowed=~/R/) {
1.620     albertel 5931:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5932:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5933: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5934: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5935: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5936: 	   }
                   5937: 	   return '';
1.54      www      5938:        }
1.53      www      5939:    }
1.30      www      5940: 
1.246     www      5941: # Restricted by state or randomout?
1.30      www      5942: 
1.52      www      5943:    if ($thisallowed=~/X/) {
1.620     albertel 5944:       if ($env{'acc.randomout'}) {
1.579     albertel 5945: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5946:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5947:             return ''; 
                   5948:          }
1.247     www      5949:       }
                   5950:       if (&condval($statecond)) {
1.52      www      5951: 	 return '2';
                   5952:       } else {
                   5953:          return '';
                   5954:       }
                   5955:    }
1.30      www      5956: 
1.766     albertel 5957:     if ($thisallowed eq 'A') {
                   5958: 	return 'A';
1.814     raeburn  5959:     } elsif ($thisallowed eq 'B') {
                   5960:         return 'B';
1.766     albertel 5961:     }
1.52      www      5962:    return 'F';
1.232     www      5963: }
                   5964: 
1.710     albertel 5965: sub split_uri_for_cond {
                   5966:     my $uri=&deversion(&declutter(shift));
                   5967:     my @uriparts=split(/\//,$uri);
                   5968:     my $filename=pop(@uriparts);
                   5969:     my $pathname=join('/',@uriparts);
                   5970:     return ($pathname,$filename);
                   5971: }
1.232     www      5972: # --------------------------------------------------- Is a resource on the map?
                   5973: 
                   5974: sub is_on_map {
1.710     albertel 5975:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5976:     #Trying to find the conditional for the file
1.620     albertel 5977:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5978: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5979:     if ($match) {
1.289     bowersj2 5980: 	return (1,$1);
                   5981:     } else {
1.434     www      5982: 	return (0,0);
1.289     bowersj2 5983:     }
1.12      www      5984: }
                   5985: 
1.427     www      5986: # --------------------------------------------------------- Get symb from alias
                   5987: 
                   5988: sub get_symb_from_alias {
                   5989:     my $symb=shift;
                   5990:     my ($map,$resid,$url)=&decode_symb($symb);
                   5991: # Already is a symb
                   5992:     if ($url) { return $symb; }
                   5993: # Must be an alias
                   5994:     my $aliassymb='';
                   5995:     my %bighash;
1.620     albertel 5996:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5997:                             &GDBM_READER(),0640)) {
                   5998:         my $rid=$bighash{'mapalias_'.$symb};
                   5999: 	if ($rid) {
                   6000: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6001: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6002: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6003: 	}
                   6004:         untie %bighash;
                   6005:     }
                   6006:     return $aliassymb;
                   6007: }
                   6008: 
1.12      www      6009: # ----------------------------------------------------------------- Define Role
                   6010: 
                   6011: sub definerole {
                   6012:   if (allowed('mcr','/')) {
                   6013:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6014:     foreach my $role (split(':',$sysrole)) {
                   6015: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6016:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6017:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6018: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6019:                return "refused:s:$crole&$cqual"; 
                   6020:             }
                   6021:         }
1.191     harris41 6022:     }
1.800     albertel 6023:     foreach my $role (split(':',$domrole)) {
                   6024: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6025:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6026:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6027: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6028:                return "refused:d:$crole&$cqual"; 
                   6029:             }
                   6030:         }
1.191     harris41 6031:     }
1.800     albertel 6032:     foreach my $role (split(':',$courole)) {
                   6033: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6034:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6035:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6036: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6037:                return "refused:c:$crole&$cqual"; 
                   6038:             }
                   6039:         }
1.191     harris41 6040:     }
1.620     albertel 6041:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6042:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6043: 	        "rolesdef_$rolename=".
                   6044:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6045:     return reply($command,$env{'user.home'});
1.12      www      6046:   } else {
                   6047:     return 'refused';
                   6048:   }
1.105     harris41 6049: }
                   6050: 
                   6051: # ---------------- Make a metadata query against the network of library servers
                   6052: 
                   6053: sub metadata_query {
1.244     matthew  6054:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6055:     my %rhash;
1.845     albertel 6056:     my %libserv = &all_library();
1.244     matthew  6057:     my @server_list = (defined($server_array) ? @$server_array
                   6058:                                               : keys(%libserv) );
                   6059:     for my $server (@server_list) {
1.118     harris41 6060: 	unless ($custom or $customshow) {
                   6061: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6062: 	    $rhash{$server}=$reply;
                   6063: 	}
                   6064: 	else {
                   6065: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6066: 			     &escape($custom).':'.&escape($customshow),
                   6067: 			     $server);
                   6068: 	    $rhash{$server}=$reply;
                   6069: 	}
1.112     harris41 6070:     }
1.118     harris41 6071:     return \%rhash;
1.240     www      6072: }
                   6073: 
                   6074: # ----------------------------------------- Send log queries and wait for reply
                   6075: 
                   6076: sub log_query {
                   6077:     my ($uname,$udom,$query,%filters)=@_;
                   6078:     my $uhome=&homeserver($uname,$udom);
                   6079:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6080:     my $uhost=&hostname($uhome);
1.800     albertel 6081:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6082:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6083:                        $uhome);
1.479     albertel 6084:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6085:     return get_query_reply($queryid);
                   6086: }
                   6087: 
1.818     raeburn  6088: # -------------------------- Update MySQL table for portfolio file
                   6089: 
                   6090: sub update_portfolio_table {
1.821     raeburn  6091:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6092:     if ($group ne '') {
                   6093:         $file_name =~s /^\Q$group\E//;
                   6094:     }
1.818     raeburn  6095:     my $homeserver = &homeserver($uname,$udom);
                   6096:     my $queryid=
1.821     raeburn  6097:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6098:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6099:     my $reply = &get_query_reply($queryid);
                   6100:     return $reply;
                   6101: }
                   6102: 
1.899     raeburn  6103: # -------------------------- Update MySQL allusers table
                   6104: 
                   6105: sub update_allusers_table {
                   6106:     my ($uname,$udom,$names) = @_;
                   6107:     my $homeserver = &homeserver($uname,$udom);
                   6108:     my $queryid=
                   6109:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6110:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6111:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6112:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6113:                'generation='.&escape($names->{'generation'}).'%%'.
                   6114:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6115:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6116:     return;
1.899     raeburn  6117: }
                   6118: 
1.508     raeburn  6119: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6120: 
                   6121: sub fetch_enrollment_query {
1.511     raeburn  6122:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6123:     my $homeserver;
1.547     raeburn  6124:     my $maxtries = 1;
1.508     raeburn  6125:     if ($context eq 'automated') {
                   6126:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6127:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6128:     } else {
                   6129:         $homeserver = &homeserver($cnum,$dom);
                   6130:     }
1.838     albertel 6131:     my $host=&hostname($homeserver);
1.506     raeburn  6132:     my $cmd = '';
1.1000    raeburn  6133:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6134:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6135:     }
                   6136:     $cmd =~ s/%%$//;
                   6137:     $cmd = &escape($cmd);
                   6138:     my $query = 'fetchenrollment';
1.620     albertel 6139:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6140:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6141:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6142:         return 'error: '.$queryid;
                   6143:     }
1.506     raeburn  6144:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6145:     my $tries = 1;
                   6146:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6147:         $reply = &get_query_reply($queryid);
                   6148:         $tries ++;
                   6149:     }
1.526     raeburn  6150:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6151:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6152:     } else {
1.901     albertel 6153:         my @responses = split(/:/,$reply);
1.515     raeburn  6154:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6155:             foreach my $line (@responses) {
                   6156:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6157:                 $$replyref{$key} = $value;
                   6158:             }
                   6159:         } else {
1.1117    foxr     6160:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6161:             foreach my $line (@responses) {
                   6162:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6163:                 $$replyref{$key} = $value;
                   6164:                 if ($value > 0) {
1.800     albertel 6165:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6166:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6167:                         my $destname = $pathname.'/'.$filename;
                   6168:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6169:                         if ($xml_classlist =~ /^error/) {
                   6170:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6171:                         } else {
1.506     raeburn  6172:                             if ( open(FILE,">$destname") ) {
                   6173:                                 print FILE &unescape($xml_classlist);
                   6174:                                 close(FILE);
1.526     raeburn  6175:                             } else {
                   6176:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6177:                             }
                   6178:                         }
                   6179:                     }
                   6180:                 }
                   6181:             }
                   6182:         }
                   6183:         return 'ok';
                   6184:     }
                   6185:     return 'error';
                   6186: }
                   6187: 
1.242     www      6188: sub get_query_reply {
                   6189:     my $queryid=shift;
1.1117    foxr     6190:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6191:     my $reply='';
                   6192:     for (1..100) {
                   6193: 	sleep 2;
                   6194:         if (-e $replyfile.'.end') {
1.448     albertel 6195: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6196: 		$reply = join('',<$fh>);
                   6197: 		close($fh);
1.240     www      6198: 	   } else { return 'error: reply_file_error'; }
1.242     www      6199:            return &unescape($reply);
                   6200: 	}
1.240     www      6201:     }
1.242     www      6202:     return 'timeout:'.$queryid;
1.240     www      6203: }
                   6204: 
                   6205: sub courselog_query {
1.241     www      6206: #
                   6207: # possible filters:
                   6208: # url: url or symb
                   6209: # username
                   6210: # domain
                   6211: # action: view, submit, grade
                   6212: # start: timestamp
                   6213: # end: timestamp
                   6214: #
1.240     www      6215:     my (%filters)=@_;
1.620     albertel 6216:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6217:     if ($filters{'url'}) {
                   6218: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6219:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6220:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6221:     }
1.620     albertel 6222:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6223:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6224:     return &log_query($cname,$cdom,'courselog',%filters);
                   6225: }
                   6226: 
                   6227: sub userlog_query {
1.858     raeburn  6228: #
                   6229: # possible filters:
                   6230: # action: log check role
                   6231: # start: timestamp
                   6232: # end: timestamp
                   6233: #
1.240     www      6234:     my ($uname,$udom,%filters)=@_;
                   6235:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6236: }
                   6237: 
1.506     raeburn  6238: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6239: 
                   6240: sub auto_run {
1.508     raeburn  6241:     my ($cnum,$cdom) = @_;
1.876     raeburn  6242:     my $response = 0;
                   6243:     my $settings;
                   6244:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6245:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6246:         $settings = $domconfig{'autoenroll'};
                   6247:         if ($settings->{'run'} eq '1') {
                   6248:             $response = 1;
                   6249:         }
                   6250:     } else {
1.934     raeburn  6251:         my $homeserver;
                   6252:         if (&is_course($cdom,$cnum)) {
                   6253:             $homeserver = &homeserver($cnum,$cdom);
                   6254:         } else {
                   6255:             $homeserver = &domain($cdom,'primary');
                   6256:         }
                   6257:         if ($homeserver ne 'no_host') {
                   6258:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6259:         }
1.876     raeburn  6260:     }
1.506     raeburn  6261:     return $response;
                   6262: }
1.776     albertel 6263: 
1.506     raeburn  6264: sub auto_get_sections {
1.508     raeburn  6265:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6266:     my $homeserver;
                   6267:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6268:         $homeserver = &homeserver($cnum,$cdom);
                   6269:     }
                   6270:     if (!defined($homeserver)) { 
                   6271:         if ($cdom =~ /^$match_domain$/) {
                   6272:             $homeserver = &domain($cdom,'primary');
                   6273:         }
                   6274:     }
                   6275:     my @secs;
                   6276:     if (defined($homeserver)) {
                   6277:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6278:         unless ($response eq 'refused') {
                   6279:             @secs = split(/:/,$response);
                   6280:         }
1.506     raeburn  6281:     }
                   6282:     return @secs;
                   6283: }
1.776     albertel 6284: 
1.506     raeburn  6285: sub auto_new_course {
1.1099    raeburn  6286:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6287:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6288:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6289:     return $response;
                   6290: }
1.776     albertel 6291: 
1.506     raeburn  6292: sub auto_validate_courseID {
1.508     raeburn  6293:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6294:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6295:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6296:     return $response;
                   6297: }
1.776     albertel 6298: 
1.1007    raeburn  6299: sub auto_validate_instcode {
1.1020    raeburn  6300:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6301:     my ($homeserver,$response);
                   6302:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6303:         $homeserver = &homeserver($cnum,$cdom);
                   6304:     }
                   6305:     if (!defined($homeserver)) {
                   6306:         if ($cdom =~ /^$match_domain$/) {
                   6307:             $homeserver = &domain($cdom,'primary');
                   6308:         }
                   6309:     }
1.1065    raeburn  6310:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6311:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6312:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6313:     return ($outcome,$description);
1.1007    raeburn  6314: }
                   6315: 
1.506     raeburn  6316: sub auto_create_password {
1.873     raeburn  6317:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6318:     my ($homeserver,$response);
1.506     raeburn  6319:     my $create_passwd = 0;
                   6320:     my $authchk = '';
1.873     raeburn  6321:     if ($udom =~ /^$match_domain$/) {
                   6322:         $homeserver = &domain($udom,'primary');
                   6323:     }
                   6324:     if ($homeserver eq '') {
                   6325:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6326:             $homeserver = &homeserver($cnum,$cdom);
                   6327:         }
                   6328:     }
                   6329:     if ($homeserver eq '') {
                   6330:         $authchk = 'nodomain';
1.506     raeburn  6331:     } else {
1.873     raeburn  6332:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6333:         if ($response eq 'refused') {
                   6334:             $authchk = 'refused';
                   6335:         } else {
1.901     albertel 6336:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6337:         }
1.506     raeburn  6338:     }
                   6339:     return ($authparam,$create_passwd,$authchk);
                   6340: }
                   6341: 
1.706     raeburn  6342: sub auto_photo_permission {
                   6343:     my ($cnum,$cdom,$students) = @_;
                   6344:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6345:     my ($outcome,$perm_reqd,$conditions) = 
                   6346: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6347:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6348: 	return (undef,undef);
                   6349:     }
1.706     raeburn  6350:     return ($outcome,$perm_reqd,$conditions);
                   6351: }
                   6352: 
                   6353: sub auto_checkphotos {
                   6354:     my ($uname,$udom,$pid) = @_;
                   6355:     my $homeserver = &homeserver($uname,$udom);
                   6356:     my ($result,$resulttype);
                   6357:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6358: 				   &escape($uname).':'.&escape($pid),
                   6359: 				   $homeserver));
1.709     albertel 6360:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6361: 	return (undef,undef);
                   6362:     }
1.706     raeburn  6363:     if ($outcome) {
                   6364:         ($result,$resulttype) = split(/:/,$outcome);
                   6365:     } 
                   6366:     return ($result,$resulttype);
                   6367: }
                   6368: 
                   6369: sub auto_photochoice {
                   6370:     my ($cnum,$cdom) = @_;
                   6371:     my $homeserver = &homeserver($cnum,$cdom);
                   6372:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6373: 						       &escape($cdom),
                   6374: 						       $homeserver)));
1.709     albertel 6375:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6376: 	return (undef,undef);
                   6377:     }
1.706     raeburn  6378:     return ($update,$comment);
                   6379: }
                   6380: 
                   6381: sub auto_photoupdate {
                   6382:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6383:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6384:     my $host=&hostname($homeserver);
1.706     raeburn  6385:     my $cmd = '';
                   6386:     my $maxtries = 1;
1.800     albertel 6387:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6388:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6389:     }
                   6390:     $cmd =~ s/%%$//;
                   6391:     $cmd = &escape($cmd);
                   6392:     my $query = 'institutionalphotos';
                   6393:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6394:     unless ($queryid=~/^\Q$host\E\_/) {
                   6395:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6396:         return 'error: '.$queryid;
                   6397:     }
                   6398:     my $reply = &get_query_reply($queryid);
                   6399:     my $tries = 1;
                   6400:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6401:         $reply = &get_query_reply($queryid);
                   6402:         $tries ++;
                   6403:     }
                   6404:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6405:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6406:     } else {
                   6407:         my @responses = split(/:/,$reply);
                   6408:         my $outcome = shift(@responses); 
                   6409:         foreach my $item (@responses) {
                   6410:             my ($key,$value) = split(/=/,$item);
                   6411:             $$photo{$key} = $value;
                   6412:         }
                   6413:         return $outcome;
                   6414:     }
                   6415:     return 'error';
                   6416: }
                   6417: 
1.521     raeburn  6418: sub auto_instcode_format {
1.793     albertel 6419:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6420: 	$cat_order) = @_;
1.521     raeburn  6421:     my $courses = '';
1.772     raeburn  6422:     my @homeservers;
1.521     raeburn  6423:     if ($caller eq 'global') {
1.841     albertel 6424: 	my %servers = &get_servers($codedom,'library');
                   6425: 	foreach my $tryserver (keys(%servers)) {
                   6426: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6427: 		push(@homeservers,$tryserver);
                   6428: 	    }
1.584     raeburn  6429:         }
1.1022    raeburn  6430:     } elsif ($caller eq 'requests') {
                   6431:         if ($codedom =~ /^$match_domain$/) {
                   6432:             my $chome = &domain($codedom,'primary');
                   6433:             unless ($chome eq 'no_host') {
                   6434:                 push(@homeservers,$chome);
                   6435:             }
                   6436:         }
1.521     raeburn  6437:     } else {
1.772     raeburn  6438:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6439:     }
1.793     albertel 6440:     foreach my $code (keys(%{$instcodes})) {
                   6441:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6442:     }
                   6443:     chop($courses);
1.772     raeburn  6444:     my $ok_response = 0;
                   6445:     my $response;
                   6446:     while (@homeservers > 0 && $ok_response == 0) {
                   6447:         my $server = shift(@homeservers); 
                   6448:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6449:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6450:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6451: 		split(/:/,$response);
1.772     raeburn  6452:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6453:             push(@{$codetitles},&str2array($codetitles_str));
                   6454:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6455:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6456:             $ok_response = 1;
                   6457:         }
                   6458:     }
                   6459:     if ($ok_response) {
1.521     raeburn  6460:         return 'ok';
1.772     raeburn  6461:     } else {
                   6462:         return $response;
1.521     raeburn  6463:     }
                   6464: }
                   6465: 
1.792     raeburn  6466: sub auto_instcode_defaults {
                   6467:     my ($domain,$returnhash,$code_order) = @_;
                   6468:     my @homeservers;
1.841     albertel 6469: 
                   6470:     my %servers = &get_servers($domain,'library');
                   6471:     foreach my $tryserver (keys(%servers)) {
                   6472: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6473: 	    push(@homeservers,$tryserver);
                   6474: 	}
1.792     raeburn  6475:     }
1.841     albertel 6476: 
1.792     raeburn  6477:     my $response;
1.841     albertel 6478:     foreach my $server (@homeservers) {
1.792     raeburn  6479:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6480:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6481: 	
                   6482: 	foreach my $pair (split(/\&/,$response)) {
                   6483: 	    my ($name,$value)=split(/\=/,$pair);
                   6484: 	    if ($name eq 'code_order') {
                   6485: 		@{$code_order} = split(/\&/,&unescape($value));
                   6486: 	    } else {
                   6487: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6488: 	    }
                   6489: 	}
                   6490: 	return 'ok';
1.792     raeburn  6491:     }
1.841     albertel 6492: 
                   6493:     return $response;
1.1003    raeburn  6494: }
                   6495: 
                   6496: sub auto_possible_instcodes {
1.1007    raeburn  6497:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6498:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6499:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6500:         return;
                   6501:     }
1.1003    raeburn  6502:     my (@homeservers,$uhome);
                   6503:     if (defined(&domain($domain,'primary'))) {
                   6504:         $uhome=&domain($domain,'primary');
                   6505:         push(@homeservers,&domain($domain,'primary'));
                   6506:     } else {
                   6507:         my %servers = &get_servers($domain,'library');
                   6508:         foreach my $tryserver (keys(%servers)) {
                   6509:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6510:                 push(@homeservers,$tryserver);
                   6511:             }
                   6512:         }
                   6513:     }
                   6514:     my $response;
                   6515:     foreach my $server (@homeservers) {
                   6516:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6517:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6518:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6519:             split(':',$response);
                   6520:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6521:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6522:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6523:             my ($name,$value)=split('=',$item);
                   6524:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6525:         }
                   6526:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6527:             my ($name,$value)=split('=',$item);
                   6528:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6529:         }
                   6530:         return 'ok';
                   6531:     }
                   6532:     return $response;
                   6533: }
1.792     raeburn  6534: 
1.1010    raeburn  6535: sub auto_courserequest_checks {
                   6536:     my ($dom) = @_;
1.1020    raeburn  6537:     my ($homeserver,%validations);
                   6538:     if ($dom =~ /^$match_domain$/) {
                   6539:         $homeserver = &domain($dom,'primary');
                   6540:     }
                   6541:     unless ($homeserver eq 'no_host') {
                   6542:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6543:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6544:             my @items = split(/&/,$response);
                   6545:             foreach my $item (@items) {
                   6546:                 my ($key,$value) = split('=',$item);
                   6547:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6548:             }
                   6549:         }
                   6550:     }
1.1010    raeburn  6551:     return %validations; 
                   6552: }
                   6553: 
1.1020    raeburn  6554: sub auto_courserequest_validation {
                   6555:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6556:     my ($homeserver,$response);
                   6557:     if ($dom =~ /^$match_domain$/) {
                   6558:         $homeserver = &domain($dom,'primary');
                   6559:     }
                   6560:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6561:           
1.1020    raeburn  6562:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6563:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6564:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6565:                                     $homeserver));
                   6566:     }
                   6567:     return $response;
                   6568: }
                   6569: 
1.777     albertel 6570: sub auto_validate_class_sec {
1.918     raeburn  6571:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6572:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6573:     my $ownerlist;
                   6574:     if (ref($owners) eq 'ARRAY') {
                   6575:         $ownerlist = join(',',@{$owners});
                   6576:     } else {
                   6577:         $ownerlist = $owners;
                   6578:     }
1.773     raeburn  6579:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6580:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6581:     return $response;
                   6582: }
                   6583: 
1.679     raeburn  6584: # ------------------------------------------------------- Course Group routines
                   6585: 
                   6586: sub get_coursegroups {
1.809     raeburn  6587:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6588:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6589: }
                   6590: 
1.679     raeburn  6591: sub modify_coursegroup {
                   6592:     my ($cdom,$cnum,$groupsettings) = @_;
                   6593:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6594: }
                   6595: 
1.809     raeburn  6596: sub toggle_coursegroup_status {
                   6597:     my ($cdom,$cnum,$group,$action) = @_;
                   6598:     my ($from_namespace,$to_namespace);
                   6599:     if ($action eq 'delete') {
                   6600:         $from_namespace = 'coursegroups';
                   6601:         $to_namespace = 'deleted_groups';
                   6602:     } else {
                   6603:         $from_namespace = 'deleted_groups';
                   6604:         $to_namespace = 'coursegroups';
                   6605:     }
                   6606:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6607:     if (my $tmp = &error(%curr_group)) {
                   6608:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6609:         return ('read error',$tmp);
                   6610:     } else {
                   6611:         my %savedsettings = %curr_group; 
1.809     raeburn  6612:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6613:         my $deloutcome;
                   6614:         if ($result eq 'ok') {
1.809     raeburn  6615:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6616:         } else {
                   6617:             return ('write error',$result);
                   6618:         }
                   6619:         if ($deloutcome eq 'ok') {
                   6620:             return 'ok';
                   6621:         } else {
                   6622:             return ('delete error',$deloutcome);
                   6623:         }
                   6624:     }
                   6625: }
                   6626: 
1.679     raeburn  6627: sub modify_group_roles {
1.957     raeburn  6628:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6629:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6630:     my $role = 'gr/'.&escape($userprivs);
                   6631:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6632:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6633:     if ($result eq 'ok') {
                   6634:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6635:     }
1.679     raeburn  6636:     return $result;
                   6637: }
                   6638: 
                   6639: sub modify_coursegroup_membership {
                   6640:     my ($cdom,$cnum,$membership) = @_;
                   6641:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6642:     return $result;
                   6643: }
                   6644: 
1.682     raeburn  6645: sub get_active_groups {
                   6646:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6647:     my $now = time;
                   6648:     my %groups = ();
                   6649:     foreach my $key (keys(%env)) {
1.811     albertel 6650:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6651:             my ($start,$end) = split(/\./,$env{$key});
                   6652:             if (($end!=0) && ($end<$now)) { next; }
                   6653:             if (($start!=0) && ($start>$now)) { next; }
                   6654:             if ($1 eq $cdom && $2 eq $cnum) {
                   6655:                 $groups{$3} = $env{$key} ;
                   6656:             }
                   6657:         }
                   6658:     }
                   6659:     return %groups;
                   6660: }
                   6661: 
1.683     raeburn  6662: sub get_group_membership {
                   6663:     my ($cdom,$cnum,$group) = @_;
                   6664:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6665: }
                   6666: 
                   6667: sub get_users_groups {
                   6668:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6669:     my @usersgroups;
1.683     raeburn  6670:     my $cachetime=1800;
                   6671: 
                   6672:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6673:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6674:     if (defined($cached)) {
1.734     albertel 6675:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6676:     } else {  
                   6677:         $grouplist = '';
1.816     raeburn  6678:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6679:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6680:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6681:         my $access_end = $env{'course.'.$courseid.
                   6682:                               '.default_enrollment_end_date'};
                   6683:         my $now = time;
                   6684:         foreach my $key (keys(%roleshash)) {
                   6685:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6686:                 my $group = $1;
                   6687:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6688:                     my $start = $2;
                   6689:                     my $end = $1;
                   6690:                     if ($start == -1) { next; } # deleted from group
                   6691:                     if (($start!=0) && ($start>$now)) { next; }
                   6692:                     if (($end!=0) && ($end<$now)) {
                   6693:                         if ($access_end && $access_end < $now) {
                   6694:                             if ($access_end - $end < 86400) {
                   6695:                                 push(@usersgroups,$group);
1.733     raeburn  6696:                             }
                   6697:                         }
1.817     raeburn  6698:                         next;
1.733     raeburn  6699:                     }
1.817     raeburn  6700:                     push(@usersgroups,$group);
1.683     raeburn  6701:                 }
                   6702:             }
                   6703:         }
1.817     raeburn  6704:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6705:         $grouplist = join(':',@usersgroups);
                   6706:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6707:     }
1.733     raeburn  6708:     return @usersgroups;
1.683     raeburn  6709: }
                   6710: 
                   6711: sub devalidate_getgroups_cache {
                   6712:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6713:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6714: 
1.683     raeburn  6715:     my $hashid="$udom:$uname:$courseid";
                   6716:     &devalidate_cache_new('getgroups',$hashid);
                   6717: }
                   6718: 
1.12      www      6719: # ------------------------------------------------------------------ Plain Text
                   6720: 
                   6721: sub plaintext {
1.988     raeburn  6722:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6723:     if ($short =~ m{^cr/}) {
1.758     albertel 6724: 	return (split('/',$short))[-1];
                   6725:     }
1.742     raeburn  6726:     if (!defined($cid)) {
                   6727:         $cid = $env{'request.course.id'};
                   6728:     }
                   6729:     my %rolenames = (
1.1008    raeburn  6730:                       Course    => 'std',
                   6731:                       Community => 'alt1',
1.742     raeburn  6732:                     );
1.1037    raeburn  6733:     if ($cid ne '') {
                   6734:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6735:             unless ($forcedefault) {
                   6736:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6737:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6738:                 return &Apache::lonlocal::mt($roletext);
                   6739:             }
                   6740:         }
                   6741:     }
                   6742:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6743:         (defined($rolenames{$type})) && 
                   6744:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6745:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6746:     } elsif ($cid ne '') {
                   6747:         my $crstype = $env{'course.'.$cid.'.type'};
                   6748:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6749:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6750:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6751:         }
1.742     raeburn  6752:     }
1.1037    raeburn  6753:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6754: }
                   6755: 
                   6756: # ----------------------------------------------------------------- Assign Role
                   6757: 
                   6758: sub assignrole {
1.957     raeburn  6759:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6760:         $context)=@_;
1.21      www      6761:     my $mrole;
                   6762:     if ($role =~ /^cr\//) {
1.393     www      6763:         my $cwosec=$url;
1.811     albertel 6764:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6765: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6766:            my $refused = 1;
                   6767:            if ($context eq 'requestcourses') {
                   6768:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6769:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6770:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6771:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6772:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6773:                            if ($crsenv{'internal.courseowner'} eq
                   6774:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6775:                                $refused = '';
                   6776:                            }
                   6777:                        }
                   6778:                    }
                   6779:                }
                   6780:            }
                   6781:            if ($refused) {
                   6782:                &logthis('Refused custom assignrole: '.
                   6783:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6784:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6785:                return 'refused';
                   6786:            }
1.104     www      6787:         }
1.21      www      6788:         $mrole='cr';
1.678     raeburn  6789:     } elsif ($role =~ /^gr\//) {
                   6790:         my $cwogrp=$url;
1.811     albertel 6791:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6792:         unless (&allowed('mdg',$cwogrp)) {
                   6793:             &logthis('Refused group assignrole: '.
                   6794:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6795:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6796:             return 'refused';
                   6797:         }
                   6798:         $mrole='gr';
1.21      www      6799:     } else {
1.82      www      6800:         my $cwosec=$url;
1.811     albertel 6801:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6802:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6803:             my $refused;
                   6804:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6805:                 if (!(&allowed('c'.$role,$url))) {
                   6806:                     $refused = 1;
                   6807:                 }
                   6808:             } else {
                   6809:                 $refused = 1;
                   6810:             }
1.947     raeburn  6811:             if ($refused) {
1.1045    raeburn  6812:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6813:                 if (!$selfenroll && $context eq 'course') {
                   6814:                     my %crsenv;
                   6815:                     if ($role eq 'cc' || $role eq 'co') {
                   6816:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6817:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6818:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6819:                                 if ($crsenv{'internal.courseowner'} eq 
                   6820:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6821:                                     $refused = '';
                   6822:                                 }
                   6823:                             }
                   6824:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6825:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6826:                                 if ($crsenv{'internal.courseowner'} eq 
                   6827:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6828:                                     $refused = '';
                   6829:                                 }
                   6830:                             }
                   6831:                         }
                   6832:                     }
                   6833:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6834:                     $refused = '';
1.1017    raeburn  6835:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6836:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6837:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6838:                         my $wrongcc;
                   6839:                         if ($cnum =~ /^$match_community$/) {
                   6840:                             $wrongcc = 1 if ($role eq 'cc');
                   6841:                         } else {
                   6842:                             $wrongcc = 1 if ($role eq 'co');
                   6843:                         }
                   6844:                         unless ($wrongcc) {
                   6845:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6846:                             if ($crsenv{'internal.courseowner'} eq 
                   6847:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6848:                                 $refused = '';
                   6849:                             }
1.1017    raeburn  6850:                         }
                   6851:                     }
                   6852:                 }
                   6853:                 if ($refused) {
1.947     raeburn  6854:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6855:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6856: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6857:                     return 'refused';
                   6858:                 }
1.932     raeburn  6859:             }
1.104     www      6860:         }
1.21      www      6861:         $mrole=$role;
                   6862:     }
1.620     albertel 6863:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6864:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6865:     if ($end) { $command.='_'.$end; }
1.21      www      6866:     if ($start) {
                   6867: 	if ($end) { 
1.81      www      6868:            $command.='_'.$start; 
1.21      www      6869:         } else {
1.81      www      6870:            $command.='_0_'.$start;
1.21      www      6871:         }
                   6872:     }
1.739     raeburn  6873:     my $origstart = $start;
                   6874:     my $origend = $end;
1.957     raeburn  6875:     my $delflag;
1.357     www      6876: # actually delete
                   6877:     if ($deleteflag) {
1.373     www      6878: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6879: # modify command to delete the role
1.620     albertel 6880:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6881:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6882: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6883: # set start and finish to negative values for userrolelog
                   6884:            $start=-1;
                   6885:            $end=-1;
1.957     raeburn  6886:            $delflag = 1;
1.357     www      6887:         }
                   6888:     }
                   6889: # send command
1.349     www      6890:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6891: # log new user role if status is ok
1.349     www      6892:     if ($answer eq 'ok') {
1.663     raeburn  6893: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6894: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6895:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6896:         unless ($role =~ /^gr/) {
                   6897:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6898:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6899:         }
1.1053    raeburn  6900:         if ($role eq 'cc') {
                   6901:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6902:         }
1.349     www      6903:     }
                   6904:     return $answer;
1.169     harris41 6905: }
                   6906: 
1.1053    raeburn  6907: sub autoupdate_coowners {
                   6908:     my ($url,$end,$start,$uname,$udom) = @_;
                   6909:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6910:     if (($cdom ne '') && ($cnum ne '')) {
                   6911:         my $now = time;
                   6912:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6913:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6914:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6915:             my $instcode = $coursehash{'internal.coursecode'};
                   6916:             if ($instcode ne '') {
1.1056    raeburn  6917:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6918:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6919:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6920:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6921:                         if ($result eq 'valid') {
                   6922:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6923:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6924:                                     push(@newcoowners,$coowner);
                   6925:                                 }
                   6926:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6927:                                     push(@newcoowners,$uname.':'.$udom);
                   6928:                                 }
                   6929:                                 @newcoowners = sort(@newcoowners);
                   6930:                             } else {
                   6931:                                 push(@newcoowners,$uname.':'.$udom);
                   6932:                             }
                   6933:                         } else {
                   6934:                             if ($coursehash{'internal.co-owners'}) {
                   6935:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6936:                                     unless ($coowner eq $uname.':'.$udom) {
                   6937:                                         push(@newcoowners,$coowner);
                   6938:                                     }
                   6939:                                 }
                   6940:                                 unless (@newcoowners > 0) {
                   6941:                                     $delcoowners = 1;
                   6942:                                     $coowners = '';
                   6943:                                 }
                   6944:                             }
                   6945:                         }
                   6946:                         if (@newcoowners || $delcoowners) {
                   6947:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6948:                                             $delcoowners,@newcoowners);
                   6949:                         }
                   6950:                     }
                   6951:                 }
                   6952:             }
                   6953:         }
                   6954:     }
                   6955: }
                   6956: 
                   6957: sub store_coowners {
                   6958:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6959:     my $cid = $cdom.'_'.$cnum;
                   6960:     my ($coowners,$delresult,$putresult);
                   6961:     if (@newcoowners) {
                   6962:         $coowners = join(',',@newcoowners);
                   6963:         my %coownershash = (
                   6964:                             'internal.co-owners' => $coowners,
                   6965:                            );
                   6966:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6967:         if ($putresult eq 'ok') {
                   6968:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6969:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6970:             }
                   6971:         }
                   6972:     }
                   6973:     if ($delcoowners) {
                   6974:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6975:         if ($delresult eq 'ok') {
                   6976:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6977:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6978:             }
                   6979:         }
                   6980:     }
                   6981:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6982:         my %crsinfo =
                   6983:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6984:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6985:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6986:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6987:         }
                   6988:     }
                   6989: }
                   6990: 
1.169     harris41 6991: # -------------------------------------------------- Modify user authentication
1.197     www      6992: # Overrides without validation
                   6993: 
1.169     harris41 6994: sub modifyuserauth {
                   6995:     my ($udom,$uname,$umode,$upass)=@_;
                   6996:     my $uhome=&homeserver($uname,$udom);
1.197     www      6997:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6998:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6999:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7000:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7001:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7002: 		     &escape($upass),$uhome);
1.620     albertel 7003:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7004:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7005:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7006:     &log($udom,,$uname,$uhome,
1.620     albertel 7007:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7008:                                      $env{'user.name'}.', '.$umode.
1.197     www      7009:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7010:     unless ($reply eq 'ok') {
1.197     www      7011:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7012: 	return 'error: '.$reply;
                   7013:     }   
1.170     harris41 7014:     return 'ok';
1.80      www      7015: }
                   7016: 
1.81      www      7017: # --------------------------------------------------------------- Modify a user
1.80      www      7018: 
1.81      www      7019: sub modifyuser {
1.206     matthew  7020:     my ($udom,    $uname, $uid,
                   7021:         $umode,   $upass, $first,
                   7022:         $middle,  $last,  $gene,
1.1058    raeburn  7023:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7024:     $udom= &LONCAPA::clean_domain($udom);
                   7025:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7026:     my $showcandelete = 'none';
                   7027:     if (ref($candelete) eq 'ARRAY') {
                   7028:         if (@{$candelete} > 0) {
                   7029:             $showcandelete = join(', ',@{$candelete});
                   7030:         }
                   7031:     }
1.81      www      7032:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7033:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7034: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7035:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7036:                                      ' desiredhome not specified'). 
1.620     albertel 7037:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7038:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7039:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7040:     my $newuser;
                   7041:     if ($uhome eq 'no_host') {
                   7042:         $newuser = 1;
                   7043:     }
1.80      www      7044: # ----------------------------------------------------------------- Create User
1.406     albertel 7045:     if (($uhome eq 'no_host') && 
                   7046: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7047:         my $unhome='';
1.844     albertel 7048:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7049:             $unhome = $desiredhome;
1.620     albertel 7050: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7051: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7052:         } else { # load balancing routine for determining $unhome
1.81      www      7053:             my $loadm=10000000;
1.841     albertel 7054: 	    my %servers = &get_servers($udom,'library');
                   7055: 	    foreach my $tryserver (keys(%servers)) {
                   7056: 		my $answer=reply('load',$tryserver);
                   7057: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7058: 		    $loadm=$answer;
                   7059: 		    $unhome=$tryserver;
                   7060: 		}
1.80      www      7061: 	    }
                   7062:         }
                   7063:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7064: 	    return 'error: unable to find a home server for '.$uname.
                   7065:                    ' in domain '.$udom;
1.80      www      7066:         }
                   7067:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7068:                          &escape($upass),$unhome);
                   7069: 	unless ($reply eq 'ok') {
                   7070:             return 'error: '.$reply;
                   7071:         }   
1.230     stredwic 7072:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7073:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7074: 	    return 'error: unable verify users home machine.';
1.80      www      7075:         }
1.209     matthew  7076:     }   # End of creation of new user
1.80      www      7077: # ---------------------------------------------------------------------- Add ID
                   7078:     if ($uid) {
                   7079:        $uid=~tr/A-Z/a-z/;
                   7080:        my %uidhash=&idrget($udom,$uname);
1.196     www      7081:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7082:          && (!$forceid)) {
1.80      www      7083: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7084: 	      return 'error: user id "'.$uid.'" does not match '.
                   7085:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7086:           }
                   7087:        } else {
                   7088: 	  &idput($udom,($uname => $uid));
                   7089:        }
                   7090:     }
                   7091: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7092:     my @tmp=&get('environment',
1.899     raeburn  7093: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7094:                     'permanentemail','inststatus'],
1.134     albertel 7095: 		   $udom,$uname);
1.1075    raeburn  7096:     my (%names,%oldnames);
1.313     matthew  7097:     if ($tmp[0] =~ m/^error:.*/) { 
                   7098:         %names=(); 
                   7099:     } else {
                   7100:         %names = @tmp;
1.1075    raeburn  7101:         %oldnames = %names;
1.313     matthew  7102:     }
1.388     www      7103: #
1.1058    raeburn  7104: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7105: # of users did not contain them), do not overwrite existing values
                   7106: # unless field is in $candelete array ref.  
                   7107: #
                   7108: 
                   7109:     my @fields = ('firstname','middlename','lastname','generation',
                   7110:                   'permanentemail','id');
                   7111:     my %newvalues;
                   7112:     if (ref($candelete) eq 'ARRAY') {
                   7113:         foreach my $field (@fields) {
                   7114:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7115:                 if ($field eq 'firstname') {
                   7116:                     $names{$field} = $first;
                   7117:                 } elsif ($field eq 'middlename') {
                   7118:                     $names{$field} = $middle;
                   7119:                 } elsif ($field eq 'lastname') {
                   7120:                     $names{$field} = $last;
                   7121:                 } elsif ($field eq 'generation') { 
                   7122:                     $names{$field} = $gene;
                   7123:                 } elsif ($field eq 'permanentemail') {
                   7124:                     $names{$field} = $email;
                   7125:                 } elsif ($field eq 'id') {
                   7126:                     $names{$field}  = $uid;
                   7127:                 }
                   7128:             }
                   7129:         }
                   7130:     }
1.388     www      7131:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7132:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7133:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7134:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7135:     if ($email) {
                   7136:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7137:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7138:     }
1.899     raeburn  7139:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7140:     if (defined($inststatus)) {
                   7141:         $names{'inststatus'} = '';
                   7142:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7143:         if (ref($usertypes) eq 'HASH') {
                   7144:             my @okstatuses; 
                   7145:             foreach my $item (split(/:/,$inststatus)) {
                   7146:                 if (defined($usertypes->{$item})) {
                   7147:                     push(@okstatuses,$item);  
                   7148:                 }
                   7149:             }
                   7150:             if (@okstatuses) {
                   7151:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7152:             }
                   7153:         }
                   7154:     }
1.1075    raeburn  7155:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7156:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7157:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7158:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7159:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7160:     } else {
                   7161:         $logmsg .= ' during self creation';
                   7162:     }
1.1075    raeburn  7163:     my $changed;
                   7164:     if ($newuser) {
                   7165:         $changed = 1;
                   7166:     } else {
                   7167:         foreach my $field (@fields) {
                   7168:             if ($names{$field} ne $oldnames{$field}) {
                   7169:                 $changed = 1;
                   7170:                 last;
                   7171:             }
                   7172:         }
                   7173:     }
                   7174:     unless ($changed) {
                   7175:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7176:         &logthis($logmsg);
                   7177:         return 'ok';
                   7178:     }
                   7179:     my $reply = &put('environment', \%names, $udom,$uname);
                   7180:     if ($reply ne 'ok') { 
                   7181:         return 'error: '.$reply;
                   7182:     }
1.1087    raeburn  7183:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7184:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7185:     }
1.1075    raeburn  7186:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7187:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7188:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7189:     &logthis($logmsg);
1.134     albertel 7190:     return 'ok';
1.80      www      7191: }
                   7192: 
1.81      www      7193: # -------------------------------------------------------------- Modify student
1.80      www      7194: 
1.81      www      7195: sub modifystudent {
                   7196:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7197:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7198:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7199:     if (!$cid) {
1.620     albertel 7200: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7201: 	    return 'not_in_class';
                   7202: 	}
1.80      www      7203:     }
                   7204: # --------------------------------------------------------------- Make the user
1.81      www      7205:     my $reply=&modifyuser
1.209     matthew  7206: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7207:          $desiredhome,$email,$inststatus);
1.80      www      7208:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7209:     # This will cause &modify_student_enrollment to get the uid from the
                   7210:     # students environment
                   7211:     $uid = undef if (!$forceid);
1.455     albertel 7212:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7213: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7214:     return $reply;
                   7215: }
                   7216: 
                   7217: sub modify_student_enrollment {
1.957     raeburn  7218:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7219:     my ($cdom,$cnum,$chome);
                   7220:     if (!$cid) {
1.620     albertel 7221: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7222: 	    return 'not_in_class';
                   7223: 	}
1.620     albertel 7224: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7225: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7226:     } else {
                   7227: 	($cdom,$cnum)=split(/_/,$cid);
                   7228:     }
1.620     albertel 7229:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7230:     if (!$chome) {
1.457     raeburn  7231: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7232:     }
1.455     albertel 7233:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7234:     # Make sure the user exists
1.81      www      7235:     my $uhome=&homeserver($uname,$udom);
                   7236:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7237: 	return 'error: no such user';
                   7238:     }
1.297     matthew  7239:     # Get student data if we were not given enough information
                   7240:     if (!defined($first)  || $first  eq '' || 
                   7241:         !defined($last)   || $last   eq '' || 
                   7242:         !defined($uid)    || $uid    eq '' || 
                   7243:         !defined($middle) || $middle eq '' || 
                   7244:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7245:         # They did not supply us with enough data to enroll the student, so
                   7246:         # we need to pick up more information.
1.297     matthew  7247:         my %tmp = &get('environment',
1.294     matthew  7248:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7249:                        ,$udom,$uname);
                   7250: 
1.800     albertel 7251:         #foreach my $key (keys(%tmp)) {
                   7252:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7253:         #}
1.294     matthew  7254:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7255:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7256:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7257:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7258:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7259:     }
1.556     albertel 7260:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7261:     my $reply=cput('classlist',
                   7262: 		   {"$uname:$udom" => 
1.515     raeburn  7263: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7264: 		   $cdom,$cnum);
1.81      www      7265:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7266: 	return 'error: '.$reply;
1.652     albertel 7267:     } else {
                   7268: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7269:     }
1.297     matthew  7270:     # Add student role to user
1.83      www      7271:     my $uurl='/'.$cid;
1.81      www      7272:     $uurl=~s/\_/\//g;
                   7273:     if ($usec) {
                   7274: 	$uurl.='/'.$usec;
                   7275:     }
1.957     raeburn  7276:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7277: }
                   7278: 
1.556     albertel 7279: sub format_name {
                   7280:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7281:     my $name;
                   7282:     if ($first ne 'lastname') {
                   7283: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7284:     } else {
                   7285: 	if ($lastname=~/\S/) {
                   7286: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7287: 	    $name=~s/\s+,/,/;
                   7288: 	} else {
                   7289: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7290: 	}
                   7291:     }
                   7292:     $name=~s/^\s+//;
                   7293:     $name=~s/\s+$//;
                   7294:     $name=~s/\s+/ /g;
                   7295:     return $name;
                   7296: }
                   7297: 
1.84      www      7298: # ------------------------------------------------- Write to course preferences
                   7299: 
                   7300: sub writecoursepref {
                   7301:     my ($courseid,%prefs)=@_;
                   7302:     $courseid=~s/^\///;
                   7303:     $courseid=~s/\_/\//g;
                   7304:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7305:     my $chome=homeserver($cnum,$cdomain);
                   7306:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7307: 	return 'error: no such course';
                   7308:     }
                   7309:     my $cstring='';
1.800     albertel 7310:     foreach my $pref (keys(%prefs)) {
                   7311: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7312:     }
1.84      www      7313:     $cstring=~s/\&$//;
                   7314:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7315: }
                   7316: 
                   7317: # ---------------------------------------------------------- Make/modify course
                   7318: 
                   7319: sub createcourse {
1.741     raeburn  7320:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7321:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7322:     $url=&declutter($url);
                   7323:     my $cid='';
1.1028    raeburn  7324:     if ($context eq 'requestcourses') {
                   7325:         my $can_create = 0;
                   7326:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7327:         if ($udom eq $ownerdom) {
                   7328:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7329:                                   $context)) {
                   7330:                 $can_create = 1;
                   7331:             }
                   7332:         } else {
                   7333:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7334:                                            $category);
                   7335:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7336:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7337:                 if (@curr > 0) {
                   7338:                     my @options = qw(approval validate autolimit);
                   7339:                     my $optregex = join('|',@options);
                   7340:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7341:                         $can_create = 1;
                   7342:                     }
                   7343:                 }
                   7344:             }
                   7345:         }
                   7346:         if ($can_create) {
                   7347:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7348:                 unless (&allowed('ccc',$udom)) {
                   7349:                     return 'refused'; 
                   7350:                 }
1.1017    raeburn  7351:             }
                   7352:         } else {
                   7353:             return 'refused';
                   7354:         }
1.1028    raeburn  7355:     } elsif (!&allowed('ccc',$udom)) {
                   7356:         return 'refused';
1.84      www      7357:     }
1.1011    raeburn  7358: # --------------------------------------------------------------- Get Unique ID
                   7359:     my $uname;
                   7360:     if ($cnum =~ /^$match_courseid$/) {
                   7361:         my $chome=&homeserver($cnum,$udom,'true');
                   7362:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7363:             $uname = $cnum;
                   7364:         } else {
1.1038    raeburn  7365:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7366:         }
                   7367:     } else {
1.1038    raeburn  7368:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7369:     }
                   7370:     return $uname if ($uname =~ /^error/);
                   7371: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7372:     if (!defined($course_server)) {
                   7373:         if (defined(&domain($udom,'primary'))) {
                   7374:             $course_server = &domain($udom,'primary');
                   7375:         } else {
                   7376:             $course_server = $env{'user.home'}; 
                   7377:         }
                   7378:     }
                   7379:     my %host_servers =
                   7380:         &Apache::lonnet::get_servers($udom,'library');
                   7381:     unless ($host_servers{$course_server}) {
                   7382:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7383:     }
1.84      www      7384: # ------------------------------------------------------------- Make the course
                   7385:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7386:                       $course_server);
1.84      www      7387:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7388:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7389:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7390: 	return 'error: no such course';
                   7391:     }
1.271     www      7392: # ----------------------------------------------------------------- Course made
1.516     raeburn  7393: # log existence
1.1029    raeburn  7394:     my $now = time;
1.918     raeburn  7395:     my $newcourse = {
                   7396:                     $udom.'_'.$uname => {
1.921     raeburn  7397:                                      description => $description,
                   7398:                                      inst_code   => $inst_code,
                   7399:                                      owner       => $course_owner,
                   7400:                                      type        => $crstype,
1.1029    raeburn  7401:                                      creator     => $env{'user.name'}.':'.
                   7402:                                                     $env{'user.domain'},
                   7403:                                      created     => $now,
                   7404:                                      context     => $context,
1.918     raeburn  7405:                                                 },
                   7406:                     };
1.921     raeburn  7407:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7408: # set toplevel url
1.271     www      7409:     my $topurl=$url;
                   7410:     unless ($nonstandard) {
                   7411: # ------------------------------------------ For standard courses, make top url
                   7412:         my $mapurl=&clutter($url);
1.278     www      7413:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7414:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7415: <map>
                   7416: <resource id="1" type="start"></resource>
                   7417: <resource id="2" src="$mapurl"></resource>
                   7418: <resource id="3" type="finish"></resource>
                   7419: <link index="1" from="1" to="2"></link>
                   7420: <link index="2" from="2" to="3"></link>
                   7421: </map>
                   7422: ENDINITMAP
                   7423:         $topurl=&declutter(
1.638     albertel 7424:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7425:                           );
                   7426:     }
                   7427: # ----------------------------------------------------------- Write preferences
1.84      www      7428:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7429:                      ('description'              => $description,
                   7430:                       'url'                      => $topurl,
                   7431:                       'internal.creator'         => $env{'user.name'}.':'.
                   7432:                                                     $env{'user.domain'},
                   7433:                       'internal.created'         => $now,
                   7434:                       'internal.creationcontext' => $context)
                   7435:                     );
1.84      www      7436:     return '/'.$udom.'/'.$uname;
                   7437: }
                   7438: 
1.1011    raeburn  7439: # ------------------------------------------------------------------- Create ID
                   7440: sub generate_coursenum {
1.1038    raeburn  7441:     my ($udom,$crstype) = @_;
1.1011    raeburn  7442:     my $domdesc = &domain($udom);
                   7443:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7444:     my $first;
                   7445:     if ($crstype eq 'Community') {
                   7446:         $first = '0';
                   7447:     } else {
                   7448:         $first = int(1+rand(9)); 
                   7449:     } 
                   7450:     my $uname=$first.
1.1011    raeburn  7451:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7452:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7453:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7454: # ----------------------------------------------- Make sure that does not exist
                   7455:     my $uhome=&homeserver($uname,$udom,'true');
                   7456:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7457:         if ($crstype eq 'Community') {
                   7458:             $first = '0';
                   7459:         } else {
                   7460:             $first = int(1+rand(9));
                   7461:         }
                   7462:         $uname=$first.
1.1011    raeburn  7463:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7464:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7465:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7466:         $uhome=&homeserver($uname,$udom,'true');
                   7467:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7468:             return 'error: unable to generate unique course-ID';
                   7469:         }
                   7470:     }
                   7471:     return $uname;
                   7472: }
                   7473: 
1.813     albertel 7474: sub is_course {
                   7475:     my ($cdom,$cnum) = @_;
                   7476:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7477: 				undef,'.');
1.813     albertel 7478:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7479:         return 1;
                   7480:     }
                   7481:     return 0;
                   7482: }
                   7483: 
1.1015    raeburn  7484: sub store_userdata {
                   7485:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7486:     my $result;
1.1016    raeburn  7487:     if ($datakey ne '') {
1.1013    raeburn  7488:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7489:             if ($udom eq '' || $uname eq '') {
                   7490:                 $udom = $env{'user.domain'};
                   7491:                 $uname = $env{'user.name'};
                   7492:             }
                   7493:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7494:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7495:                 $result = 'error: no_host';
                   7496:             } else {
                   7497:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7498:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7499: 
                   7500:                 my $namevalue='';
                   7501:                 foreach my $key (keys(%{$storehash})) {
                   7502:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7503:                 }
                   7504:                 $namevalue=~s/\&$//;
1.1105    raeburn  7505:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7506:                                   $namevalue,$uhome);
1.1013    raeburn  7507:             }
                   7508:         } else {
                   7509:             $result = 'error: data to store was not a hash reference'; 
                   7510:         }
                   7511:     } else {
                   7512:         $result= 'error: invalid requestkey'; 
                   7513:     }
                   7514:     return $result;
                   7515: }
                   7516: 
1.21      www      7517: # ---------------------------------------------------------- Assign Custom Role
                   7518: 
                   7519: sub assigncustomrole {
1.957     raeburn  7520:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7521:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7522:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7523: }
                   7524: 
                   7525: # ----------------------------------------------------------------- Revoke Role
                   7526: 
                   7527: sub revokerole {
1.957     raeburn  7528:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7529:     my $now=time;
1.965     raeburn  7530:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7531: }
                   7532: 
                   7533: # ---------------------------------------------------------- Revoke Custom Role
                   7534: 
                   7535: sub revokecustomrole {
1.957     raeburn  7536:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7537:     my $now=time;
1.357     www      7538:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7539:            $deleteflag,$selfenroll,$context);
1.17      www      7540: }
                   7541: 
1.533     banghart 7542: # ------------------------------------------------------------ Disk usage
1.535     albertel 7543: sub diskusage {
1.955     raeburn  7544:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7545:     $directorypath =~ s/\/$//;
                   7546:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7547:                        .&escape($getpropath).':'.&escape($uname).':'
                   7548:                        .&escape($udom),homeserver($uname,$udom));
                   7549:     if ($listing eq 'unknown_cmd') {
                   7550:         if ($getpropath) {
                   7551:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7552:         }
                   7553:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7554:     }
1.514     albertel 7555:     return $listing;
1.512     banghart 7556: }
                   7557: 
1.566     banghart 7558: sub is_locked {
1.1096    raeburn  7559:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7560:     my @check;
                   7561:     my $is_locked;
1.1093    raeburn  7562:     push (@check,$file_name);
1.613     albertel 7563:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7564: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7565:     my ($tmp)=keys(%locked);
                   7566:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7567:     
1.566     banghart 7568:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7569:         $is_locked = 'false';
                   7570:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7571:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7572:                $is_locked = 'true';
1.1096    raeburn  7573:                if (ref($which) eq 'ARRAY') {
                   7574:                    push(@{$which},$entry);
                   7575:                } else {
                   7576:                    last;
                   7577:                }
1.745     raeburn  7578:            }
                   7579:        }
1.566     banghart 7580:     } else {
                   7581:         $is_locked = 'false';
                   7582:     }
1.1093    raeburn  7583:     return $is_locked;
1.566     banghart 7584: }
                   7585: 
1.759     albertel 7586: sub declutter_portfile {
                   7587:     my ($file) = @_;
1.833     albertel 7588:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7589:     return $file;
                   7590: }
                   7591: 
1.559     banghart 7592: # ------------------------------------------------------------- Mark as Read Only
                   7593: 
                   7594: sub mark_as_readonly {
                   7595:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7596:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7597:     my ($tmp)=keys(%current_permissions);
                   7598:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7599:     foreach my $file (@{$files}) {
1.759     albertel 7600: 	$file = &declutter_portfile($file);
1.561     banghart 7601:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7602:     }
1.613     albertel 7603:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7604:     return;
                   7605: }
                   7606: 
1.572     banghart 7607: # ------------------------------------------------------------Save Selected Files
                   7608: 
                   7609: sub save_selected_files {
                   7610:     my ($user, $path, @files) = @_;
                   7611:     my $filename = $user."savedfiles";
1.573     banghart 7612:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7613:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7614:     foreach my $file (@files) {
1.620     albertel 7615:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7616:     }
                   7617:     foreach my $file (@other_files) {
1.574     banghart 7618:         print (OUT $file."\n");
1.572     banghart 7619:     }
1.574     banghart 7620:     close (OUT);
1.572     banghart 7621:     return 'ok';
                   7622: }
                   7623: 
1.574     banghart 7624: sub clear_selected_files {
                   7625:     my ($user) = @_;
                   7626:     my $filename = $user."savedfiles";
1.1117    foxr     7627:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7628:     print (OUT undef);
                   7629:     close (OUT);
                   7630:     return ("ok");    
                   7631: }
                   7632: 
1.572     banghart 7633: sub files_in_path {
                   7634:     my ($user, $path) = @_;
                   7635:     my $filename = $user."savedfiles";
                   7636:     my %return_files;
1.1117    foxr     7637:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7638:     while (my $line_in = <IN>) {
1.574     banghart 7639:         chomp ($line_in);
                   7640:         my @paths_and_file = split (m!/!, $line_in);
                   7641:         my $file_part = pop (@paths_and_file);
                   7642:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7643:         $path_part.='/';
                   7644:         my $path_and_file = $path_part.$file_part;
                   7645:         if ($path_part eq $path) {
                   7646:             $return_files{$file_part}= 'selected';
                   7647:         }
                   7648:     }
1.574     banghart 7649:     close (IN);
                   7650:     return (\%return_files);
1.572     banghart 7651: }
                   7652: 
                   7653: # called in portfolio select mode, to show files selected NOT in current directory
                   7654: sub files_not_in_path {
                   7655:     my ($user, $path) = @_;
                   7656:     my $filename = $user."savedfiles";
                   7657:     my @return_files;
                   7658:     my $path_part;
1.1117    foxr     7659:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7660:     while (my $line = <IN>) {
1.572     banghart 7661:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7662:         my @paths_and_file = split(m|/|, $line);
                   7663:         my $file_part = pop(@paths_and_file);
                   7664:         chomp($file_part);
                   7665:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7666:         $path_part .= '/';
                   7667:         my $path_and_file = $path_part.$file_part;
                   7668:         if ($path_part ne $path) {
1.800     albertel 7669:             push(@return_files, ($path_and_file));
1.572     banghart 7670:         }
                   7671:     }
1.800     albertel 7672:     close(OUT);
1.574     banghart 7673:     return (@return_files);
1.572     banghart 7674: }
                   7675: 
1.745     raeburn  7676: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7677: 
1.745     raeburn  7678: sub get_portfile_permissions {
                   7679:     my ($domain,$user) = @_;
1.613     albertel 7680:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7681:     my ($tmp)=keys(%current_permissions);
                   7682:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7683:     return \%current_permissions;
                   7684: }
                   7685: 
                   7686: #---------------------------------------------Get portfolio file access controls
                   7687: 
1.749     raeburn  7688: sub get_access_controls {
1.745     raeburn  7689:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7690:     my %access;
                   7691:     my $real_file = $file;
                   7692:     $file =~ s/\.meta$//;
1.745     raeburn  7693:     if (defined($file)) {
1.749     raeburn  7694:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7695:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7696:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7697:             }
                   7698:         }
1.745     raeburn  7699:     } else {
1.749     raeburn  7700:         foreach my $key (keys(%{$current_permissions})) {
                   7701:             if ($key =~ /\0accesscontrol$/) {
                   7702:                 if (defined($group)) {
                   7703:                     if ($key !~ m-^\Q$group\E/-) {
                   7704:                         next;
                   7705:                     }
                   7706:                 }
                   7707:                 my ($fullpath) = split(/\0/,$key);
                   7708:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7709:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7710:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7711:                     }
                   7712:                 }
                   7713:             }
                   7714:         }
                   7715:     }
                   7716:     return %access;
                   7717: }
                   7718: 
                   7719: sub modify_access_controls {
                   7720:     my ($file_name,$changes,$domain,$user)=@_;
                   7721:     my ($outcome,$deloutcome);
                   7722:     my %store_permissions;
                   7723:     my %new_values;
                   7724:     my %new_control;
                   7725:     my %translation;
                   7726:     my @deletions = ();
                   7727:     my $now = time;
                   7728:     if (exists($$changes{'activate'})) {
                   7729:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7730:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7731:             my $numnew = scalar(@newitems);
                   7732:             for (my $i=0; $i<$numnew; $i++) {
                   7733:                 my $newkey = $newitems[$i];
                   7734:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7735:                 if ($newkey =~ /^\d+:/) { 
                   7736:                     $newkey =~ s/^(\d+)/$newid/;
                   7737:                     $translation{$1} = $newid;
                   7738:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7739:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7740:                     $translation{$1} = $newid;
                   7741:                 }
1.749     raeburn  7742:                 $new_values{$file_name."\0".$newkey} = 
                   7743:                                           $$changes{'activate'}{$newitems[$i]};
                   7744:                 $new_control{$newkey} = $now;
                   7745:             }
                   7746:         }
                   7747:     }
                   7748:     my %todelete;
                   7749:     my %changed_items;
                   7750:     foreach my $action ('delete','update') {
                   7751:         if (exists($$changes{$action})) {
                   7752:             if (ref($$changes{$action}) eq 'HASH') {
                   7753:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7754:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7755:                     if ($action eq 'delete') { 
                   7756:                         $todelete{$itemnum} = 1;
                   7757:                     } else {
                   7758:                         $changed_items{$itemnum} = $key;
                   7759:                     }
                   7760:                 }
1.745     raeburn  7761:             }
                   7762:         }
1.749     raeburn  7763:     }
                   7764:     # get lock on access controls for file.
                   7765:     my $lockhash = {
                   7766:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7767:                                                        ':'.$env{'user.domain'},
                   7768:                    }; 
                   7769:     my $tries = 0;
                   7770:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7771:    
                   7772:     while (($gotlock ne 'ok') && $tries <3) {
                   7773:         $tries ++;
                   7774:         sleep 1;
                   7775:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7776:     }
                   7777:     if ($gotlock eq 'ok') {
                   7778:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7779:         my ($tmp)=keys(%curr_permissions);
                   7780:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7781:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7782:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7783:             if (ref($curr_controls) eq 'HASH') {
                   7784:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7785:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7786:                     if (defined($todelete{$itemnum})) {
                   7787:                         push(@deletions,$file_name."\0".$control_item);
                   7788:                     } else {
                   7789:                         if (defined($changed_items{$itemnum})) {
                   7790:                             $new_control{$changed_items{$itemnum}} = $now;
                   7791:                             push(@deletions,$file_name."\0".$control_item);
                   7792:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7793:                         } else {
                   7794:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7795:                         }
                   7796:                     }
1.745     raeburn  7797:                 }
                   7798:             }
                   7799:         }
1.970     raeburn  7800:         my ($group);
                   7801:         if (&is_course($domain,$user)) {
                   7802:             ($group,my $file) = split(/\//,$file_name,2);
                   7803:         }
1.749     raeburn  7804:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7805:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7806:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7807:         #  remove lock
                   7808:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7809:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7810:         my $sqlresult =
1.970     raeburn  7811:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7812:                                     $group);
1.749     raeburn  7813:     } else {
                   7814:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7815:     }
1.749     raeburn  7816:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7817: }
                   7818: 
1.827     raeburn  7819: sub make_public_indefinitely {
                   7820:     my ($requrl) = @_;
                   7821:     my $now = time;
                   7822:     my $action = 'activate';
                   7823:     my $aclnum = 0;
                   7824:     if (&is_portfolio_url($requrl)) {
                   7825:         my (undef,$udom,$unum,$file_name,$group) =
                   7826:             &parse_portfolio_url($requrl);
                   7827:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7828:         my %access_controls = &get_access_controls($current_perms,
                   7829:                                                    $group,$file_name);
                   7830:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7831:             my ($num,$scope,$end,$start) = 
                   7832:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7833:             if ($scope eq 'public') {
                   7834:                 if ($start <= $now && $end == 0) {
                   7835:                     $action = 'none';
                   7836:                 } else {
                   7837:                     $action = 'update';
                   7838:                     $aclnum = $num;
                   7839:                 }
                   7840:                 last;
                   7841:             }
                   7842:         }
                   7843:         if ($action eq 'none') {
                   7844:              return 'ok';
                   7845:         } else {
                   7846:             my %changes;
                   7847:             my $newend = 0;
                   7848:             my $newstart = $now;
                   7849:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7850:             $changes{$action}{$newkey} = {
                   7851:                 type => 'public',
                   7852:                 time => {
                   7853:                     start => $newstart,
                   7854:                     end   => $newend,
                   7855:                 },
                   7856:             };
                   7857:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7858:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7859:             return $outcome;
                   7860:         }
                   7861:     } else {
                   7862:         return 'invalid';
                   7863:     }
                   7864: }
                   7865: 
1.745     raeburn  7866: #------------------------------------------------------Get Marked as Read Only
                   7867: 
                   7868: sub get_marked_as_readonly {
                   7869:     my ($domain,$user,$what,$group) = @_;
                   7870:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7871:     my @readonly_files;
1.629     banghart 7872:     my $cmp1=$what;
                   7873:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7874:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7875:         if (defined($group)) {
                   7876:             if ($file_name !~ m-^\Q$group\E/-) {
                   7877:                 next;
                   7878:             }
                   7879:         }
1.561     banghart 7880:         if (ref($value) eq "ARRAY"){
                   7881:             foreach my $stored_what (@{$value}) {
1.629     banghart 7882:                 my $cmp2=$stored_what;
1.759     albertel 7883:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7884:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7885:                 }
1.629     banghart 7886:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7887:                     push(@readonly_files, $file_name);
1.745     raeburn  7888:                     last;
1.563     banghart 7889:                 } elsif (!defined($what)) {
                   7890:                     push(@readonly_files, $file_name);
1.745     raeburn  7891:                     last;
1.561     banghart 7892:                 }
                   7893:             }
1.745     raeburn  7894:         }
1.561     banghart 7895:     }
                   7896:     return @readonly_files;
                   7897: }
1.577     banghart 7898: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7899: 
1.577     banghart 7900: sub get_marked_as_readonly_hash {
1.745     raeburn  7901:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7902:     my %readonly_files;
1.745     raeburn  7903:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7904:         if (defined($group)) {
                   7905:             if ($file_name !~ m-^\Q$group\E/-) {
                   7906:                 next;
                   7907:             }
                   7908:         }
1.577     banghart 7909:         if (ref($value) eq "ARRAY"){
                   7910:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7911:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7912:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7913:                         if ($lock_descriptor eq 'graded') {
                   7914:                             $readonly_files{$file_name} = 'graded';
                   7915:                         } elsif ($lock_descriptor eq 'handback') {
                   7916:                             $readonly_files{$file_name} = 'handback';
                   7917:                         } else {
                   7918:                             if (!exists($readonly_files{$file_name})) {
                   7919:                                 $readonly_files{$file_name} = 'locked';
                   7920:                             }
                   7921:                         }
1.745     raeburn  7922:                     }
1.750     banghart 7923:                 } 
1.577     banghart 7924:             }
                   7925:         } 
                   7926:     }
                   7927:     return %readonly_files;
                   7928: }
1.559     banghart 7929: # ------------------------------------------------------------ Unmark as Read Only
                   7930: 
                   7931: sub unmark_as_readonly {
1.629     banghart 7932:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7933:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7934:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7935:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7936:     my $symb_crs = $what;
                   7937:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7938:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7939:     my ($tmp)=keys(%current_permissions);
                   7940:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7941:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7942:     foreach my $file (@readonly_files) {
1.759     albertel 7943: 	my $clean_file = &declutter_portfile($file);
                   7944: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7945: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7946:         my @new_locks;
                   7947:         my @del_keys;
                   7948:         if (ref($current_locks) eq "ARRAY"){
                   7949:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7950:                 my $compare=$locker;
1.749     raeburn  7951:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7952:                     $compare=join('',@{$locker});
1.746     raeburn  7953:                     if ($compare ne $symb_crs) {
                   7954:                         push(@new_locks, $locker);
                   7955:                     }
1.563     banghart 7956:                 }
                   7957:             }
1.650     albertel 7958:             if (scalar(@new_locks) > 0) {
1.563     banghart 7959:                 $current_permissions{$file} = \@new_locks;
                   7960:             } else {
                   7961:                 push(@del_keys, $file);
1.613     albertel 7962:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7963:                 delete($current_permissions{$file});
1.563     banghart 7964:             }
                   7965:         }
1.561     banghart 7966:     }
1.613     albertel 7967:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7968:     return;
                   7969: }
1.512     banghart 7970: 
1.17      www      7971: # ------------------------------------------------------------ Directory lister
                   7972: 
                   7973: sub dirlist {
1.955     raeburn  7974:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7975:     $uri=~s/^\///;
                   7976:     $uri=~s/\/$//;
1.253     stredwic 7977:     my ($udom, $uname);
1.955     raeburn  7978:     if ($getuserdir) {
1.253     stredwic 7979:         $udom = $userdomain;
                   7980:         $uname = $username;
1.955     raeburn  7981:     } else {
                   7982:         (undef,$udom,$uname)=split(/\//,$uri);
                   7983:         if(defined($userdomain)) {
                   7984:             $udom = $userdomain;
                   7985:         }
                   7986:         if(defined($username)) {
                   7987:             $uname = $username;
                   7988:         }
1.253     stredwic 7989:     }
1.955     raeburn  7990:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7991: 
1.955     raeburn  7992:     $dirRoot = $perlvar{'lonDocRoot'};
                   7993:     if (defined($getpropath)) {
                   7994:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7995:         $dirRoot =~ s/\/$//;
1.955     raeburn  7996:     } elsif (defined($getuserdir)) {
                   7997:         my $subdir=$uname.'__';
                   7998:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7999:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8000:                    ."/$udom/$subdir/$uname";
                   8001:     } elsif (defined($alternateRoot)) {
                   8002:         $dirRoot = $alternateRoot;
1.751     banghart 8003:     }
1.253     stredwic 8004: 
                   8005:     if($udom) {
                   8006:         if($uname) {
1.955     raeburn  8007:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8008:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  8009:                               .':'.&escape($uname).':'.&escape($udom),
                   8010:                               &homeserver($uname,$udom));
                   8011:             if ($listing eq 'unknown_cmd') {
                   8012:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   8013:                                   &homeserver($uname,$udom));
                   8014:             } else {
                   8015:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8016:             }
1.605     matthew  8017:             if ($listing eq 'unknown_cmd') {
1.800     albertel 8018:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   8019: 				  &homeserver($uname,$udom));
1.605     matthew  8020:                 @listing_results = split(/:/,$listing);
                   8021:             } else {
                   8022:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8023:             }
                   8024:             return @listing_results;
1.955     raeburn  8025:         } elsif(!$alternateRoot) {
1.800     albertel 8026:             my %allusers;
1.841     albertel 8027: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8028:  	    foreach my $tryserver (keys(%servers)) {
                   8029:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8030:                                   &escape($udom),$tryserver);
                   8031:                 if ($listing eq 'unknown_cmd') {
                   8032: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8033: 				      $udom, $tryserver);
                   8034:                 } else {
                   8035:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8036:                 }
1.841     albertel 8037: 		if ($listing eq 'unknown_cmd') {
                   8038: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8039: 				      $udom, $tryserver);
                   8040: 		    @listing_results = split(/:/,$listing);
                   8041: 		} else {
                   8042: 		    @listing_results =
                   8043: 			map { &unescape($_); } split(/:/,$listing);
                   8044: 		}
                   8045: 		if ($listing_results[0] ne 'no_such_dir' && 
                   8046: 		    $listing_results[0] ne 'empty'       &&
                   8047: 		    $listing_results[0] ne 'con_lost') {
                   8048: 		    foreach my $line (@listing_results) {
                   8049: 			my ($entry) = split(/&/,$line,2);
                   8050: 			$allusers{$entry} = 1;
                   8051: 		    }
                   8052: 		}
1.253     stredwic 8053:             }
                   8054:             my $alluserstr='';
1.800     albertel 8055:             foreach my $user (sort(keys(%allusers))) {
                   8056:                 $alluserstr.=$user.'&user:';
1.253     stredwic 8057:             }
                   8058:             $alluserstr=~s/:$//;
                   8059:             return split(/:/,$alluserstr);
                   8060:         } else {
1.800     albertel 8061:             return ('missing user name');
1.253     stredwic 8062:         }
1.955     raeburn  8063:     } elsif(!defined($getpropath)) {
1.841     albertel 8064:         my @all_domains = sort(&all_domains());
1.955     raeburn  8065:         foreach my $domain (@all_domains) {
                   8066:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   8067:         }
                   8068:         return @all_domains;
                   8069:     } else {
1.800     albertel 8070:         return ('missing domain');
1.275     stredwic 8071:     }
                   8072: }
                   8073: 
                   8074: # --------------------------------------------- GetFileTimestamp
                   8075: # This function utilizes dirlist and returns the date stamp for
                   8076: # when it was last modified.  It will also return an error of -1
                   8077: # if an error occurs
                   8078: 
                   8079: sub GetFileTimestamp {
1.955     raeburn  8080:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8081:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8082:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  8083:     my ($fileStat) = 
                   8084:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   8085:                                  undef,$getuserdir);
1.275     stredwic 8086:     my @stats = split('&', $fileStat);
                   8087:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  8088:         # @stats contains first the filename, then the stat output
                   8089:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8090:     } else {
                   8091:         return -1;
1.253     stredwic 8092:     }
1.26      www      8093: }
                   8094: 
1.712     albertel 8095: sub stat_file {
                   8096:     my ($uri) = @_;
1.787     albertel 8097:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8098: 
1.955     raeburn  8099:     my ($udom,$uname,$file);
1.712     albertel 8100:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8101: 	($udom,$uname,$file) =
1.811     albertel 8102: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8103: 	$file = 'userfiles/'.$file;
                   8104:     }
                   8105:     if ($uri =~ m-^/res/-) {
                   8106: 	($udom,$uname) = 
1.807     albertel 8107: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8108: 	$file = $uri;
                   8109:     }
                   8110: 
                   8111:     if (!$udom || !$uname || !$file) {
                   8112: 	# unable to handle the uri
                   8113: 	return ();
                   8114:     }
1.956     raeburn  8115:     my $getpropath;
                   8116:     if ($file =~ /^userfiles\//) {
                   8117:         $getpropath = 1;
                   8118:     }
1.955     raeburn  8119:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8120:     my @stats = split('&', $result);
1.721     banghart 8121:     
1.712     albertel 8122:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8123: 	shift(@stats); #filename is first
                   8124: 	return @stats;
                   8125:     }
                   8126:     return ();
                   8127: }
                   8128: 
1.26      www      8129: # -------------------------------------------------------- Value of a Condition
                   8130: 
1.713     albertel 8131: # gets the value of a specific preevaluated condition
                   8132: #    stored in the string  $env{user.state.<cid>}
                   8133: # or looks up a condition reference in the bighash and if if hasn't
                   8134: # already been evaluated recurses into docondval to get the value of
                   8135: # the condition, then memoizing it to 
                   8136: #   $env{user.state.<cid>.<condition>}
1.40      www      8137: sub directcondval {
                   8138:     my $number=shift;
1.620     albertel 8139:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8140: 	&Apache::lonuserstate::evalstate();
                   8141:     }
1.713     albertel 8142:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8143: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8144:     } elsif ($number =~ /^_/) {
                   8145: 	my $sub_condition;
                   8146: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8147: 		&GDBM_READER(),0640)) {
                   8148: 	    $sub_condition=$bighash{'conditions'.$number};
                   8149: 	    untie(%bighash);
                   8150: 	}
                   8151: 	my $value = &docondval($sub_condition);
1.949     raeburn  8152: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8153: 	return $value;
                   8154:     }
1.620     albertel 8155:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8156:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8157:     } else {
                   8158:        return 2;
                   8159:     }
                   8160: }
                   8161: 
1.713     albertel 8162: # get the collection of conditions for this resource
1.26      www      8163: sub condval {
                   8164:     my $condidx=shift;
1.54      www      8165:     my $allpathcond='';
1.713     albertel 8166:     foreach my $cond (split(/\|/,$condidx)) {
                   8167: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8168: 	    $allpathcond.=
                   8169: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8170: 	}
1.191     harris41 8171:     }
1.54      www      8172:     $allpathcond=~s/\|$//;
1.713     albertel 8173:     return &docondval($allpathcond);
                   8174: }
                   8175: 
                   8176: #evaluates an expression of conditions
                   8177: sub docondval {
                   8178:     my ($allpathcond) = @_;
                   8179:     my $result=0;
                   8180:     if ($env{'request.course.id'}
                   8181: 	&& defined($allpathcond)) {
                   8182: 	my $operand='|';
                   8183: 	my @stack;
                   8184: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8185: 	    if ($chunk eq '(') {
                   8186: 		push @stack,($operand,$result);
                   8187: 	    } elsif ($chunk eq ')') {
                   8188: 		my $before=pop @stack;
                   8189: 		if (pop @stack eq '&') {
                   8190: 		    $result=$result>$before?$before:$result;
                   8191: 		} else {
                   8192: 		    $result=$result>$before?$result:$before;
                   8193: 		}
                   8194: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8195: 		$operand=$chunk;
                   8196: 	    } else {
                   8197: 		my $new=directcondval($chunk);
                   8198: 		if ($operand eq '&') {
                   8199: 		    $result=$result>$new?$new:$result;
                   8200: 		} else {
                   8201: 		    $result=$result>$new?$result:$new;
                   8202: 		}
                   8203: 	    }
                   8204: 	}
1.26      www      8205:     }
                   8206:     return $result;
1.421     albertel 8207: }
                   8208: 
                   8209: # ---------------------------------------------------- Devalidate courseresdata
                   8210: 
                   8211: sub devalidatecourseresdata {
                   8212:     my ($coursenum,$coursedomain)=@_;
                   8213:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8214:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8215: }
                   8216: 
1.763     www      8217: 
1.200     www      8218: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8219: #
                   8220: #  Parameters:
                   8221: #      $coursenum    - Number of the course.
                   8222: #      $coursedomain - Domain at which the course was created.
                   8223: #  Returns:
                   8224: #     A hash of the course parameters along (I think) with timestamps
                   8225: #     and version info.
1.877     foxr     8226: 
1.624     albertel 8227: sub get_courseresdata {
                   8228:     my ($coursenum,$coursedomain)=@_;
1.200     www      8229:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8230:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8231:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8232:     my %dumpreply;
1.417     albertel 8233:     unless (defined($cached)) {
1.624     albertel 8234: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8235: 	$result=\%dumpreply;
1.251     albertel 8236: 	my ($tmp) = keys(%dumpreply);
                   8237: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8238: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8239: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8240: 	    return $tmp;
1.416     albertel 8241: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8242: 	    $result=undef;
1.599     albertel 8243: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8244: 	}
                   8245:     }
1.624     albertel 8246:     return $result;
                   8247: }
                   8248: 
1.633     albertel 8249: sub devalidateuserresdata {
                   8250:     my ($uname,$udom)=@_;
                   8251:     my $hashid="$udom:$uname";
                   8252:     &devalidate_cache_new('userres',$hashid);
                   8253: }
                   8254: 
1.624     albertel 8255: sub get_userresdata {
                   8256:     my ($uname,$udom)=@_;
                   8257:     #most student don\'t have any data set, check if there is some data
                   8258:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8259: 
                   8260:     my $hashid="$udom:$uname";
                   8261:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8262:     if (!defined($cached)) {
                   8263: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8264: 	$result=\%resourcedata;
                   8265: 	&do_cache_new('userres',$hashid,$result,600);
                   8266:     }
                   8267:     my ($tmp)=keys(%$result);
                   8268:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8269: 	return $result;
                   8270:     }
                   8271:     #error 2 occurs when the .db doesn't exist
                   8272:     if ($tmp!~/error: 2 /) {
1.672     albertel 8273: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8274: 		 " Trying to get resource data for ".
                   8275: 		 $uname." at ".$udom.": ".
                   8276: 		 $tmp."</font>");
                   8277:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8278: 	#&EXT_cache_set($udom,$uname);
                   8279: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8280: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8281:     }
                   8282:     return $tmp;
                   8283: }
1.879     foxr     8284: #----------------------------------------------- resdata - return resource data
                   8285: #  Purpose:
                   8286: #    Return resource data for either users or for a course.
                   8287: #  Parameters:
                   8288: #     $name      - Course/user name.
                   8289: #     $domain    - Name of the domain the user/course is registered on.
                   8290: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8291: #     @which     - Array of names of resources desired.
                   8292: #  Returns:
                   8293: #     The value of the first reasource in @which that is found in the
                   8294: #     resource hash.
                   8295: #  Exceptional Conditions:
                   8296: #     If the $type passed in is not valid (not the string 'course' or 
                   8297: #     'user', an undefined  reference is returned.
                   8298: #     If none of the resources are found, an undef is returned
1.624     albertel 8299: sub resdata {
                   8300:     my ($name,$domain,$type,@which)=@_;
                   8301:     my $result;
                   8302:     if ($type eq 'course') {
                   8303: 	$result=&get_courseresdata($name,$domain);
                   8304:     } elsif ($type eq 'user') {
                   8305: 	$result=&get_userresdata($name,$domain);
                   8306:     }
                   8307:     if (!ref($result)) { return $result; }    
1.251     albertel 8308:     foreach my $item (@which) {
1.927     albertel 8309: 	if (defined($result->{$item->[0]})) {
                   8310: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8311: 	}
1.250     albertel 8312:     }
1.291     albertel 8313:     return undef;
1.200     www      8314: }
                   8315: 
1.379     matthew  8316: #
                   8317: # EXT resource caching routines
                   8318: #
                   8319: 
                   8320: sub clear_EXT_cache_status {
1.383     albertel 8321:     &delenv('cache.EXT.');
1.379     matthew  8322: }
                   8323: 
                   8324: sub EXT_cache_status {
                   8325:     my ($target_domain,$target_user) = @_;
1.383     albertel 8326:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8327:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8328:         # We know already the user has no data
                   8329:         return 1;
                   8330:     } else {
                   8331:         return 0;
                   8332:     }
                   8333: }
                   8334: 
                   8335: sub EXT_cache_set {
                   8336:     my ($target_domain,$target_user) = @_;
1.383     albertel 8337:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8338:     #&appenv({$cachename => time});
1.379     matthew  8339: }
                   8340: 
1.28      www      8341: # --------------------------------------------------------- Value of a Variable
1.58      www      8342: sub EXT {
1.715     albertel 8343: 
1.395     albertel 8344:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8345:     unless ($varname) { return ''; }
1.218     albertel 8346:     #get real user name/domain, courseid and symb
                   8347:     my $courseid;
1.359     albertel 8348:     my $publicuser;
1.427     www      8349:     if ($symbparm) {
                   8350: 	$symbparm=&get_symb_from_alias($symbparm);
                   8351:     }
1.218     albertel 8352:     if (!($uname && $udom)) {
1.790     albertel 8353:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8354:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8355:     } else {
1.620     albertel 8356: 	$courseid=$env{'request.course.id'};
1.218     albertel 8357:     }
1.48      www      8358:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8359:     my $rest;
1.320     albertel 8360:     if (defined($therest[0])) {
1.48      www      8361:        $rest=join('.',@therest);
                   8362:     } else {
                   8363:        $rest='';
                   8364:     }
1.320     albertel 8365: 
1.57      www      8366:     my $qualifierrest=$qualifier;
                   8367:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8368:     my $spacequalifierrest=$space;
                   8369:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8370:     if ($realm eq 'user') {
1.48      www      8371: # --------------------------------------------------------------- user.resource
                   8372: 	if ($space eq 'resource') {
1.651     albertel 8373: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8374: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8375: 		 &&
1.744     albertel 8376: 		 ($symbparm eq &symbread()) ) {	
                   8377: 		# if we are in the middle of processing the resource the
                   8378: 		# get the value we are planning on committing
                   8379:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8380:                     return $Apache::lonhomework::results{$qualifierrest};
                   8381:                 } else {
                   8382:                     return $Apache::lonhomework::history{$qualifierrest};
                   8383:                 }
1.335     albertel 8384: 	    } else {
1.359     albertel 8385: 		my %restored;
1.620     albertel 8386: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8387: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8388: 		} else {
                   8389: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8390: 		}
1.335     albertel 8391: 		return $restored{$qualifierrest};
                   8392: 	    }
1.48      www      8393: # ----------------------------------------------------------------- user.access
                   8394:         } elsif ($space eq 'access') {
1.218     albertel 8395: 	    # FIXME - not supporting calls for a specific user
1.48      www      8396:             return &allowed($qualifier,$rest);
                   8397: # ------------------------------------------ user.preferences, user.environment
                   8398:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8399: 	    if (($uname eq $env{'user.name'}) &&
                   8400: 		($udom eq $env{'user.domain'})) {
                   8401: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8402: 	    } else {
1.359     albertel 8403: 		my %returnhash;
                   8404: 		if (!$publicuser) {
                   8405: 		    %returnhash=&userenvironment($udom,$uname,
                   8406: 						 $qualifierrest);
                   8407: 		}
1.218     albertel 8408: 		return $returnhash{$qualifierrest};
                   8409: 	    }
1.48      www      8410: # ----------------------------------------------------------------- user.course
                   8411:         } elsif ($space eq 'course') {
1.218     albertel 8412: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8413:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8414: # ------------------------------------------------------------------- user.role
                   8415:         } elsif ($space eq 'role') {
1.218     albertel 8416: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8417:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8418:             if ($qualifier eq 'value') {
                   8419: 		return $role;
                   8420:             } elsif ($qualifier eq 'extent') {
                   8421:                 return $where;
                   8422:             }
                   8423: # ----------------------------------------------------------------- user.domain
                   8424:         } elsif ($space eq 'domain') {
1.218     albertel 8425:             return $udom;
1.48      www      8426: # ------------------------------------------------------------------- user.name
                   8427:         } elsif ($space eq 'name') {
1.218     albertel 8428:             return $uname;
1.48      www      8429: # ---------------------------------------------------- Any other user namespace
1.29      www      8430:         } else {
1.359     albertel 8431: 	    my %reply;
                   8432: 	    if (!$publicuser) {
                   8433: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8434: 	    }
                   8435: 	    return $reply{$qualifierrest};
1.48      www      8436:         }
1.236     www      8437:     } elsif ($realm eq 'query') {
                   8438: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8439:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8440: 						[$spacequalifierrest]);
1.620     albertel 8441: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8442:    } elsif ($realm eq 'request') {
1.48      www      8443: # ------------------------------------------------------------- request.browser
                   8444:         if ($space eq 'browser') {
1.430     www      8445: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8446: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8447: 		    return 1;
                   8448: 		} else {
                   8449: 		    return 0;
                   8450: 		}
                   8451: 	    } else {
1.620     albertel 8452: 		return $env{'browser.'.$qualifier};
1.430     www      8453: 	    }
1.57      www      8454: # ------------------------------------------------------------ request.filename
                   8455:         } else {
1.620     albertel 8456:             return $env{'request.'.$spacequalifierrest};
1.29      www      8457:         }
1.28      www      8458:     } elsif ($realm eq 'course') {
1.48      www      8459: # ---------------------------------------------------------- course.description
1.620     albertel 8460:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8461:     } elsif ($realm eq 'resource') {
1.165     www      8462: 
1.620     albertel 8463: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8464: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8465: 	}
1.693     albertel 8466: 
                   8467: 	if ($space eq 'title') {
                   8468: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8469: 	    return &gettitle($symbparm);
                   8470: 	}
                   8471: 	
                   8472: 	if ($space eq 'map') {
                   8473: 	    my ($map) = &decode_symb($symbparm);
                   8474: 	    return &symbread($map);
                   8475: 	}
1.905     albertel 8476: 	if ($space eq 'filename') {
                   8477: 	    if ($symbparm) {
                   8478: 		return &clutter((&decode_symb($symbparm))[2]);
                   8479: 	    }
                   8480: 	    return &hreflocation('',$env{'request.filename'});
                   8481: 	}
1.693     albertel 8482: 
                   8483: 	my ($section, $group, @groups);
1.593     albertel 8484: 	my ($courselevelm,$courselevel);
1.539     albertel 8485: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8486: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8487: 
1.218     albertel 8488: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8489: 
1.60      www      8490: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8491: 	    my $symbp=$symbparm;
1.735     albertel 8492: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8493: 
                   8494: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8495: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8496: 
1.620     albertel 8497: 	    if (($env{'user.name'} eq $uname) &&
                   8498: 		($env{'user.domain'} eq $udom)) {
                   8499: 		$section=$env{'request.course.sec'};
1.733     raeburn  8500:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8501:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8502: 	    } else {
1.539     albertel 8503: 		if (! defined($usection)) {
1.551     albertel 8504: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8505: 		} else {
                   8506: 		    $section = $usection;
                   8507: 		}
1.733     raeburn  8508:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8509: 	    }
                   8510: 
                   8511: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8512: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8513: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8514: 
1.593     albertel 8515: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8516: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8517: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8518: 
1.60      www      8519: # ----------------------------------------------------------- first, check user
1.624     albertel 8520: 
                   8521: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8522: 				       ([$courselevelr,'resource'],
                   8523: 					[$courselevelm,'map'     ],
                   8524: 					[$courselevel, 'course'  ]));
1.931     albertel 8525: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8526: 
1.594     albertel 8527: # ------------------------------------------------ second, check some of course
1.684     raeburn  8528:             my $coursereply;
1.691     raeburn  8529:             if (@groups > 0) {
                   8530:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8531:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8532:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8533:             }
1.96      www      8534: 
1.684     raeburn  8535: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8536: 				  $env{'course.'.$courseid.'.domain'},
                   8537: 				  'course',
                   8538: 				  ([$seclevelr,   'resource'],
                   8539: 				   [$seclevelm,   'map'     ],
                   8540: 				   [$seclevel,    'course'  ],
                   8541: 				   [$courselevelr,'resource']));
                   8542: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8543: 
1.60      www      8544: # ------------------------------------------------------ third, check map parms
1.218     albertel 8545: 	    my %parmhash=();
                   8546: 	    my $thisparm='';
                   8547: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8548: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8549: 		    &GDBM_READER(),0640)) {
1.218     albertel 8550: 		$thisparm=$parmhash{$symbparm};
                   8551: 		untie(%parmhash);
                   8552: 	    }
1.927     albertel 8553: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8554: 	}
1.594     albertel 8555: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8556: 
1.218     albertel 8557: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8558: 	my $filename;
                   8559: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8560: 	if ($symbparm) {
1.409     www      8561: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8562: 	} else {
1.620     albertel 8563: 	    $filename=$env{'request.filename'};
1.282     albertel 8564: 	}
                   8565: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8566: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8567: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8568: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8569: 
1.927     albertel 8570: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8571: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8572: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8573: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8574: 				     $env{'course.'.$courseid.'.domain'},
                   8575: 				     'course',
1.927     albertel 8576: 				     ([$courselevelm,'map'   ],
                   8577: 				      [$courselevel, 'course']));
                   8578: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8579: 	}
1.145     www      8580: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8581: 	unless ($space eq '0') {
1.336     albertel 8582: 	    my @parts=split(/_/,$space);
                   8583: 	    my $id=pop(@parts);
                   8584: 	    my $part=join('_',@parts);
                   8585: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8586: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8587: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8588: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8589: 	}
1.395     albertel 8590: 	if ($recurse) { return undef; }
                   8591: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8592: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8593: # ---------------------------------------------------- Any other user namespace
                   8594:     } elsif ($realm eq 'environment') {
                   8595: # ----------------------------------------------------------------- environment
1.620     albertel 8596: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8597: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8598: 	} else {
1.770     albertel 8599: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8600: 		return '';
                   8601: 	    }
1.219     albertel 8602: 	    my %returnhash=&userenvironment($udom,$uname,
                   8603: 					    $spacequalifierrest);
                   8604: 	    return $returnhash{$spacequalifierrest};
                   8605: 	}
1.28      www      8606:     } elsif ($realm eq 'system') {
1.48      www      8607: # ----------------------------------------------------------------- system.time
                   8608: 	if ($space eq 'time') {
                   8609: 	    return time;
                   8610:         }
1.696     albertel 8611:     } elsif ($realm eq 'server') {
                   8612: # ----------------------------------------------------------------- system.time
                   8613: 	if ($space eq 'name') {
                   8614: 	    return $ENV{'SERVER_NAME'};
                   8615:         }
1.28      www      8616:     }
1.48      www      8617:     return '';
1.61      www      8618: }
                   8619: 
1.927     albertel 8620: sub get_reply {
                   8621:     my ($reply_value) = @_;
1.940     raeburn  8622:     if (ref($reply_value) eq 'ARRAY') {
                   8623:         if (wantarray) {
                   8624: 	    return @$reply_value;
                   8625:         }
                   8626:         return $reply_value->[0];
                   8627:     } else {
                   8628:         return $reply_value;
1.927     albertel 8629:     }
                   8630: }
                   8631: 
1.691     raeburn  8632: sub check_group_parms {
                   8633:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8634:     my @groupitems = ();
                   8635:     my $resultitem;
1.927     albertel 8636:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8637:     foreach my $group (@{$groups}) {
                   8638:         foreach my $level (@levels) {
1.927     albertel 8639:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8640:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8641:         }
                   8642:     }
                   8643:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8644:                             $env{'course.'.$courseid.'.domain'},
                   8645:                                      'course',@groupitems);
                   8646:     return $coursereply;
                   8647: }
                   8648: 
                   8649: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8650:     my ($courseid,@groups) = @_;
                   8651:     @groups = sort(@groups);
1.691     raeburn  8652:     return @groups;
                   8653: }
                   8654: 
1.395     albertel 8655: sub packages_tab_default {
                   8656:     my ($uri,$varname)=@_;
                   8657:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8658: 
                   8659:     my (@extension,@specifics,$do_default);
                   8660:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8661: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8662: 	if ($pack_type eq 'default') {
                   8663: 	    $do_default=1;
                   8664: 	} elsif ($pack_type eq 'extension') {
                   8665: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8666: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8667: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8668: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8669: 	}
                   8670:     }
                   8671:     # first look for a package that matches the requested part id
                   8672:     foreach my $package (@specifics) {
                   8673: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8674: 	next if ($pack_part ne $part);
                   8675: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8676: 	    return $packagetab{"$pack_type&$name&default"};
                   8677: 	}
                   8678:     }
                   8679:     # look for any possible matching non extension_ package
                   8680:     foreach my $package (@specifics) {
                   8681: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8682: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8683: 	    return $packagetab{"$pack_type&$name&default"};
                   8684: 	}
1.585     albertel 8685: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8686: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8687: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8688: 	}
                   8689:     }
1.738     albertel 8690:     # look for any posible extension_ match
                   8691:     foreach my $package (@extension) {
                   8692: 	my ($package,$pack_type)=@{$package};
                   8693: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8694: 	    return $packagetab{"$pack_type&$name&default"};
                   8695: 	}
                   8696: 	if (defined($packagetab{$package."&$name&default"})) {
                   8697: 	    return $packagetab{$package."&$name&default"};
                   8698: 	}
                   8699:     }
                   8700:     # look for a global default setting
                   8701:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8702: 	return $packagetab{"default&$name&default"};
                   8703:     }
1.395     albertel 8704:     return undef;
                   8705: }
                   8706: 
1.334     albertel 8707: sub add_prefix_and_part {
                   8708:     my ($prefix,$part)=@_;
                   8709:     my $keyroot;
                   8710:     if (defined($prefix) && $prefix !~ /^__/) {
                   8711: 	# prefix that has a part already
                   8712: 	$keyroot=$prefix;
                   8713:     } elsif (defined($prefix)) {
                   8714: 	# prefix that is missing a part
                   8715: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8716:     } else {
                   8717: 	# no prefix at all
                   8718: 	if (defined($part)) { $keyroot='_'.$part; }
                   8719:     }
                   8720:     return $keyroot;
                   8721: }
                   8722: 
1.71      www      8723: # ---------------------------------------------------------------- Get metadata
                   8724: 
1.599     albertel 8725: my %metaentry;
1.1070    www      8726: my %importedpartids;
1.71      www      8727: sub metadata {
1.176     www      8728:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8729:     $uri=&declutter($uri);
1.288     albertel 8730:     # if it is a non metadata possible uri return quickly
1.529     albertel 8731:     if (($uri eq '') || 
                   8732: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8733: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8734:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8735: 	return undef;
                   8736:     }
                   8737:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8738: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8739: 	return undef;
1.288     albertel 8740:     }
1.73      www      8741:     my $filename=$uri;
                   8742:     $uri=~s/\.meta$//;
1.172     www      8743: #
                   8744: # Is the metadata already cached?
1.177     www      8745: # Look at timestamp of caching
1.172     www      8746: # Everything is cached by the main uri, libraries are never directly cached
                   8747: #
1.428     albertel 8748:     if (!defined($liburi)) {
1.599     albertel 8749: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8750: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8751:     }
                   8752:     {
1.1069    www      8753: # Imported parts would go here
1.1070    www      8754:         my %importedids=();
                   8755:         my @origfileimportpartids=();
1.1069    www      8756:         my $importedparts=0;
1.172     www      8757: #
                   8758: # Is this a recursive call for a library?
                   8759: #
1.599     albertel 8760: #	if (! exists($metacache{$uri})) {
                   8761: #	    $metacache{$uri}={};
                   8762: #	}
1.924     albertel 8763: 	my $cachetime = 60*60;
1.171     www      8764:         if ($liburi) {
                   8765: 	    $liburi=&declutter($liburi);
                   8766:             $filename=$liburi;
1.401     bowersj2 8767:         } else {
1.599     albertel 8768: 	    &devalidate_cache_new('meta',$uri);
                   8769: 	    undef(%metaentry);
1.401     bowersj2 8770: 	}
1.140     www      8771:         my %metathesekeys=();
1.73      www      8772:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8773: 	my $metastring;
1.924     albertel 8774: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8775: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8776: 	    $metastring = 
1.929     albertel 8777: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8778: 					  ('grade_target' => 'meta'));
                   8779: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8780: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8781:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8782: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8783: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8784: 	    $metastring=&getfile($file);
1.489     albertel 8785: 	}
1.208     albertel 8786:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8787:         my $token;
1.140     www      8788:         undef %metathesekeys;
1.71      www      8789:         while ($token=$parser->get_token) {
1.339     albertel 8790: 	    if ($token->[0] eq 'S') {
                   8791: 		if (defined($token->[2]->{'package'})) {
1.172     www      8792: #
                   8793: # This is a package - get package info
                   8794: #
1.339     albertel 8795: 		    my $package=$token->[2]->{'package'};
                   8796: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8797: 		    if (defined($token->[2]->{'id'})) { 
                   8798: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8799: 		    }
1.599     albertel 8800: 		    if ($metaentry{':packages'}) {
                   8801: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8802: 		    } else {
1.599     albertel 8803: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8804: 		    }
1.736     albertel 8805: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8806: 			my $part=$keyroot;
                   8807: 			$part=~s/^\_//;
1.736     albertel 8808: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8809: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8810: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8811: 			    # ignore package.tab specified default values
                   8812:                             # here &package_tab_default() will fetch those
                   8813: 			    if ($subp eq 'default') { next; }
1.736     albertel 8814: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8815: 			    my $unikey;
                   8816: 			    if ($pack =~ /_0$/) {
                   8817: 				$unikey='parameter_0_'.$name;
                   8818: 				$part=0;
                   8819: 			    } else {
                   8820: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8821: 			    }
1.339     albertel 8822: 			    if ($subp eq 'display') {
                   8823: 				$value.=' [Part: '.$part.']';
                   8824: 			    }
1.599     albertel 8825: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8826: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8827: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8828: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8829: 			    }
1.599     albertel 8830: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8831: 				$metaentry{':'.$unikey}=
                   8832: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8833: 			    }
1.339     albertel 8834: 			}
                   8835: 		    }
                   8836: 		} else {
1.172     www      8837: #
                   8838: # This is not a package - some other kind of start tag
1.339     albertel 8839: #
                   8840: 		    my $entry=$token->[1];
1.1068    www      8841: 		    my $unikey='';
1.175     www      8842: 
1.339     albertel 8843: 		    if ($entry eq 'import') {
1.175     www      8844: #
                   8845: # Importing a library here
1.339     albertel 8846: #
1.1067    www      8847:                         my $location=$parser->get_text('/import');
                   8848:                         my $dir=$filename;
                   8849:                         $dir=~s|[^/]*$||;
                   8850:                         $location=&filelocation($dir,$location);
1.1069    www      8851:                        
1.1068    www      8852:                         my $importmode=$token->[2]->{'importmode'};
                   8853:                         if ($importmode eq 'problem') {
1.1069    www      8854: # Import as problem/response
1.1068    www      8855:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8856:                         } elsif ($importmode eq 'part') {
                   8857: # Import as part(s)
1.1069    www      8858:                            $importedparts=1;
                   8859: # We need to get the original file and the imported file to get the part order correct
                   8860: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8861: # Load and inspect original file
1.1070    www      8862:                            if ($#origfileimportpartids<0) {
                   8863:                               undef(%importedpartids);
                   8864:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8865:                               my $origfile=&getfile($origfilelocation);
                   8866:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8867:                            }
                   8868: 
1.1069    www      8869: # Load and inspect imported file
                   8870:                            my $impfile=&getfile($location);
                   8871:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8872:                            if ($#impfilepartids>=0) {
                   8873: # This problem had parts
1.1070    www      8874:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8875:                            } else {
                   8876: # Importing by turning a single problem into a problem part
                   8877: # It gets the import-tags ID as part-ID
                   8878:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8879:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8880:                            }
1.1068    www      8881:                         } else {
                   8882: # Normal import
                   8883:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8884:                            if (defined($token->[2]->{'id'})) {
                   8885:                               $unikey.='_'.$token->[2]->{'id'};
                   8886:                            }
1.1067    www      8887:                         }
                   8888: 
1.339     albertel 8889: 			if ($depthcount<20) {
1.736     albertel 8890: 			    my $metadata = 
                   8891: 				&metadata($uri,'keys', $location,$unikey,
                   8892: 					  $depthcount+1);
                   8893: 			    foreach my $meta (split(',',$metadata)) {
                   8894: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8895: 				$metathesekeys{$meta}=1;
1.339     albertel 8896: 			    }
1.1068    www      8897: 			
                   8898:                         }
1.1067    www      8899: 		    } else {
                   8900: #
                   8901: # Not importing, some other kind of non-package, non-library start tag
                   8902: # 
                   8903:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8904:                         if (defined($token->[2]->{'id'})) {
                   8905:                             $unikey.='_'.$token->[2]->{'id'};
                   8906:                         }
1.339     albertel 8907: 			if (defined($token->[2]->{'name'})) { 
                   8908: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8909: 			}
                   8910: 			$metathesekeys{$unikey}=1;
1.736     albertel 8911: 			foreach my $param (@{$token->[3]}) {
                   8912: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8913: 				$token->[2]->{$param};
1.339     albertel 8914: 			}
                   8915: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8916: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8917: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8918: 		 # only ws inside the tag, and not in default, so use default
                   8919: 		 # as value
1.599     albertel 8920: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8921: 			} elsif ( $internaltext =~ /\S/ ) {
                   8922: 		  # something interesting inside the tag
                   8923: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8924: 			} else {
1.908     albertel 8925: 		  # no interesting values, don't set a default
1.339     albertel 8926: 			}
1.172     www      8927: # end of not-a-package not-a-library import
1.339     albertel 8928: 		    }
1.172     www      8929: # end of not-a-package start tag
1.339     albertel 8930: 		}
1.172     www      8931: # the next is the end of "start tag"
1.339     albertel 8932: 	    }
                   8933: 	}
1.483     albertel 8934: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8935: 	$extension = lc($extension);
                   8936: 	if ($extension eq 'htm') { $extension='html'; }
                   8937: 
1.737     albertel 8938: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8939: 	    #no specific packages #how's our extension
                   8940: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8941: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8942: 					 \%metathesekeys);
                   8943: 	}
1.883     albertel 8944: 
                   8945: 	if (!exists($metaentry{':packages'})
                   8946: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8947: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8948: 		#no specific packages well let's get default then
                   8949: 		if ($key!~/^default&/) { next; }
1.488     albertel 8950: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8951: 					     \%metathesekeys);
                   8952: 	    }
                   8953: 	}
1.338     www      8954: # are there custom rights to evaluate
1.599     albertel 8955: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8956: 
1.338     www      8957:     #
                   8958:     # Importing a rights file here
1.339     albertel 8959:     #
                   8960: 	    unless ($depthcount) {
1.599     albertel 8961: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8962: 		my $dir=$filename;
                   8963: 		$dir=~s|[^/]*$||;
                   8964: 		$location=&filelocation($dir,$location);
1.736     albertel 8965: 		my $rights_metadata =
                   8966: 		    &metadata($uri,'keys',$location,'_rights',
                   8967: 			      $depthcount+1);
                   8968: 		foreach my $rights (split(',',$rights_metadata)) {
                   8969: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8970: 		    $metathesekeys{$rights}=1;
1.339     albertel 8971: 		}
                   8972: 	    }
                   8973: 	}
1.737     albertel 8974: 	# uniqifiy package listing
                   8975: 	my %seen;
                   8976: 	my @uniq_packages =
                   8977: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8978: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8979: 
1.1070    www      8980:         if ($importedparts) {
                   8981: # We had imported parts and need to rebuild partorder
                   8982:            $metaentry{':partorder'}='';
                   8983:            $metathesekeys{'partorder'}=1;
                   8984:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8985:                if ($origfileimportpartids[$index] eq 'part') {
                   8986: # original part, part of the problem
                   8987:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8988:                } else {
                   8989: # we have imported parts at this position
                   8990:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8991:                }
                   8992:            }
                   8993:            $metaentry{':partorder'}=~s/^\,//;
                   8994:         }
                   8995: 
1.737     albertel 8996: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8997: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8998: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8999: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9000: # this is the end of "was not already recently cached
1.71      www      9001:     }
1.599     albertel 9002:     return $metaentry{':'.$what};
1.261     albertel 9003: }
                   9004: 
1.488     albertel 9005: sub metadata_create_package_def {
1.483     albertel 9006:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9007:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9008:     if ($subp eq 'default') { next; }
                   9009:     
1.599     albertel 9010:     if (defined($metaentry{':packages'})) {
                   9011: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9012:     } else {
1.599     albertel 9013: 	$metaentry{':packages'}=$package;
1.483     albertel 9014:     }
                   9015:     my $value=$packagetab{$key};
                   9016:     my $unikey;
                   9017:     $unikey='parameter_0_'.$name;
1.599     albertel 9018:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9019:     $$metathesekeys{$unikey}=1;
1.599     albertel 9020:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9021: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9022:     }
1.599     albertel 9023:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9024: 	$metaentry{':'.$unikey}=
                   9025: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9026:     }
                   9027: }
                   9028: 
1.261     albertel 9029: sub metadata_generate_part0 {
                   9030:     my ($metadata,$metacache,$uri) = @_;
                   9031:     my %allnames;
1.737     albertel 9032:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9033: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9034: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9035: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9036: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9037: 	    $allnames{$name}=$part;
                   9038: 	  }
                   9039: 	}
                   9040:     }
                   9041:     foreach my $name (keys(%allnames)) {
                   9042:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9043:       my $key=":parameter_0_$name";
1.261     albertel 9044:       $$metacache{"$key.part"}='0';
                   9045:       $$metacache{"$key.name"}=$name;
1.428     albertel 9046:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9047: 					   $allnames{$name}.'_'.$name.
                   9048: 					   '.type'};
1.428     albertel 9049:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9050: 			     '.display'};
1.644     www      9051:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9052:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9053:       $$metacache{"$key.display"}=$olddis;
                   9054:     }
1.71      www      9055: }
                   9056: 
1.764     albertel 9057: # ------------------------------------------------------ Devalidate title cache
                   9058: 
                   9059: sub devalidate_title_cache {
                   9060:     my ($url)=@_;
                   9061:     if (!$env{'request.course.id'}) { return; }
                   9062:     my $symb=&symbread($url);
                   9063:     if (!$symb) { return; }
                   9064:     my $key=$env{'request.course.id'}."\0".$symb;
                   9065:     &devalidate_cache_new('title',$key);
                   9066: }
                   9067: 
1.1014    droeschl 9068: # ------------------------------------------------- Get the title of a course
                   9069: 
                   9070: sub current_course_title {
                   9071:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9072: }
1.301     www      9073: # ------------------------------------------------- Get the title of a resource
                   9074: 
                   9075: sub gettitle {
                   9076:     my $urlsymb=shift;
                   9077:     my $symb=&symbread($urlsymb);
1.534     albertel 9078:     if ($symb) {
1.620     albertel 9079: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9080: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9081: 	if (defined($cached)) { 
                   9082: 	    return $result;
                   9083: 	}
1.534     albertel 9084: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9085: 	my $title='';
1.907     albertel 9086: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9087: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9088: 	} else {
                   9089: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9090: 		    &GDBM_READER(),0640)) {
                   9091: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9092: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9093: 		untie(%bighash);
                   9094: 	    }
1.534     albertel 9095: 	}
                   9096: 	$title=~s/\&colon\;/\:/gs;
                   9097: 	if ($title) {
1.599     albertel 9098: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9099: 	}
                   9100: 	$urlsymb=$url;
                   9101:     }
                   9102:     my $title=&metadata($urlsymb,'title');
                   9103:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9104:     return $title;
1.301     www      9105: }
1.613     albertel 9106: 
1.614     albertel 9107: sub get_slot {
                   9108:     my ($which,$cnum,$cdom)=@_;
                   9109:     if (!$cnum || !$cdom) {
1.790     albertel 9110: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9111: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9112: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9113:     }
1.703     albertel 9114:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9115:     my %slotinfo;
                   9116:     if (exists($remembered{$key})) {
                   9117: 	$slotinfo{$which} = $remembered{$key};
                   9118:     } else {
                   9119: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9120: 	&Apache::lonhomework::showhash(%slotinfo);
                   9121: 	my ($tmp)=keys(%slotinfo);
                   9122: 	if ($tmp=~/^error:/) { return (); }
                   9123: 	$remembered{$key} = $slotinfo{$which};
                   9124:     }
1.616     albertel 9125:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9126: 	return %{$slotinfo{$which}};
                   9127:     }
                   9128:     return $slotinfo{$which};
1.614     albertel 9129: }
1.31      www      9130: # ------------------------------------------------- Update symbolic store links
                   9131: 
                   9132: sub symblist {
                   9133:     my ($mapname,%newhash)=@_;
1.438     www      9134:     $mapname=&deversion(&declutter($mapname));
1.31      www      9135:     my %hash;
1.620     albertel 9136:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9137:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9138:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9139: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9140: 		next if ($url eq 'last_known'
                   9141: 			 && $env{'form.no_update_last_known'});
                   9142: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9143: 						    $newhash{$url}->[1],
                   9144: 						    $newhash{$url}->[0]);
1.191     harris41 9145:             }
1.31      www      9146:             if (untie(%hash)) {
                   9147: 		return 'ok';
                   9148:             }
                   9149:         }
                   9150:     }
                   9151:     return 'error';
1.212     www      9152: }
                   9153: 
                   9154: # --------------------------------------------------------------- Verify a symb
                   9155: 
                   9156: sub symbverify {
1.510     www      9157:     my ($symb,$thisurl)=@_;
                   9158:     my $thisfn=$thisurl;
1.439     www      9159:     $thisfn=&declutter($thisfn);
1.215     www      9160: # direct jump to resource in page or to a sequence - will construct own symbs
                   9161:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9162: # check URL part
1.409     www      9163:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9164: 
1.431     www      9165:     unless ($url eq $thisfn) { return 0; }
1.213     www      9166: 
1.216     www      9167:     $symb=&symbclean($symb);
1.510     www      9168:     $thisurl=&deversion($thisurl);
1.439     www      9169:     $thisfn=&deversion($thisfn);
1.213     www      9170: 
                   9171:     my %bighash;
                   9172:     my $okay=0;
1.431     www      9173: 
1.620     albertel 9174:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9175:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9176:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9177:             $thisurl =~ s/\?.+$//;
                   9178:         }
1.510     www      9179:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9180:         unless ($ids) {
                   9181:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9182:             $ids=$bighash{$idkey};
1.216     www      9183:         }
                   9184:         if ($ids) {
                   9185: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9186: 	    foreach my $id (split(/\,/,$ids)) {
                   9187: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9188:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9189:                    $symb =~ s/\?.+$//;
                   9190:                }
1.216     www      9191:                if (
                   9192:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9193:    eq $symb) { 
1.620     albertel 9194: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9195: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9196:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9197: 		       $okay=1; 
                   9198: 		   }
                   9199: 	       }
1.216     www      9200: 	   }
                   9201:         }
1.213     www      9202: 	untie(%bighash);
                   9203:     }
                   9204:     return $okay;
1.31      www      9205: }
                   9206: 
1.210     www      9207: # --------------------------------------------------------------- Clean-up symb
                   9208: 
                   9209: sub symbclean {
                   9210:     my $symb=shift;
1.568     albertel 9211:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9212: # remove version from map
                   9213:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9214: 
1.210     www      9215: # remove version from URL
                   9216:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9217: 
1.507     www      9218: # remove wrapper
                   9219: 
1.510     www      9220:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9221:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9222:     return $symb;
1.409     www      9223: }
                   9224: 
                   9225: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9226: 
                   9227: sub encode_symb {
                   9228:     my ($map,$resid,$url)=@_;
                   9229:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9230: }
1.409     www      9231: 
                   9232: sub decode_symb {
1.568     albertel 9233:     my $symb=shift;
                   9234:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9235:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9236:     return (&fixversion($map),$resid,&fixversion($url));
                   9237: }
                   9238: 
                   9239: sub fixversion {
                   9240:     my $fn=shift;
1.609     banghart 9241:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9242:     my %bighash;
                   9243:     my $uri=&clutter($fn);
1.620     albertel 9244:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9245: # is this cached?
1.599     albertel 9246:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9247:     if (defined($cached)) { return $result; }
                   9248: # unfortunately not cached, or expired
1.620     albertel 9249:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9250: 	    &GDBM_READER(),0640)) {
                   9251:  	if ($bighash{'version_'.$uri}) {
                   9252:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9253:  	    unless (($version eq 'mostrecent') || 
                   9254: 		    ($version==&getversion($uri))) {
1.440     www      9255:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9256:  	    }
                   9257:  	}
                   9258:  	untie %bighash;
1.413     www      9259:     }
1.599     albertel 9260:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9261: }
                   9262: 
                   9263: sub deversion {
                   9264:     my $url=shift;
                   9265:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9266:     return $url;
1.210     www      9267: }
                   9268: 
1.31      www      9269: # ------------------------------------------------------ Return symb list entry
                   9270: 
                   9271: sub symbread {
1.249     www      9272:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9273:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9274:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9275: # no filename provided? try from environment
1.44      www      9276:     unless ($thisfn) {
1.620     albertel 9277:         if ($env{'request.symb'}) {
                   9278: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9279: 	}
1.620     albertel 9280: 	$thisfn=$env{'request.filename'};
1.44      www      9281:     }
1.569     albertel 9282:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9283: # is that filename actually a symb? Verify, clean, and return
                   9284:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9285: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9286: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9287: 	}
1.242     www      9288:     }
1.44      www      9289:     $thisfn=declutter($thisfn);
1.31      www      9290:     my %hash;
1.37      www      9291:     my %bighash;
                   9292:     my $syval='';
1.620     albertel 9293:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9294:         my $targetfn = $thisfn;
1.609     banghart 9295:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9296:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9297:         }
1.687     albertel 9298: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9299: 	    $targetfn=$1;
                   9300: 	}
1.620     albertel 9301:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9302:                       &GDBM_READER(),0640)) {
1.481     raeburn  9303: 	    $syval=$hash{$targetfn};
1.37      www      9304:             untie(%hash);
                   9305:         }
                   9306: # ---------------------------------------------------------- There was an entry
                   9307:         if ($syval) {
1.601     albertel 9308: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9309: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9310: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9311: 		    #return $env{$cache_str}='';
1.601     albertel 9312: 		#}    
                   9313: 		#$syval.=$1;
                   9314: 	    #}
1.37      www      9315:         } else {
                   9316: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9317:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9318:                             &GDBM_READER(),0640)) {
1.37      www      9319: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9320:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9321:               unless ($ids) { 
                   9322:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9323:               }
                   9324:               unless ($ids) {
                   9325: # alias?
                   9326: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9327:               }
1.37      www      9328:               if ($ids) {
                   9329: # ------------------------------------------------------------------- Has ID(s)
                   9330:                  my @possibilities=split(/\,/,$ids);
1.39      www      9331:                  if ($#possibilities==0) {
                   9332: # ----------------------------------------------- There is only one possibility
1.37      www      9333: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9334: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9335: 						    $resid,$thisfn);
1.249     www      9336:                  } elsif (!$donotrecurse) {
1.39      www      9337: # ------------------------------------------ There is more than one possibility
                   9338:                      my $realpossible=0;
1.800     albertel 9339:                      foreach my $id (@possibilities) {
                   9340: 			 my $file=$bighash{'src_'.$id};
1.39      www      9341:                          if (&allowed('bre',$file)) {
1.800     albertel 9342:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9343:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9344: 				$realpossible++;
1.626     albertel 9345:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9346: 						    $resid,$thisfn);
1.39      www      9347:                             }
                   9348: 			 }
1.191     harris41 9349:                      }
1.39      www      9350: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9351:                  } else {
                   9352:                      $syval='';
1.37      www      9353:                  }
                   9354: 	      }
                   9355:               untie(%bighash)
1.481     raeburn  9356:            }
1.31      www      9357:         }
1.62      www      9358:         if ($syval) {
1.620     albertel 9359: 	    return $env{$cache_str}=$syval;
1.62      www      9360:         }
1.31      www      9361:     }
1.949     raeburn  9362:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9363:     return $env{$cache_str}='';
1.31      www      9364: }
                   9365: 
                   9366: # ---------------------------------------------------------- Return random seed
                   9367: 
1.32      www      9368: sub numval {
                   9369:     my $txt=shift;
                   9370:     $txt=~tr/A-J/0-9/;
                   9371:     $txt=~tr/a-j/0-9/;
                   9372:     $txt=~tr/K-T/0-9/;
                   9373:     $txt=~tr/k-t/0-9/;
                   9374:     $txt=~tr/U-Z/0-5/;
                   9375:     $txt=~tr/u-z/0-5/;
                   9376:     $txt=~s/\D//g;
1.564     albertel 9377:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9378:     return int($txt);
1.368     albertel 9379: }
                   9380: 
1.484     albertel 9381: sub numval2 {
                   9382:     my $txt=shift;
                   9383:     $txt=~tr/A-J/0-9/;
                   9384:     $txt=~tr/a-j/0-9/;
                   9385:     $txt=~tr/K-T/0-9/;
                   9386:     $txt=~tr/k-t/0-9/;
                   9387:     $txt=~tr/U-Z/0-5/;
                   9388:     $txt=~tr/u-z/0-5/;
                   9389:     $txt=~s/\D//g;
                   9390:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9391:     my $total;
                   9392:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9393:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9394:     return int($total);
                   9395: }
                   9396: 
1.575     albertel 9397: sub numval3 {
                   9398:     use integer;
                   9399:     my $txt=shift;
                   9400:     $txt=~tr/A-J/0-9/;
                   9401:     $txt=~tr/a-j/0-9/;
                   9402:     $txt=~tr/K-T/0-9/;
                   9403:     $txt=~tr/k-t/0-9/;
                   9404:     $txt=~tr/U-Z/0-5/;
                   9405:     $txt=~tr/u-z/0-5/;
                   9406:     $txt=~s/\D//g;
                   9407:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9408:     my $total;
                   9409:     foreach my $val (@txts) { $total+=$val; }
                   9410:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9411:     return $total;
                   9412: }
                   9413: 
1.675     albertel 9414: sub digest {
                   9415:     my ($data)=@_;
                   9416:     my $digest=&Digest::MD5::md5($data);
                   9417:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9418:     my ($e,$f);
                   9419:     {
                   9420:         use integer;
                   9421:         $e=($a+$b);
                   9422:         $f=($c+$d);
                   9423:         if ($_64bit) {
                   9424:             $e=(($e<<32)>>32);
                   9425:             $f=(($f<<32)>>32);
                   9426:         }
                   9427:     }
                   9428:     if (wantarray) {
                   9429: 	return ($e,$f);
                   9430:     } else {
                   9431: 	my $g;
                   9432: 	{
                   9433: 	    use integer;
                   9434: 	    $g=($e+$f);
                   9435: 	    if ($_64bit) {
                   9436: 		$g=(($g<<32)>>32);
                   9437: 	    }
                   9438: 	}
                   9439: 	return $g;
                   9440:     }
                   9441: }
                   9442: 
1.368     albertel 9443: sub latest_rnd_algorithm_id {
1.675     albertel 9444:     return '64bit5';
1.366     albertel 9445: }
1.32      www      9446: 
1.503     albertel 9447: sub get_rand_alg {
                   9448:     my ($courseid)=@_;
1.790     albertel 9449:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9450:     if ($courseid) {
1.620     albertel 9451: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9452:     }
                   9453:     return &latest_rnd_algorithm_id();
                   9454: }
                   9455: 
1.562     albertel 9456: sub validCODE {
                   9457:     my ($CODE)=@_;
                   9458:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9459:     return 0;
                   9460: }
                   9461: 
1.491     albertel 9462: sub getCODE {
1.620     albertel 9463:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9464:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9465: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9466: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9467: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9468:     }
                   9469:     return undef;
                   9470: }
                   9471: 
1.31      www      9472: sub rndseed {
1.155     albertel 9473:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9474:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9475:     if (!defined($symb)) {
1.366     albertel 9476: 	unless ($symb=$wsymb) { return time; }
                   9477:     }
                   9478:     if (!$courseid) { $courseid=$wcourseid; }
                   9479:     if (!$domain) { $domain=$wdomain; }
                   9480:     if (!$username) { $username=$wusername }
1.503     albertel 9481:     my $which=&get_rand_alg();
1.1110    www      9482: 
1.491     albertel 9483:     if (defined(&getCODE())) {
1.675     albertel 9484: 	if ($which eq '64bit5') {
                   9485: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9486: 	} elsif ($which eq '64bit4') {
1.575     albertel 9487: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9488: 	} else {
                   9489: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9490: 	}
1.675     albertel 9491:     } elsif ($which eq '64bit5') {
                   9492: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9493:     } elsif ($which eq '64bit4') {
                   9494: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9495:     } elsif ($which eq '64bit3') {
                   9496: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9497:     } elsif ($which eq '64bit2') {
                   9498: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9499:     } elsif ($which eq '64bit') {
                   9500: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9501:     }
                   9502:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9503: }
                   9504: 
                   9505: sub rndseed_32bit {
                   9506:     my ($symb,$courseid,$domain,$username)=@_;
                   9507:     {
                   9508: 	use integer;
                   9509: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9510: 	my $symbseed=numval($symb) << 22;
                   9511: 	my $namechck=unpack("%32C*",$username) << 17;
                   9512: 	my $nameseed=numval($username) << 12;
                   9513: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9514: 	my $courseseed=unpack("%32C*",$courseid);
                   9515: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9516: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9517: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9518: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9519: 	return $num;
                   9520:     }
                   9521: }
                   9522: 
                   9523: sub rndseed_64bit {
                   9524:     my ($symb,$courseid,$domain,$username)=@_;
                   9525:     {
                   9526: 	use integer;
                   9527: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9528: 	my $symbseed=numval($symb) << 10;
                   9529: 	my $namechck=unpack("%32S*",$username);
                   9530: 	
                   9531: 	my $nameseed=numval($username) << 21;
                   9532: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9533: 	my $courseseed=unpack("%32S*",$courseid);
                   9534: 	
                   9535: 	my $num1=$symbchck+$symbseed+$namechck;
                   9536: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9537: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9538: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9539: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9540: 	return "$num1,$num2";
1.155     albertel 9541:     }
1.366     albertel 9542: }
                   9543: 
1.443     albertel 9544: sub rndseed_64bit2 {
                   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=numval($symb) << 10;
                   9552: 	my $namechck=unpack("%32S*",$username.' ');
                   9553: 	
                   9554: 	my $nameseed=numval($username) << 21;
1.501     albertel 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 :$num:$symb");
1.803     albertel 9562: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9563: 	return "$num1,$num2";
                   9564:     }
                   9565: }
                   9566: 
                   9567: sub rndseed_64bit3 {
                   9568:     my ($symb,$courseid,$domain,$username)=@_;
                   9569:     {
                   9570: 	use integer;
                   9571: 	# strings need to be an even # of cahracters long, it it is odd the
                   9572:         # last characters gets thrown away
                   9573: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9574: 	my $symbseed=numval2($symb) << 10;
                   9575: 	my $namechck=unpack("%32S*",$username.' ');
                   9576: 	
                   9577: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9578: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9579: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9580: 	
                   9581: 	my $num1=$symbchck+$symbseed+$namechck;
                   9582: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9583: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9584: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9585: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9586: 	
1.503     albertel 9587: 	return "$num1:$num2";
1.443     albertel 9588:     }
                   9589: }
                   9590: 
1.575     albertel 9591: sub rndseed_64bit4 {
                   9592:     my ($symb,$courseid,$domain,$username)=@_;
                   9593:     {
                   9594: 	use integer;
                   9595: 	# strings need to be an even # of cahracters long, it it is odd the
                   9596:         # last characters gets thrown away
                   9597: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9598: 	my $symbseed=numval3($symb) << 10;
                   9599: 	my $namechck=unpack("%32S*",$username.' ');
                   9600: 	
                   9601: 	my $nameseed=numval3($username) << 21;
                   9602: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9603: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9604: 	
                   9605: 	my $num1=$symbchck+$symbseed+$namechck;
                   9606: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9607: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9608: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9609: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9610: 	
1.575     albertel 9611: 	return "$num1:$num2";
                   9612:     }
                   9613: }
                   9614: 
1.675     albertel 9615: sub rndseed_64bit5 {
                   9616:     my ($symb,$courseid,$domain,$username)=@_;
                   9617:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9618:     return "$num1:$num2";
                   9619: }
                   9620: 
1.366     albertel 9621: sub rndseed_CODE_64bit {
                   9622:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9623:     {
1.366     albertel 9624: 	use integer;
1.443     albertel 9625: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9626: 	my $symbseed=numval2($symb);
1.491     albertel 9627: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9628: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9629: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9630: 	my $num1=$symbseed+$CODEchck;
                   9631: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9632: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9633: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9634: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9635: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9636: 	return "$num1:$num2";
1.366     albertel 9637:     }
                   9638: }
                   9639: 
1.575     albertel 9640: sub rndseed_CODE_64bit4 {
                   9641:     my ($symb,$courseid,$domain,$username)=@_;
                   9642:     {
                   9643: 	use integer;
                   9644: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9645: 	my $symbseed=numval3($symb);
                   9646: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9647: 	my $CODEseed=numval3(&getCODE());
                   9648: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9649: 	my $num1=$symbseed+$CODEchck;
                   9650: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9651: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9652: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9653: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9654: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9655: 	return "$num1:$num2";
                   9656:     }
                   9657: }
                   9658: 
1.675     albertel 9659: sub rndseed_CODE_64bit5 {
                   9660:     my ($symb,$courseid,$domain,$username)=@_;
                   9661:     my $code = &getCODE();
                   9662:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9663:     return "$num1:$num2";
                   9664: }
                   9665: 
1.366     albertel 9666: sub setup_random_from_rndseed {
                   9667:     my ($rndseed)=@_;
1.503     albertel 9668:     if ($rndseed =~/([,:])/) {
                   9669: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9670: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9671:     } else {
                   9672: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9673:     }
1.36      albertel 9674: }
                   9675: 
1.474     albertel 9676: sub latest_receipt_algorithm_id {
1.835     albertel 9677:     return 'receipt3';
1.474     albertel 9678: }
                   9679: 
1.480     www      9680: sub recunique {
                   9681:     my $fucourseid=shift;
                   9682:     my $unique;
1.835     albertel 9683:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9684: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9685: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9686:     } else {
                   9687: 	$unique=$perlvar{'lonReceipt'};
                   9688:     }
                   9689:     return unpack("%32C*",$unique);
                   9690: }
                   9691: 
                   9692: sub recprefix {
                   9693:     my $fucourseid=shift;
                   9694:     my $prefix;
1.835     albertel 9695:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9696: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9697: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9698:     } else {
                   9699: 	$prefix=$perlvar{'lonHostID'};
                   9700:     }
                   9701:     return unpack("%32C*",$prefix);
                   9702: }
                   9703: 
1.76      www      9704: sub ireceipt {
1.474     albertel 9705:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9706: 
                   9707:     my $return =&recprefix($fucourseid).'-';
                   9708: 
                   9709:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9710: 	$env{'request.state'} eq 'construct') {
                   9711: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9712: 	return $return;
                   9713:     }
                   9714: 
1.76      www      9715:     my $cuname=unpack("%32C*",$funame);
                   9716:     my $cudom=unpack("%32C*",$fudom);
                   9717:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9718:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9719:     my $cunique=&recunique($fucourseid);
1.474     albertel 9720:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9721:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9722: 
1.790     albertel 9723: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9724: 			       
                   9725: 	$return.= ($cunique%$cuname+
                   9726: 		   $cunique%$cudom+
                   9727: 		   $cusymb%$cuname+
                   9728: 		   $cusymb%$cudom+
                   9729: 		   $cucourseid%$cuname+
                   9730: 		   $cucourseid%$cudom+
                   9731: 		   $cpart%$cuname+
                   9732: 		   $cpart%$cudom);
                   9733:     } else {
                   9734: 	$return.= ($cunique%$cuname+
                   9735: 		   $cunique%$cudom+
                   9736: 		   $cusymb%$cuname+
                   9737: 		   $cusymb%$cudom+
                   9738: 		   $cucourseid%$cuname+
                   9739: 		   $cucourseid%$cudom);
                   9740:     }
                   9741:     return $return;
1.76      www      9742: }
                   9743: 
                   9744: sub receipt {
1.474     albertel 9745:     my ($part)=@_;
1.790     albertel 9746:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9747:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9748: }
1.260     ng       9749: 
1.790     albertel 9750: sub whichuser {
                   9751:     my ($passedsymb)=@_;
                   9752:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9753:     if (defined($env{'form.grade_symb'})) {
                   9754: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9755: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9756: 	if (!$allowed &&
                   9757: 	    exists($env{'request.course.sec'}) &&
                   9758: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9759: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9760: 			      '/'.$env{'request.course.sec'});
                   9761: 	}
                   9762: 	if ($allowed) {
                   9763: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9764: 	    $courseid=$tmp_courseid;
                   9765: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9766: 	    ($name)=&get_env_multiple('form.grade_username');
                   9767: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9768: 	}
                   9769:     }
                   9770:     if (!$passedsymb) {
                   9771: 	$symb=&symbread();
                   9772:     } else {
                   9773: 	$symb=$passedsymb;
                   9774:     }
                   9775:     $courseid=$env{'request.course.id'};
                   9776:     $domain=$env{'user.domain'};
                   9777:     $name=$env{'user.name'};
                   9778:     if ($name eq 'public' && $domain eq 'public') {
                   9779: 	if (!defined($env{'form.username'})) {
                   9780: 	    $env{'form.username'}.=time.rand(10000000);
                   9781: 	}
                   9782: 	$name.=$env{'form.username'};
                   9783:     }
                   9784:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9785: 
                   9786: }
                   9787: 
1.36      albertel 9788: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9789: # returns either the contents of the file or 
                   9790: # -1 if the file doesn't exist
1.481     raeburn  9791: #
                   9792: # if the target is a file that was uploaded via DOCS, 
                   9793: # a check will be made to see if a current copy exists on the local server,
                   9794: # if it does this will be served, otherwise a copy will be retrieved from
                   9795: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9796: # the local server.   
1.472     albertel 9797: 
1.36      albertel 9798: sub getfile {
1.538     albertel 9799:     my ($file) = @_;
1.609     banghart 9800:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9801:     &repcopy($file);
                   9802:     return &readfile($file);
                   9803: }
                   9804: 
                   9805: sub repcopy_userfile {
                   9806:     my ($file)=@_;
1.609     banghart 9807:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9808:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9809:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9810: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9811:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9812:     if (-e "$file") {
1.828     www      9813: # we already have a local copy, check it out
1.538     albertel 9814: 	my @fileinfo = stat($file);
1.828     www      9815: 	my $rtncode;
                   9816: 	my $info;
1.538     albertel 9817: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9818: 	if ($lwpresp ne 'ok') {
1.828     www      9819: # there is no such file anymore, even though we had a local copy
1.482     albertel 9820: 	    if ($rtncode eq '404') {
1.538     albertel 9821: 		unlink($file);
1.482     albertel 9822: 	    }
                   9823: 	    return -1;
                   9824: 	}
                   9825: 	if ($info < $fileinfo[9]) {
1.828     www      9826: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9827: 	    return 'ok';
1.828     www      9828: 	} else {
                   9829: # the file is outdated, get rid of it
                   9830: 	    unlink($file);
1.482     albertel 9831: 	}
1.828     www      9832:     }
                   9833: # one way or the other, at this point, we don't have the file
                   9834: # construct the correct path for the file
                   9835:     my @parts = ($cdom,$cnum); 
                   9836:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9837: 	push @parts, split(/\//,$1);
                   9838:     }
                   9839:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9840:     foreach my $part (@parts) {
                   9841: 	$path .= '/'.$part;
                   9842: 	if (!-e $path) {
                   9843: 	    mkdir($path,0770);
1.482     albertel 9844: 	}
                   9845:     }
1.828     www      9846: # now the path exists for sure
                   9847: # get a user agent
                   9848:     my $ua=new LWP::UserAgent;
                   9849:     my $transferfile=$file.'.in.transfer';
                   9850: # FIXME: this should flock
                   9851:     if (-e $transferfile) { return 'ok'; }
                   9852:     my $request;
                   9853:     $uri=~s/^\///;
1.980     raeburn  9854:     my $homeserver = &homeserver($cnum,$cdom);
                   9855:     my $protocol = $protocol{$homeserver};
                   9856:     $protocol = 'http' if ($protocol ne 'https');
                   9857:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9858:     my $response=$ua->request($request,$transferfile);
                   9859: # did it work?
                   9860:     if ($response->is_error()) {
                   9861: 	unlink($transferfile);
                   9862: 	&logthis("Userfile repcopy failed for $uri");
                   9863: 	return -1;
                   9864:     }
                   9865: # worked, rename the transfer file
                   9866:     rename($transferfile,$file);
1.607     raeburn  9867:     return 'ok';
1.481     raeburn  9868: }
                   9869: 
1.517     albertel 9870: sub tokenwrapper {
                   9871:     my $uri=shift;
1.980     raeburn  9872:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9873:     $uri=~s|^/||;
1.620     albertel 9874:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9875:     my $token=$1;
1.552     albertel 9876:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9877:     if ($udom && $uname && $file) {
                   9878: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9879:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9880:         my $homeserver = &homeserver($uname,$udom);
                   9881:         my $protocol = $protocol{$homeserver};
                   9882:         $protocol = 'http' if ($protocol ne 'https');
                   9883:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9884:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9885:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9886:     } else {
                   9887:         return '/adm/notfound.html';
                   9888:     }
                   9889: }
                   9890: 
1.828     www      9891: # call with reqtype HEAD: get last modification time
                   9892: # call with reqtype GET: get the file contents
                   9893: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9894: #
1.481     raeburn  9895: sub getuploaded {
                   9896:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9897:     $uri=~s/^\///;
1.980     raeburn  9898:     my $homeserver = &homeserver($cnum,$cdom);
                   9899:     my $protocol = $protocol{$homeserver};
                   9900:     $protocol = 'http' if ($protocol ne 'https');
                   9901:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9902:     my $ua=new LWP::UserAgent;
                   9903:     my $request=new HTTP::Request($reqtype,$uri);
                   9904:     my $response=$ua->request($request);
                   9905:     $$rtncode = $response->code;
1.482     albertel 9906:     if (! $response->is_success()) {
                   9907: 	return 'failed';
                   9908:     }      
                   9909:     if ($reqtype eq 'HEAD') {
1.486     www      9910: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9911:     } elsif ($reqtype eq 'GET') {
                   9912: 	$$info = $response->content;
1.472     albertel 9913:     }
1.482     albertel 9914:     return 'ok';
1.36      albertel 9915: }
                   9916: 
1.481     raeburn  9917: sub readfile {
                   9918:     my $file = shift;
                   9919:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9920:     my $fh;
                   9921:     open($fh,"<$file");
                   9922:     my $a='';
1.800     albertel 9923:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9924:     return $a;
                   9925: }
                   9926: 
1.36      albertel 9927: sub filelocation {
1.590     banghart 9928:     my ($dir,$file) = @_;
                   9929:     my $location;
                   9930:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9931: 
                   9932:     if ($file =~ m-^/adm/-) {
                   9933: 	$file=~s-^/adm/wrapper/-/-;
                   9934: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9935:     }
1.882     albertel 9936: 
1.590     banghart 9937:     if ($file=~m:^/~:) { # is a contruction space reference
                   9938:         $location = $file;
                   9939:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9940:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9941: 	# is a correct contruction space reference
                   9942:         $location = $file;
1.956     raeburn  9943:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9944:         $location = $file;
1.609     banghart 9945:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9946:         my ($udom,$uname,$filename)=
1.811     albertel 9947:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9948:         my $home=&homeserver($uname,$udom);
                   9949:         my $is_me=0;
                   9950:         my @ids=&current_machine_ids();
                   9951:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9952:         if ($is_me) {
1.1117    foxr     9953:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9954:         } else {
                   9955:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9956:   	      $udom.'/'.$uname.'/'.$filename;
                   9957:         }
1.882     albertel 9958:     } elsif ($file =~ m-^/adm/-) {
                   9959: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9960:     } else {
                   9961:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9962:         $file=~s:^/res/:/:;
                   9963:         if ( !( $file =~ m:^/:) ) {
                   9964:             $location = $dir. '/'.$file;
                   9965:         } else {
                   9966:             $location = '/home/httpd/html/res'.$file;
                   9967:         }
1.59      albertel 9968:     }
1.590     banghart 9969:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9970:     while ($location=~m{/\.\./}) {
                   9971: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9972: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9973: 	} else {
                   9974: 	    $location=~ s{/\.\./}{/}g;
                   9975: 	}
                   9976:     } #remove dir/..
1.590     banghart 9977:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9978:     return $location;
1.46      www      9979: }
1.36      albertel 9980: 
1.46      www      9981: sub hreflocation {
                   9982:     my ($dir,$file)=@_;
1.980     raeburn  9983:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9984: 	$file=filelocation($dir,$file);
1.700     albertel 9985:     } elsif ($file=~m-^/adm/-) {
                   9986: 	$file=~s-^/adm/wrapper/-/-;
                   9987: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9988:     }
                   9989:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9990: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9991:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9992: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9993:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9994: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9995: 	    -/uploaded/$1/$2/-x;
1.46      www      9996:     }
1.913     albertel 9997:     if ($file=~ m{^/userfiles/}) {
                   9998: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9999:     }
1.462     albertel 10000:     return $file;
1.465     albertel 10001: }
                   10002: 
                   10003: sub current_machine_domains {
1.853     albertel 10004:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10005: }
                   10006: 
                   10007: sub machine_domains {
                   10008:     my ($hostname) = @_;
1.465     albertel 10009:     my @domains;
1.838     albertel 10010:     my %hostname = &all_hostnames();
1.465     albertel 10011:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10012: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10013: 	if ($hostname eq $name) {
1.844     albertel 10014: 	    push(@domains,&host_domain($id));
1.465     albertel 10015: 	}
                   10016:     }
                   10017:     return @domains;
                   10018: }
                   10019: 
                   10020: sub current_machine_ids {
1.853     albertel 10021:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10022: }
                   10023: 
                   10024: sub machine_ids {
                   10025:     my ($hostname) = @_;
                   10026:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10027:     my @ids;
1.888     albertel 10028:     my %name_to_host = &all_names();
1.889     albertel 10029:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10030: 	return @{ $name_to_host{$hostname} };
                   10031:     }
                   10032:     return;
1.31      www      10033: }
                   10034: 
1.824     raeburn  10035: sub additional_machine_domains {
                   10036:     my @domains;
                   10037:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10038:     while( my $line = <$fh>) {
                   10039:         $line =~ s/\s//g;
                   10040:         push(@domains,$line);
                   10041:     }
                   10042:     return @domains;
                   10043: }
                   10044: 
                   10045: sub default_login_domain {
                   10046:     my $domain = $perlvar{'lonDefDomain'};
                   10047:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10048:     foreach my $posdom (&current_machine_domains(),
                   10049:                         &additional_machine_domains()) {
                   10050:         if (lc($posdom) eq lc($testdomain)) {
                   10051:             $domain=$posdom;
                   10052:             last;
                   10053:         }
                   10054:     }
                   10055:     return $domain;
                   10056: }
                   10057: 
1.31      www      10058: # ------------------------------------------------------------- Declutters URLs
                   10059: 
                   10060: sub declutter {
                   10061:     my $thisfn=shift;
1.569     albertel 10062:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10063:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10064:     $thisfn=~s/^\///;
1.697     albertel 10065:     $thisfn=~s|^adm/wrapper/||;
                   10066:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10067:     $thisfn=~s/^res\///;
1.1032    raeburn  10068:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10069:         $thisfn=~s/\?.+$//;
                   10070:     }
1.268     www      10071:     return $thisfn;
                   10072: }
                   10073: 
                   10074: # ------------------------------------------------------------- Clutter up URLs
                   10075: 
                   10076: sub clutter {
                   10077:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10078:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10079: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10080:        $thisfn='/res'.$thisfn; 
                   10081:     }
1.1031    raeburn  10082:     if ($thisfn !~m|^/adm|) {
                   10083: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10084: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10085: 	} else {
                   10086: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10087: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10088: 	    if ($embstyle eq 'ssi'
                   10089: 		|| ($embstyle eq 'hdn')
                   10090: 		|| ($embstyle eq 'rat')
                   10091: 		|| ($embstyle eq 'prv')
                   10092: 		|| ($embstyle eq 'ign')) {
                   10093: 		#do nothing with these
                   10094: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10095: 		|| ($embstyle eq 'emb')
                   10096: 		|| ($embstyle eq 'wrp')) {
                   10097: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10098: 	    } elsif ($embstyle eq 'unk'
                   10099: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10100: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10101: 	    } else {
1.718     www      10102: #		&logthis("Got a blank emb style");
1.695     albertel 10103: 	    }
1.694     albertel 10104: 	}
                   10105:     }
1.31      www      10106:     return $thisfn;
1.12      www      10107: }
                   10108: 
1.787     albertel 10109: sub clutter_with_no_wrapper {
                   10110:     my $uri = &clutter(shift);
                   10111:     if ($uri =~ m-^/adm/-) {
                   10112: 	$uri =~ s-^/adm/wrapper/-/-;
                   10113: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10114:     }
                   10115:     return $uri;
                   10116: }
                   10117: 
1.557     albertel 10118: sub freeze_escape {
                   10119:     my ($value)=@_;
                   10120:     if (ref($value)) {
                   10121: 	$value=&nfreeze($value);
                   10122: 	return '__FROZEN__'.&escape($value);
                   10123:     }
                   10124:     return &escape($value);
                   10125: }
                   10126: 
1.11      www      10127: 
1.557     albertel 10128: sub thaw_unescape {
                   10129:     my ($value)=@_;
                   10130:     if ($value =~ /^__FROZEN__/) {
                   10131: 	substr($value,0,10,undef);
                   10132: 	$value=&unescape($value);
                   10133: 	return &thaw($value);
                   10134:     }
                   10135:     return &unescape($value);
                   10136: }
                   10137: 
1.436     albertel 10138: sub correct_line_ends {
                   10139:     my ($result)=@_;
                   10140:     $$result =~s/\r\n/\n/mg;
                   10141:     $$result =~s/\r/\n/mg;
1.415     albertel 10142: }
1.1       albertel 10143: # ================================================================ Main Program
                   10144: 
1.184     www      10145: sub goodbye {
1.204     albertel 10146:    &logthis("Starting Shut down");
1.443     albertel 10147: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10148:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10149: #converted
1.599     albertel 10150: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10151:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10152: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10153: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10154: #1.1 only
1.870     albertel 10155: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10156: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10157: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10158: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10159:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10160:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10161:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10162:    &flushcourselogs();
                   10163:    &logthis("Shutting down");
                   10164: }
                   10165: 
1.852     albertel 10166: sub get_dns {
1.869     albertel 10167:     my ($url,$func,$ignore_cache) = @_;
                   10168:     if (!$ignore_cache) {
                   10169: 	my ($content,$cached)=
                   10170: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10171: 	if ($cached) {
                   10172: 	    &$func($content);
                   10173: 	    return;
                   10174: 	}
                   10175:     }
                   10176: 
                   10177:     my %alldns;
1.852     albertel 10178:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10179:     foreach my $dns (<$config>) {
                   10180: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10181:         my $line = $1;
                   10182:         my ($host,$protocol) = split(/:/,$line);
                   10183:         if ($protocol ne 'https') {
                   10184:             $protocol = 'http';
                   10185:         }
                   10186: 	$alldns{$host} = $protocol;
1.869     albertel 10187:     }
                   10188:     while (%alldns) {
                   10189: 	my ($dns) = keys(%alldns);
1.852     albertel 10190: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10191: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10192: 	my $response=$ua->request($request);
1.979     raeburn  10193:         delete($alldns{$dns});
1.852     albertel 10194: 	next if ($response->is_error());
                   10195: 	my @content = split("\n",$response->content);
1.869     albertel 10196: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10197: 	&$func(\@content);
1.869     albertel 10198: 	return;
1.852     albertel 10199:     }
                   10200:     close($config);
1.871     albertel 10201:     my $which = (split('/',$url))[3];
                   10202:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10203:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10204:     my @content = <$config>;
                   10205:     &$func(\@content);
                   10206:     return;
1.852     albertel 10207: }
1.327     albertel 10208: # ------------------------------------------------------------ Read domain file
                   10209: {
1.852     albertel 10210:     my $loaded;
1.846     albertel 10211:     my %domain;
                   10212: 
1.852     albertel 10213:     sub parse_domain_tab {
                   10214: 	my ($lines) = @_;
                   10215: 	foreach my $line (@$lines) {
                   10216: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10217: 
1.846     albertel 10218: 	    chomp($line);
1.852     albertel 10219: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10220: 	    my %this_domain;
                   10221: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10222: 			       'lang_def', 'city', 'longi', 'lati',
                   10223: 			       'primary') {
                   10224: 		$this_domain{$field} = shift(@elements);
                   10225: 	    }
                   10226: 	    $domain{$name} = \%this_domain;
1.852     albertel 10227: 	}
                   10228:     }
1.864     albertel 10229: 
                   10230:     sub reset_domain_info {
                   10231: 	undef($loaded);
                   10232: 	undef(%domain);
                   10233:     }
                   10234: 
1.852     albertel 10235:     sub load_domain_tab {
1.869     albertel 10236: 	my ($ignore_cache) = @_;
                   10237: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10238: 	my $fh;
                   10239: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10240: 	    my @lines = <$fh>;
                   10241: 	    &parse_domain_tab(\@lines);
1.448     albertel 10242: 	}
1.852     albertel 10243: 	close($fh);
                   10244: 	$loaded = 1;
1.327     albertel 10245:     }
1.846     albertel 10246: 
                   10247:     sub domain {
1.852     albertel 10248: 	&load_domain_tab() if (!$loaded);
                   10249: 
1.846     albertel 10250: 	my ($name,$what) = @_;
                   10251: 	return if ( !exists($domain{$name}) );
                   10252: 
                   10253: 	if (!$what) {
                   10254: 	    return $domain{$name}{'description'};
                   10255: 	}
                   10256: 	return $domain{$name}{$what};
                   10257:     }
1.974     raeburn  10258: 
                   10259:     sub domain_info {
                   10260:         &load_domain_tab() if (!$loaded);
                   10261:         return %domain;
                   10262:     }
                   10263: 
1.327     albertel 10264: }
                   10265: 
                   10266: 
1.1       albertel 10267: # ------------------------------------------------------------- Read hosts file
                   10268: {
1.838     albertel 10269:     my %hostname;
1.844     albertel 10270:     my %hostdom;
1.845     albertel 10271:     my %libserv;
1.852     albertel 10272:     my $loaded;
1.888     albertel 10273:     my %name_to_host;
1.1074    raeburn  10274:     my %internetdom;
1.1107    raeburn  10275:     my %LC_dns_serv;
1.852     albertel 10276: 
                   10277:     sub parse_hosts_tab {
                   10278: 	my ($file) = @_;
                   10279: 	foreach my $configline (@$file) {
                   10280: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10281:             chomp($configline);
                   10282: 	    if ($configline =~ /^\^/) {
                   10283:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10284:                     $LC_dns_serv{$1} = 1;
                   10285:                 }
                   10286:                 next;
                   10287:             }
1.1074    raeburn  10288: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10289: 	    $name=~s/\s//g;
                   10290: 	    if ($id && $domain && $role && $name) {
                   10291: 		$hostname{$id}=$name;
1.888     albertel 10292: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10293: 		$hostdom{$id}=$domain;
                   10294: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10295:                 if (defined($protocol)) {
                   10296:                     if ($protocol eq 'https') {
                   10297:                         $protocol{$id} = $protocol;
                   10298:                     } else {
                   10299:                         $protocol{$id} = 'http'; 
                   10300:                     }
1.968     raeburn  10301:                 } else {
1.969     raeburn  10302:                     $protocol{$id} = 'http';
1.968     raeburn  10303:                 }
1.1074    raeburn  10304:                 if (defined($intdom)) {
                   10305:                     $internetdom{$id} = $intdom;
                   10306:                 }
1.852     albertel 10307: 	    }
                   10308: 	}
                   10309:     }
1.864     albertel 10310:     
                   10311:     sub reset_hosts_info {
1.897     albertel 10312: 	&purge_remembered();
1.864     albertel 10313: 	&reset_domain_info();
                   10314: 	&reset_hosts_ip_info();
1.892     albertel 10315: 	undef(%name_to_host);
1.864     albertel 10316: 	undef(%hostname);
                   10317: 	undef(%hostdom);
                   10318: 	undef(%libserv);
                   10319: 	undef($loaded);
                   10320:     }
1.1       albertel 10321: 
1.852     albertel 10322:     sub load_hosts_tab {
1.869     albertel 10323: 	my ($ignore_cache) = @_;
                   10324: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10325: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10326: 	my @config = <$config>;
                   10327: 	&parse_hosts_tab(\@config);
                   10328: 	close($config);
                   10329: 	$loaded=1;
1.1       albertel 10330:     }
1.852     albertel 10331: 
1.838     albertel 10332:     sub hostname {
1.852     albertel 10333: 	&load_hosts_tab() if (!$loaded);
                   10334: 
1.838     albertel 10335: 	my ($lonid) = @_;
                   10336: 	return $hostname{$lonid};
                   10337:     }
1.845     albertel 10338: 
1.838     albertel 10339:     sub all_hostnames {
1.852     albertel 10340: 	&load_hosts_tab() if (!$loaded);
                   10341: 
1.838     albertel 10342: 	return %hostname;
                   10343:     }
1.845     albertel 10344: 
1.888     albertel 10345:     sub all_names {
                   10346: 	&load_hosts_tab() if (!$loaded);
                   10347: 
                   10348: 	return %name_to_host;
                   10349:     }
                   10350: 
1.974     raeburn  10351:     sub all_host_domain {
                   10352:         &load_hosts_tab() if (!$loaded);
                   10353:         return %hostdom;
                   10354:     }
                   10355: 
1.845     albertel 10356:     sub is_library {
1.852     albertel 10357: 	&load_hosts_tab() if (!$loaded);
                   10358: 
1.845     albertel 10359: 	return exists($libserv{$_[0]});
                   10360:     }
                   10361: 
                   10362:     sub all_library {
1.852     albertel 10363: 	&load_hosts_tab() if (!$loaded);
                   10364: 
1.845     albertel 10365: 	return %libserv;
                   10366:     }
                   10367: 
1.1062    droeschl 10368:     sub unique_library {
                   10369: 	#2x reverse removes all hostnames that appear more than once
                   10370:         my %unique = reverse &all_library();
                   10371:         return reverse %unique;
                   10372:     }
                   10373: 
1.841     albertel 10374:     sub get_servers {
1.852     albertel 10375: 	&load_hosts_tab() if (!$loaded);
                   10376: 
1.841     albertel 10377: 	my ($domain,$type) = @_;
                   10378: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10379: 	                                          : %hostname;
                   10380: 	my %result;
1.842     albertel 10381: 	if (ref($domain) eq 'ARRAY') {
                   10382: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10383: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10384: 		    $result{$host} = $hostname;
                   10385: 		}
                   10386: 	    }
                   10387: 	} else {
                   10388: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10389: 		if ($hostdom{$host} eq $domain) {
                   10390: 		    $result{$host} = $hostname;
                   10391: 		}
1.841     albertel 10392: 	    }
                   10393: 	}
                   10394: 	return %result;
                   10395:     }
1.845     albertel 10396: 
1.1062    droeschl 10397:     sub get_unique_servers {
                   10398:         my %unique = reverse &get_servers(@_);
                   10399: 	return reverse %unique;
                   10400:     }
                   10401: 
1.844     albertel 10402:     sub host_domain {
1.852     albertel 10403: 	&load_hosts_tab() if (!$loaded);
                   10404: 
1.844     albertel 10405: 	my ($lonid) = @_;
                   10406: 	return $hostdom{$lonid};
                   10407:     }
                   10408: 
1.841     albertel 10409:     sub all_domains {
1.852     albertel 10410: 	&load_hosts_tab() if (!$loaded);
                   10411: 
1.841     albertel 10412: 	my %seen;
                   10413: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10414: 	return @uniq;
                   10415:     }
1.1074    raeburn  10416: 
                   10417:     sub internet_dom {
                   10418:         &load_hosts_tab() if (!$loaded);
                   10419: 
                   10420:         my ($lonid) = @_;
                   10421:         return $internetdom{$lonid};
                   10422:     }
1.1107    raeburn  10423: 
                   10424:     sub is_LC_dns {
                   10425:         &load_hosts_tab() if (!$loaded);
                   10426: 
                   10427:         my ($hostname) = @_;
                   10428:         return exists($LC_dns_serv{$hostname});
                   10429:     }
                   10430: 
1.1       albertel 10431: }
                   10432: 
1.847     albertel 10433: { 
                   10434:     my %iphost;
1.856     albertel 10435:     my %name_to_ip;
                   10436:     my %lonid_to_ip;
1.869     albertel 10437: 
1.847     albertel 10438:     sub get_hosts_from_ip {
                   10439: 	my ($ip) = @_;
                   10440: 	my %iphosts = &get_iphost();
                   10441: 	if (ref($iphosts{$ip})) {
                   10442: 	    return @{$iphosts{$ip}};
                   10443: 	}
                   10444: 	return;
1.839     albertel 10445:     }
1.864     albertel 10446:     
                   10447:     sub reset_hosts_ip_info {
                   10448: 	undef(%iphost);
                   10449: 	undef(%name_to_ip);
                   10450: 	undef(%lonid_to_ip);
                   10451:     }
1.856     albertel 10452: 
                   10453:     sub get_host_ip {
                   10454: 	my ($lonid) = @_;
                   10455: 	if (exists($lonid_to_ip{$lonid})) {
                   10456: 	    return $lonid_to_ip{$lonid};
                   10457: 	}
                   10458: 	my $name=&hostname($lonid);
                   10459:    	my $ip = gethostbyname($name);
                   10460: 	return if (!$ip || length($ip) ne 4);
                   10461: 	$ip=inet_ntoa($ip);
                   10462: 	$name_to_ip{$name}   = $ip;
                   10463: 	$lonid_to_ip{$lonid} = $ip;
                   10464: 	return $ip;
                   10465:     }
1.847     albertel 10466:     
                   10467:     sub get_iphost {
1.869     albertel 10468: 	my ($ignore_cache) = @_;
1.894     albertel 10469: 
1.869     albertel 10470: 	if (!$ignore_cache) {
                   10471: 	    if (%iphost) {
                   10472: 		return %iphost;
                   10473: 	    }
                   10474: 	    my ($ip_info,$cached)=
                   10475: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10476: 	    if ($cached) {
                   10477: 		%iphost      = %{$ip_info->[0]};
                   10478: 		%name_to_ip  = %{$ip_info->[1]};
                   10479: 		%lonid_to_ip = %{$ip_info->[2]};
                   10480: 		return %iphost;
                   10481: 	    }
                   10482: 	}
1.894     albertel 10483: 
                   10484: 	# get yesterday's info for fallback
                   10485: 	my %old_name_to_ip;
                   10486: 	my ($ip_info,$cached)=
                   10487: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10488: 	if ($cached) {
                   10489: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10490: 	}
                   10491: 
1.888     albertel 10492: 	my %name_to_host = &all_names();
                   10493: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10494: 	    my $ip;
                   10495: 	    if (!exists($name_to_ip{$name})) {
                   10496: 		$ip = gethostbyname($name);
                   10497: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10498: 		    if (defined($old_name_to_ip{$name})) {
                   10499: 			$ip = $old_name_to_ip{$name};
                   10500: 			&logthis("Can't find $name defaulting to old $ip");
                   10501: 		    } else {
                   10502: 			&logthis("Name $name no IP found");
                   10503: 			next;
                   10504: 		    }
                   10505: 		} else {
                   10506: 		    $ip=inet_ntoa($ip);
1.847     albertel 10507: 		}
                   10508: 		$name_to_ip{$name} = $ip;
                   10509: 	    } else {
                   10510: 		$ip = $name_to_ip{$name};
1.653     albertel 10511: 	    }
1.888     albertel 10512: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10513: 		$lonid_to_ip{$id} = $ip;
                   10514: 	    }
                   10515: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10516: 	}
1.869     albertel 10517: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10518: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10519: 				      48*60*60);
1.869     albertel 10520: 
1.847     albertel 10521: 	return %iphost;
1.598     albertel 10522:     }
                   10523: 
1.992     raeburn  10524:     #
                   10525:     #  Given a DNS returns the loncapa host name for that DNS 
                   10526:     # 
                   10527:     sub host_from_dns {
                   10528:         my ($dns) = @_;
                   10529:         my @hosts;
                   10530:         my $ip;
                   10531: 
1.993     raeburn  10532:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10533:             $ip = $name_to_ip{$dns};
                   10534:         }
                   10535:         if (!$ip) {
                   10536:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10537:             if (length($ip) == 4) { 
                   10538: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10539:             }
                   10540:         }
                   10541:         if ($ip) {
                   10542: 	    @hosts = get_hosts_from_ip($ip);
                   10543: 	    return $hosts[0];
                   10544:         }
                   10545:         return undef;
1.986     foxr     10546:     }
1.992     raeburn  10547: 
1.1074    raeburn  10548:     sub get_internet_names {
                   10549:         my ($lonid) = @_;
                   10550:         return if ($lonid eq '');
                   10551:         my ($idnref,$cached)=
                   10552:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10553:         if ($cached) {
                   10554:             return $idnref;
                   10555:         }
                   10556:         my $ip = &get_host_ip($lonid);
                   10557:         my @hosts = &get_hosts_from_ip($ip);
                   10558:         my %iphost = &get_iphost();
                   10559:         my (@idns,%seen);
                   10560:         foreach my $id (@hosts) {
                   10561:             my $dom = &host_domain($id);
                   10562:             my $prim_id = &domain($dom,'primary');
                   10563:             my $prim_ip = &get_host_ip($prim_id);
                   10564:             next if ($seen{$prim_ip});
                   10565:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10566:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10567:                     my $intdom = &internet_dom($id);
                   10568:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10569:                         push(@idns,$intdom);
                   10570:                     }
                   10571:                 }
                   10572:             }
                   10573:             $seen{$prim_ip} = 1;
                   10574:         }
                   10575:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10576:     }
                   10577: 
1.986     foxr     10578: }
                   10579: 
1.1079    raeburn  10580: sub all_loncaparevs {
                   10581:     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);
                   10582: }
                   10583: 
1.862     albertel 10584: BEGIN {
                   10585: 
                   10586: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10587:     unless ($readit) {
                   10588: {
                   10589:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10590:     %perlvar = (%perlvar,%{$configvars});
                   10591: }
                   10592: 
                   10593: 
1.1       albertel 10594: # ------------------------------------------------------ Read spare server file
                   10595: {
1.448     albertel 10596:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10597: 
                   10598:     while (my $configline=<$config>) {
                   10599:        chomp($configline);
1.284     matthew  10600:        if ($configline) {
1.784     albertel 10601: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10602: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10603: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10604:        }
                   10605:     }
1.448     albertel 10606:     close($config);
1.1       albertel 10607: }
1.11      www      10608: # ------------------------------------------------------------ Read permissions
                   10609: {
1.448     albertel 10610:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10611: 
                   10612:     while (my $configline=<$config>) {
1.448     albertel 10613: 	chomp($configline);
                   10614: 	if ($configline) {
                   10615: 	    my ($role,$perm)=split(/ /,$configline);
                   10616: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10617: 	}
1.11      www      10618:     }
1.448     albertel 10619:     close($config);
1.11      www      10620: }
                   10621: 
                   10622: # -------------------------------------------- Read plain texts for permissions
                   10623: {
1.448     albertel 10624:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10625: 
                   10626:     while (my $configline=<$config>) {
1.448     albertel 10627: 	chomp($configline);
                   10628: 	if ($configline) {
1.742     raeburn  10629: 	    my ($short,@plain)=split(/:/,$configline);
                   10630:             %{$prp{$short}} = ();
                   10631: 	    if (@plain > 0) {
                   10632:                 $prp{$short}{'std'} = $plain[0];
                   10633:                 for (my $i=1; $i<@plain; $i++) {
                   10634:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10635:                 }
                   10636:             }
1.448     albertel 10637: 	}
1.135     www      10638:     }
1.448     albertel 10639:     close($config);
1.135     www      10640: }
                   10641: 
                   10642: # ---------------------------------------------------------- Read package table
                   10643: {
1.448     albertel 10644:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10645: 
                   10646:     while (my $configline=<$config>) {
1.483     albertel 10647: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10648: 	chomp($configline);
                   10649: 	my ($short,$plain)=split(/:/,$configline);
                   10650: 	my ($pack,$name)=split(/\&/,$short);
                   10651: 	if ($plain ne '') {
                   10652: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10653: 	    $packagetab{$short}=$plain; 
                   10654: 	}
1.11      www      10655:     }
1.448     albertel 10656:     close($config);
1.329     matthew  10657: }
                   10658: 
1.1073    raeburn  10659: # ---------------------------------------------------------- Read loncaparev table
                   10660: {
                   10661:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10662:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10663:             while (my $configline=<$config>) {
                   10664:                 chomp($configline);
                   10665:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10666:                 $loncaparevs{$hostid}=$loncaparev;
                   10667:             }
                   10668:             close($config);
                   10669:         }
                   10670:     }
                   10671: }
                   10672: 
1.1074    raeburn  10673: # ---------------------------------------------------------- Read serverhostID table
                   10674: {
                   10675:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10676:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10677:             while (my $configline=<$config>) {
                   10678:                 chomp($configline);
                   10679:                 my ($name,$id)=split(/:/,$configline);
                   10680:                 $serverhomeIDs{$name}=$id;
                   10681:             }
                   10682:             close($config);
                   10683:         }
                   10684:     }
                   10685: }
                   10686: 
1.1079    raeburn  10687: {
                   10688:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10689:     if (-e $file) {
                   10690:         my $parser = HTML::LCParser->new($file);
                   10691:         while (my $token = $parser->get_token()) {
                   10692:             if ($token->[0] eq 'S') {
                   10693:                 my $item = $token->[1];
                   10694:                 my $name = $token->[2]{'name'};
                   10695:                 my $value = $token->[2]{'value'};
                   10696:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10697:                     my $release = $parser->get_text();
                   10698:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10699:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10700:                 }
                   10701:             }
                   10702:         }
                   10703:     }
1.1073    raeburn  10704: }
                   10705: 
1.329     matthew  10706: # ------------- set up temporary directory
                   10707: {
1.1117    foxr     10708:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10709: 
1.11      www      10710: }
                   10711: 
1.794     albertel 10712: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10713: 				'compress_threshold'=> 20_000,
                   10714:  			        });
1.185     www      10715: 
1.281     www      10716: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10717: $dumpcount=0;
1.958     www      10718: $locknum=0;
1.22      www      10719: 
1.163     harris41 10720: &logtouch();
1.672     albertel 10721: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10722: $readit=1;
1.564     albertel 10723:     {
                   10724: 	use integer;
                   10725: 	my $test=(2**32)+1;
1.568     albertel 10726: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10727: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10728:     }
1.195     www      10729: }
1.1       albertel 10730: }
1.179     www      10731: 
1.1       albertel 10732: 1;
1.191     harris41 10733: __END__
                   10734: 
1.243     albertel 10735: =pod
                   10736: 
1.191     harris41 10737: =head1 NAME
                   10738: 
1.243     albertel 10739: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10740: 
                   10741: =head1 SYNOPSIS
                   10742: 
1.243     albertel 10743: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10744: 
                   10745:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10746: 
1.243     albertel 10747: Common parameters:
                   10748: 
                   10749: =over 4
                   10750: 
                   10751: =item *
                   10752: 
                   10753: $uname : an internal username (if $cname expecting a course Id specifically)
                   10754: 
                   10755: =item *
                   10756: 
                   10757: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10758: 
                   10759: =item *
                   10760: 
                   10761: $symb : a resource instance identifier
                   10762: 
                   10763: =item *
                   10764: 
                   10765: $namespace : the name of a .db file that contains the data needed or
                   10766: being set.
                   10767: 
                   10768: =back
                   10769: 
1.394     bowersj2 10770: =head1 OVERVIEW
1.191     harris41 10771: 
1.394     bowersj2 10772: lonnet provides subroutines which interact with the
                   10773: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10774: about classes, users, and resources.
1.243     albertel 10775: 
                   10776: For many of these objects you can also use this to store data about
                   10777: them or modify them in various ways.
1.191     harris41 10778: 
1.394     bowersj2 10779: =head2 Symbs
1.191     harris41 10780: 
1.394     bowersj2 10781: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10782: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10783: map, the resource number of the resource in the map, and the URL of
                   10784: the resource itself. The latter is somewhat redundant, but might help
                   10785: if maps change.
                   10786: 
                   10787: An example is
                   10788: 
                   10789:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10790: 
                   10791: The respective map entry is
                   10792: 
                   10793:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10794:   title="Problem 2">
                   10795:  </resource>
                   10796: 
                   10797: Symbs are used by the random number generator, as well as to store and
                   10798: restore data specific to a certain instance of for example a problem.
                   10799: 
                   10800: =head2 Storing And Retrieving Data
                   10801: 
                   10802: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10803: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10804: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10805: is is the non-critical message twin of cstore. These functions are for
                   10806: handlers to store a perl hash to a user's permanent data space in an
                   10807: easy manner, and to retrieve it again on another call. It is expected
                   10808: that a handler would use this once at the beginning to retrieve data,
                   10809: and then again once at the end to send only the new data back.
                   10810: 
                   10811: The data is stored in the user's data directory on the user's
                   10812: homeserver under the ID of the course.
                   10813: 
                   10814: The hash that is returned by restore will have all of the previous
                   10815: value for all of the elements of the hash.
                   10816: 
                   10817: Example:
                   10818: 
                   10819:  #creating a hash
                   10820:  my %hash;
                   10821:  $hash{'foo'}='bar';
                   10822: 
                   10823:  #storing it
                   10824:  &Apache::lonnet::cstore(\%hash);
                   10825: 
                   10826:  #changing a value
                   10827:  $hash{'foo'}='notbar';
                   10828: 
                   10829:  #adding a new value
                   10830:  $hash{'bar'}='foo';
                   10831:  &Apache::lonnet::cstore(\%hash);
                   10832: 
                   10833:  #retrieving the hash
                   10834:  my %history=&Apache::lonnet::restore();
                   10835: 
                   10836:  #print the hash
                   10837:  foreach my $key (sort(keys(%history))) {
                   10838:    print("\%history{$key} = $history{$key}");
                   10839:  }
                   10840: 
                   10841: Will print out:
1.191     harris41 10842: 
1.394     bowersj2 10843:  %history{1:foo} = bar
                   10844:  %history{1:keys} = foo:timestamp
                   10845:  %history{1:timestamp} = 990455579
                   10846:  %history{2:bar} = foo
                   10847:  %history{2:foo} = notbar
                   10848:  %history{2:keys} = foo:bar:timestamp
                   10849:  %history{2:timestamp} = 990455580
                   10850:  %history{bar} = foo
                   10851:  %history{foo} = notbar
                   10852:  %history{timestamp} = 990455580
                   10853:  %history{version} = 2
                   10854: 
                   10855: Note that the special hash entries C<keys>, C<version> and
                   10856: C<timestamp> were added to the hash. C<version> will be equal to the
                   10857: total number of versions of the data that have been stored. The
                   10858: C<timestamp> attribute will be the UNIX time the hash was
                   10859: stored. C<keys> is available in every historical section to list which
                   10860: keys were added or changed at a specific historical revision of a
                   10861: hash.
                   10862: 
                   10863: B<Warning>: do not store the hash that restore returns directly. This
                   10864: will cause a mess since it will restore the historical keys as if the
                   10865: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10866: 
1.394     bowersj2 10867: Calling convention:
1.191     harris41 10868: 
1.394     bowersj2 10869:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10870:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10871: 
1.394     bowersj2 10872: For more detailed information, see lonnet specific documentation.
1.191     harris41 10873: 
1.394     bowersj2 10874: =head1 RETURN MESSAGES
1.191     harris41 10875: 
1.394     bowersj2 10876: =over 4
1.191     harris41 10877: 
1.394     bowersj2 10878: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10879: 
1.394     bowersj2 10880: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10881: when the connection is brought back up
1.191     harris41 10882: 
1.394     bowersj2 10883: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10884: for later delivery
1.191     harris41 10885: 
1.967     bisitz   10886: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10887: 
1.394     bowersj2 10888: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10889: that was requested
1.191     harris41 10890: 
1.243     albertel 10891: =back
1.191     harris41 10892: 
1.243     albertel 10893: =head1 PUBLIC SUBROUTINES
1.191     harris41 10894: 
1.243     albertel 10895: =head2 Session Environment Functions
1.191     harris41 10896: 
1.243     albertel 10897: =over 4
1.191     harris41 10898: 
1.394     bowersj2 10899: =item * 
                   10900: X<appenv()>
1.949     raeburn  10901: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10902: the user envirnoment file, and will be restored for each access this
1.620     albertel 10903: user makes during this session, also modifies the %env for the current
1.949     raeburn  10904: process. Optional rolesarrayref - if defined contains a reference to an array
                   10905: of roles which are exempt from the restriction on modifying user.role entries 
                   10906: in the user's environment.db and in %env.    
1.191     harris41 10907: 
                   10908: =item *
1.394     bowersj2 10909: X<delenv()>
1.987     raeburn  10910: B<delenv($delthis,$regexp)>: removes all items from the session
                   10911: environment file that begin with $delthis. If the 
                   10912: optional second arg - $regexp - is true, $delthis is treated as a 
                   10913: regular expression, otherwise \Q$delthis\E is used. 
                   10914: The values are also deleted from the current processes %env.
1.191     harris41 10915: 
1.795     albertel 10916: =item * get_env_multiple($name) 
                   10917: 
                   10918: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10919: values may be defined and end up as an array ref.
                   10920: 
                   10921: returns an array of values
                   10922: 
1.243     albertel 10923: =back
                   10924: 
                   10925: =head2 User Information
1.191     harris41 10926: 
1.243     albertel 10927: =over 4
1.191     harris41 10928: 
                   10929: =item *
1.394     bowersj2 10930: X<queryauthenticate()>
                   10931: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10932: authentication scheme
                   10933: 
                   10934: =item *
1.394     bowersj2 10935: X<authenticate()>
1.1073    raeburn  10936: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10937: authenticate user from domain's lib servers (first use the current
                   10938: one). C<$upass> should be the users password.
1.1073    raeburn  10939: $checkdefauth is optional (value is 1 if a check should be made to
                   10940:    authenticate user using default authentication method, and allow
                   10941:    account creation if username does not have account in the domain).
                   10942: $clientcancheckhost is optional (value is 1 if checking whether the
                   10943:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10944: 
                   10945: =item *
1.394     bowersj2 10946: X<homeserver()>
                   10947: B<homeserver($uname,$udom)>: find the server which has
                   10948: the user's directory and files (there must be only one), this caches
                   10949: the answer, and also caches if there is a borken connection.
1.191     harris41 10950: 
                   10951: =item *
1.394     bowersj2 10952: X<idget()>
                   10953: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10954: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10955: username, and only 1 username per ID in a specific domain) (returns
                   10956: hash: id=>name,id=>name)
1.191     harris41 10957: 
                   10958: =item *
1.394     bowersj2 10959: X<idrget()>
                   10960: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10961: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10962: 
                   10963: =item *
1.394     bowersj2 10964: X<idput()>
                   10965: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10966: 
                   10967: =item *
1.394     bowersj2 10968: X<rolesinit()>
                   10969: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10970: 
                   10971: =item *
1.551     albertel 10972: X<getsection()>
                   10973: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10974: course $cname, return section name/number or '' for "not in course"
                   10975: and '-1' for "no section"
                   10976: 
                   10977: =item *
1.394     bowersj2 10978: X<userenvironment()>
                   10979: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10980: passed in @what from the requested user's environment, returns a hash
                   10981: 
1.858     raeburn  10982: =item * 
                   10983: X<userlog_query()>
1.859     albertel 10984: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10985: activity.log file. %filters defines filters applied when parsing the
                   10986: log file. These can be start or end timestamps, or the type of action
                   10987: - log to look for Login or Logout events, check for Checkin or
                   10988: Checkout, role for role selection. The response is in the form
                   10989: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10990: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10991: 
1.243     albertel 10992: =back
                   10993: 
                   10994: =head2 User Roles
                   10995: 
                   10996: =over 4
                   10997: 
                   10998: =item *
                   10999: 
1.810     raeburn  11000: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11001:  F: full access
                   11002:  U,I,K: authentication modes (cxx only)
                   11003:  '': forbidden
                   11004:  1: user needs to choose course
                   11005:  2: browse allowed
1.766     albertel 11006:  A: passphrase authentication needed
1.243     albertel 11007: 
                   11008: =item *
                   11009: 
                   11010: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11011: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11012: and course level
                   11013: 
                   11014: =item *
                   11015: 
1.988     raeburn  11016: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11017: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11018: $type is Course (default) or Community.
1.988     raeburn  11019: If $forcedefault evaluates to true, text returned will be default 
                   11020: text for $type. Otherwise, if this is a course, the text returned 
                   11021: will be a custom name for the role (if defined in the course's 
                   11022: environment).  If no custom name is defined the default is returned.
                   11023:    
1.832     raeburn  11024: =item *
                   11025: 
1.935     raeburn  11026: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11027: All arguments are optional. Returns a hash of a roles, either for
                   11028: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11029: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11030: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11031: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11032: For each key, value is set to colon-separated start and end times for
                   11033: the role.  If no username and domain are specified, will default to
1.934     raeburn  11034: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11035: of role statuses (active, future or previous), roles 
                   11036: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11037: to restrict the list of roles reported. If no array ref is 
                   11038: provided for types, will default to return only active roles.
1.834     albertel 11039: 
1.243     albertel 11040: =back
                   11041: 
                   11042: =head2 User Modification
                   11043: 
                   11044: =over 4
                   11045: 
                   11046: =item *
                   11047: 
1.957     raeburn  11048: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11049: user for the level given by URL.  Optional start and end dates (leave empty
                   11050: string or zero for "no date")
1.191     harris41 11051: 
                   11052: =item *
                   11053: 
1.243     albertel 11054: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11055: change a users, password, possible return values are: ok,
                   11056: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11057: refused
1.191     harris41 11058: 
                   11059: =item *
                   11060: 
1.243     albertel 11061: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11062: 
                   11063: =item *
                   11064: 
1.1058    raeburn  11065: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11066:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11067: 
                   11068: will update user information (firstname,middlename,lastname,generation,
                   11069: permanentemail), and if forceid is true, student/employee ID also.
                   11070: A user's institutional affiliation(s) can also be updated.
                   11071: User information fields will not be overwritten with empty entries 
                   11072: unless the field is included in the $candelete array reference.
                   11073: This array is included when a single user is modified via "Manage Users",
                   11074: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11075: 
                   11076: =item *
                   11077: 
1.286     matthew  11078: modifystudent
                   11079: 
1.957     raeburn  11080: modify a student's enrollment and identification information.
1.286     matthew  11081: The course id is resolved based on the current users environment.  
                   11082: This means the envoking user must be a course coordinator or otherwise
                   11083: associated with a course.
                   11084: 
1.297     matthew  11085: This call is essentially a wrapper for lonnet::modifyuser and
                   11086: lonnet::modify_student_enrollment
1.286     matthew  11087: 
                   11088: Inputs: 
                   11089: 
                   11090: =over 4
                   11091: 
1.957     raeburn  11092: =item B<$udom> Student's loncapa domain
1.286     matthew  11093: 
1.957     raeburn  11094: =item B<$uname> Student's loncapa login name
1.286     matthew  11095: 
1.964     bisitz   11096: =item B<$uid> Student/Employee ID
1.286     matthew  11097: 
1.957     raeburn  11098: =item B<$umode> Student's authentication mode
1.286     matthew  11099: 
1.957     raeburn  11100: =item B<$upass> Student's password
1.286     matthew  11101: 
1.957     raeburn  11102: =item B<$first> Student's first name
1.286     matthew  11103: 
1.957     raeburn  11104: =item B<$middle> Student's middle name
1.286     matthew  11105: 
1.957     raeburn  11106: =item B<$last> Student's last name
1.286     matthew  11107: 
1.957     raeburn  11108: =item B<$gene> Student's generation
1.286     matthew  11109: 
1.957     raeburn  11110: =item B<$usec> Student's section in course
1.286     matthew  11111: 
                   11112: =item B<$end> Unix time of the roles expiration
                   11113: 
                   11114: =item B<$start> Unix time of the roles start date
                   11115: 
                   11116: =item B<$forceid> If defined, allow $uid to be changed
                   11117: 
                   11118: =item B<$desiredhome> server to use as home server for student
                   11119: 
1.957     raeburn  11120: =item B<$email> Student's permanent e-mail address
                   11121: 
                   11122: =item B<$type> Type of enrollment (auto or manual)
                   11123: 
1.963     raeburn  11124: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11125: 
                   11126: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11127: 
1.963     raeburn  11128: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11129: 
1.963     raeburn  11130: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11131: 
1.963     raeburn  11132: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11133: 
1.286     matthew  11134: =back
1.297     matthew  11135: 
                   11136: =item *
                   11137: 
                   11138: modify_student_enrollment
                   11139: 
                   11140: Change a students enrollment status in a class.  The environment variable
                   11141: 'role.request.course' must be defined for this function to proceed.
                   11142: 
                   11143: Inputs:
                   11144: 
                   11145: =over 4
                   11146: 
                   11147: =item $udom, students domain
                   11148: 
                   11149: =item $uname, students name
                   11150: 
                   11151: =item $uid, students user id
                   11152: 
                   11153: =item $first, students first name
                   11154: 
                   11155: =item $middle
                   11156: 
                   11157: =item $last
                   11158: 
                   11159: =item $gene
                   11160: 
                   11161: =item $usec
                   11162: 
                   11163: =item $end
                   11164: 
                   11165: =item $start
                   11166: 
1.957     raeburn  11167: =item $type
                   11168: 
                   11169: =item $locktype
                   11170: 
                   11171: =item $cid
                   11172: 
                   11173: =item $selfenroll
                   11174: 
                   11175: =item $context
                   11176: 
1.297     matthew  11177: =back
                   11178: 
1.191     harris41 11179: 
                   11180: =item *
                   11181: 
1.243     albertel 11182: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11183: custom role; give a custom role to a user for the level given by URL.  Specify
                   11184: name and domain of role author, and role name
1.191     harris41 11185: 
                   11186: =item *
                   11187: 
1.243     albertel 11188: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11189: 
                   11190: =item *
                   11191: 
1.243     albertel 11192: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11193: 
                   11194: =back
                   11195: 
                   11196: =head2 Course Infomation
                   11197: 
                   11198: =over 4
1.191     harris41 11199: 
                   11200: =item *
                   11201: 
1.1118    foxr     11202: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11203: specified course id, including all environment settings for the
                   11204: course, the description of the course will be in the hash under the
                   11205: key 'description'
1.191     harris41 11206: 
1.1118    foxr     11207: $options is an optional parameter that if supplied is a hash reference that controls
                   11208: what how this function works.  It has the following key/values:
                   11209: 
                   11210: =over 4
                   11211: 
                   11212: =item freshen_cache
                   11213: 
                   11214: If defined, and the environment cache for the course is valid, it is 
                   11215: returned in the returned hash.
                   11216: 
                   11217: =item one_time
                   11218: 
                   11219: If defined, the last cache time is set to _now_
                   11220: 
                   11221: =item user
                   11222: 
                   11223: If defined, the supplied username is used instead of the current user.
                   11224: 
                   11225: 
                   11226: =back
                   11227: 
1.191     harris41 11228: =item *
                   11229: 
1.624     albertel 11230: resdata($name,$domain,$type,@which) : request for current parameter
                   11231: setting for a specific $type, where $type is either 'course' or 'user',
                   11232: @what should be a list of parameters to ask about. This routine caches
                   11233: answers for 5 minutes.
1.243     albertel 11234: 
1.877     foxr     11235: =item *
                   11236: 
                   11237: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11238: data base, returning a hash that is keyed by the resource name and has
                   11239: values that are the resource value.  I believe that the timestamps and
                   11240: versions are also returned.
                   11241: 
                   11242: 
1.243     albertel 11243: =back
                   11244: 
                   11245: =head2 Course Modification
                   11246: 
                   11247: =over 4
1.191     harris41 11248: 
                   11249: =item *
                   11250: 
1.243     albertel 11251: writecoursepref($courseid,%prefs) : write preferences (environment
                   11252: database) for a course
1.191     harris41 11253: 
                   11254: =item *
                   11255: 
1.1011    raeburn  11256: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11257: 
                   11258: =item *
                   11259: 
1.1038    raeburn  11260: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11261: 
                   11262: =back
                   11263: 
                   11264: =head2 Resource Subroutines
                   11265: 
                   11266: =over 4
1.191     harris41 11267: 
                   11268: =item *
                   11269: 
1.243     albertel 11270: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11271: 
                   11272: =item *
                   11273: 
1.243     albertel 11274: repcopy($filename) : subscribes to the requested file, and attempts to
                   11275: replicate from the owning library server, Might return
1.607     raeburn  11276: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11277: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11278: resource. Expects the local filesystem pathname
                   11279: (/home/httpd/html/res/....)
                   11280: 
                   11281: =back
                   11282: 
                   11283: =head2 Resource Information
                   11284: 
                   11285: =over 4
1.191     harris41 11286: 
                   11287: =item *
                   11288: 
1.243     albertel 11289: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11290: a vairety of different possible values, $varname should be a request
                   11291: string, and the other parameters can be used to specify who and what
                   11292: one is asking about.
                   11293: 
                   11294: Possible values for $varname are environment.lastname (or other item
                   11295: from the envirnment hash), user.name (or someother aspect about the
                   11296: user), resource.0.maxtries (or some other part and parameter of a
                   11297: resource)
1.204     albertel 11298: 
                   11299: =item *
                   11300: 
1.243     albertel 11301: directcondval($number) : get current value of a condition; reads from a state
                   11302: string
1.204     albertel 11303: 
                   11304: =item *
                   11305: 
1.243     albertel 11306: condval($condidx) : value of condition index based on state
1.204     albertel 11307: 
                   11308: =item *
                   11309: 
1.243     albertel 11310: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11311: resource's metadata, $what should be either a specific key, or either
                   11312: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11313: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11314: 
                   11315: this function automatically caches all requests
1.191     harris41 11316: 
                   11317: =item *
                   11318: 
1.243     albertel 11319: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11320: network of library servers; returns file handle of where SQL and regex results
                   11321: will be stored for query
1.191     harris41 11322: 
                   11323: =item *
                   11324: 
1.243     albertel 11325: symbread($filename) : return symbolic list entry (filename argument optional);
                   11326: returns the data handle
1.191     harris41 11327: 
                   11328: =item *
                   11329: 
1.243     albertel 11330: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11331: a possible symb for the URL in $thisfn, and if is an encryypted
                   11332: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11333: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11334: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11335: 
1.191     harris41 11336: 
                   11337: =item *
                   11338: 
1.243     albertel 11339: symbclean($symb) : removes versions numbers from a symb, returns the
                   11340: cleaned symb
1.191     harris41 11341: 
                   11342: =item *
                   11343: 
1.243     albertel 11344: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11345: course map, user must be in a course for it to work.
1.191     harris41 11346: 
                   11347: =item *
                   11348: 
1.243     albertel 11349: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11350: 
                   11351: =item *
                   11352: 
1.243     albertel 11353: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11354: a random seed, all arguments are optional, if they aren't sent it uses the
                   11355: environment to derive them. Note: if symb isn't sent and it can't get one
                   11356: from &symbread it will use the current time as its return value
1.191     harris41 11357: 
                   11358: =item *
                   11359: 
1.243     albertel 11360: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11361: unfakeable, receipt
1.191     harris41 11362: 
                   11363: =item *
                   11364: 
1.620     albertel 11365: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11366: 
                   11367: =item *
                   11368: 
1.243     albertel 11369: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11370: 
                   11371: =item *
                   11372: 
1.243     albertel 11373: 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 11374: 
                   11375: =item *
                   11376: 
1.243     albertel 11377: 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 11378: 
                   11379: =item *
                   11380: 
1.243     albertel 11381: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11382: 
                   11383: =item *
                   11384: 
1.243     albertel 11385: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11386: forcing spreadsheet to reevaluate the resource scores next time.
                   11387: 
                   11388: =back
                   11389: 
                   11390: =head2 Storing/Retreiving Data
                   11391: 
                   11392: =over 4
1.191     harris41 11393: 
                   11394: =item *
                   11395: 
1.243     albertel 11396: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11397: for this url; hashref needs to be given and should be a \%hashname; the
                   11398: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11399: be derived from the env
1.191     harris41 11400: 
                   11401: =item *
                   11402: 
1.243     albertel 11403: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11404: uses critical subroutine
1.191     harris41 11405: 
                   11406: =item *
                   11407: 
1.243     albertel 11408: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11409: all args are optional
1.191     harris41 11410: 
                   11411: =item *
                   11412: 
1.717     albertel 11413: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11414: dumps the complete (or key matching regexp) namespace into a hash
                   11415: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11416: normally &store()ed into
                   11417: 
                   11418: $range should be either an integer '100' (give me the first 100
                   11419:                                            matching records)
                   11420:               or be  two integers sperated by a - with no spaces
                   11421:                  '30-50' (give me the 30th through the 50th matching
                   11422:                           records)
                   11423: 
                   11424: 
                   11425: =item *
                   11426: 
                   11427: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11428: replaces a &store() version of data with a replacement set of data
                   11429: for a particular resource in a namespace passed in the $storehash hash 
                   11430: reference
                   11431: 
                   11432: =item *
                   11433: 
1.243     albertel 11434: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11435: works very similar to store/cstore, but all data is stored in a
                   11436: temporary location and can be reset using tmpreset, $storehash should
                   11437: be a hash reference, returns nothing on success
1.191     harris41 11438: 
                   11439: =item *
                   11440: 
1.243     albertel 11441: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11442: similar to restore, but all data is stored in a temporary location and
                   11443: can be reset using tmpreset. Returns a hash of values on success,
                   11444: error string otherwise.
1.191     harris41 11445: 
                   11446: =item *
                   11447: 
1.243     albertel 11448: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11449: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11450: 
                   11451: =item *
                   11452: 
1.243     albertel 11453: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11454: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11455: 
                   11456: =item *
                   11457: 
1.243     albertel 11458: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11459: namesp ($udom and $uname are optional)
1.191     harris41 11460: 
                   11461: =item *
                   11462: 
1.702     albertel 11463: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11464: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11465: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11466: 
1.702     albertel 11467: $range should be either an integer '100' (give me the first 100
                   11468:                                            matching records)
                   11469:               or be  two integers sperated by a - with no spaces
                   11470:                  '30-50' (give me the 30th through the 50th matching
                   11471:                           records)
1.449     matthew  11472: =item *
                   11473: 
                   11474: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11475: $store can be a scalar, an array reference, or if the amount to be 
                   11476: incremented is > 1, a hash reference.
                   11477: 
                   11478: ($udom and $uname are optional)
1.191     harris41 11479: 
                   11480: =item *
                   11481: 
1.243     albertel 11482: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11483: ($udom and $uname are optional)
1.191     harris41 11484: 
                   11485: =item *
                   11486: 
1.243     albertel 11487: cput($namespace,$storehash,$udom,$uname) : critical put
                   11488: ($udom and $uname are optional)
1.191     harris41 11489: 
                   11490: =item *
                   11491: 
1.748     albertel 11492: newput($namespace,$storehash,$udom,$uname) :
                   11493: 
                   11494: Attempts to store the items in the $storehash, but only if they don't
                   11495: currently exist, if this succeeds you can be certain that you have 
                   11496: successfully created a new key value pair in the $namespace db.
                   11497: 
                   11498: 
                   11499: Args:
                   11500:  $namespace: name of database to store values to
                   11501:  $storehash: hashref to store to the db
                   11502:  $udom: (optional) domain of user containing the db
                   11503:  $uname: (optional) name of user caontaining the db
                   11504: 
                   11505: Returns:
                   11506:  'ok' -> succeeded in storing all keys of $storehash
                   11507:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11508:                         least <key> already existed in the db (other
                   11509:                         requested keys may also already exist)
1.967     bisitz   11510:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11511:  'con_lost' -> unable to contact request server
                   11512:  'refused' -> action was not allowed by remote machine
                   11513: 
                   11514: 
                   11515: =item *
                   11516: 
1.243     albertel 11517: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11518: reference filled in from namesp (encrypts the return communication)
                   11519: ($udom and $uname are optional)
1.191     harris41 11520: 
                   11521: =item *
                   11522: 
1.243     albertel 11523: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11524: critical subroutine
                   11525: 
1.806     raeburn  11526: =item *
                   11527: 
1.860     raeburn  11528: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11529: array reference filled in from namespace found in domain level on either
                   11530: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11531: 
                   11532: =item *
                   11533: 
1.860     raeburn  11534: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11535: domain level either on specified domain server ($uhome) or primary domain 
                   11536: server ($udom and $uhome are optional)
1.806     raeburn  11537: 
1.943     raeburn  11538: =item * 
                   11539: 
                   11540: get_domain_defaults($target_domain) : returns hash with defaults for
                   11541: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11542: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11543: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11544: Values are retrieved from cache (if current), or from domain's configuration.db
                   11545: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11546: or lonTabs/domain.tab. 
                   11547: 
                   11548: %domdefaults = &get_auth_defaults($target_domain);
                   11549: 
1.243     albertel 11550: =back
                   11551: 
                   11552: =head2 Network Status Functions
                   11553: 
                   11554: =over 4
1.191     harris41 11555: 
                   11556: =item *
                   11557: 
                   11558: dirlist($uri) : return directory list based on URI
                   11559: 
                   11560: =item *
                   11561: 
1.243     albertel 11562: spareserver() : find server with least workload from spare.tab
                   11563: 
1.986     foxr     11564: 
                   11565: =item *
                   11566: 
                   11567: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11568: if there is no corresponding loncapa host.
                   11569: 
1.243     albertel 11570: =back
                   11571: 
1.986     foxr     11572: 
1.243     albertel 11573: =head2 Apache Request
                   11574: 
                   11575: =over 4
1.191     harris41 11576: 
                   11577: =item *
                   11578: 
1.243     albertel 11579: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11580: localhost, posts hash
                   11581: 
                   11582: =back
                   11583: 
                   11584: =head2 Data to String to Data
                   11585: 
                   11586: =over 4
1.191     harris41 11587: 
                   11588: =item *
                   11589: 
1.243     albertel 11590: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11591: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11592: 
                   11593: =item *
                   11594: 
1.243     albertel 11595: hashref2str($hashref) : convert a hashref into a string complete with
                   11596: escaping and '=' and '&' separators, supports elements that are
                   11597: arrayrefs and hashrefs
1.191     harris41 11598: 
                   11599: =item *
                   11600: 
1.243     albertel 11601: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11602: with escaping and '&' separators, supports elements that are arrayrefs
                   11603: and hashrefs
1.191     harris41 11604: 
                   11605: =item *
                   11606: 
1.243     albertel 11607: str2hash($string) : convert string to hash using unescaping and
                   11608: splitting on '=' and '&', supports elements that are arrayrefs and
                   11609: hashrefs
1.191     harris41 11610: 
                   11611: =item *
                   11612: 
1.243     albertel 11613: str2array($string) : convert string to hash using unescaping and
                   11614: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11615: 
                   11616: =back
                   11617: 
                   11618: =head2 Logging Routines
                   11619: 
                   11620: 
                   11621: These routines allow one to make log messages in the lonnet.log and
                   11622: lonnet.perm logfiles.
1.191     harris41 11623: 
1.1119    foxr     11624: =over 4
                   11625: 
1.191     harris41 11626: =item *
                   11627: 
1.243     albertel 11628: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11629: 
                   11630: =item *
                   11631: 
1.243     albertel 11632: logthis() : append message to the normal lonnet.log file, it gets
                   11633: preiodically rolled over and deleted.
1.191     harris41 11634: 
                   11635: =item *
                   11636: 
1.243     albertel 11637: logperm() : append a permanent message to lonnet.perm.log, this log
                   11638: file never gets deleted by any automated portion of the system, only
                   11639: messages of critical importance should go in here.
                   11640: 
1.1119    foxr     11641: 
1.243     albertel 11642: =back
                   11643: 
                   11644: =head2 General File Helper Routines
                   11645: 
                   11646: =over 4
1.191     harris41 11647: 
                   11648: =item *
                   11649: 
1.481     raeburn  11650: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11651: (a) files in /uploaded
                   11652:   (i) If a local copy of the file exists - 
                   11653:       compares modification date of local copy with last-modified date for 
                   11654:       definitive version stored on home server for course. If local copy is 
                   11655:       stale, requests a new version from the home server and stores it. 
                   11656:       If the original has been removed from the home server, then local copy 
                   11657:       is unlinked.
                   11658:   (ii) If local copy does not exist -
                   11659:       requests the file from the home server and stores it. 
                   11660:   
                   11661:   If $caller is 'uploadrep':  
                   11662:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11663:     for request for files originally uploaded via DOCS. 
                   11664:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11665:   
                   11666:   Otherwise:
                   11667:      This indicates a call from the content generation phase of the request.
                   11668:      -  returns the entire contents of the file or -1.
                   11669:      
                   11670: (b) files in /res
                   11671:    - returns the entire contents of a file or -1; 
                   11672:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11673: 
1.712     albertel 11674: 
                   11675: =item *
                   11676: 
                   11677: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11678:                   reference
                   11679: 
                   11680: returns either a stat() list of data about the file or an empty list
                   11681: if the file doesn't exist or couldn't find out about it (connection
                   11682: problems or user unknown)
                   11683: 
1.191     harris41 11684: =item *
                   11685: 
1.243     albertel 11686: filelocation($dir,$file) : returns file system location of a file
                   11687: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11688: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11689: and a file of ../bob will become /a/bob)
1.191     harris41 11690: 
                   11691: =item *
                   11692: 
                   11693: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11694: filelocation except for hrefs
                   11695: 
                   11696: =item *
                   11697: 
                   11698: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11699: 
1.243     albertel 11700: =back
                   11701: 
1.608     albertel 11702: =head2 Usererfile file routines (/uploaded*)
                   11703: 
                   11704: =over 4
                   11705: 
                   11706: =item *
                   11707: 
                   11708: userfileupload(): main rotine for putting a file in a user or course's
                   11709:                   filespace, arguments are,
                   11710: 
1.620     albertel 11711:  formname - required - this is the name of the element in $env where the
1.608     albertel 11712:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11713:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11714:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11715:  context - if coursedoc, store the file in the course of the active role
                   11716:              of the current user; 
                   11717:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11718:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11719:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11720:          if undefined, it will be placed in "unknown"
                   11721: 
                   11722:  (This routine calls clean_filename() to remove any dangerous
                   11723:  characters from the filename, and then calls finuserfileupload() to
                   11724:  complete the transaction)
                   11725: 
                   11726:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11727:  and /adm/notfound.html if unsuccessful
                   11728: 
                   11729: =item *
                   11730: 
                   11731: clean_filename(): routine for cleaing a filename up for storage in
                   11732:                  userfile space, argument is:
                   11733: 
                   11734:  filename - proposed filename
                   11735: 
                   11736: returns: the new clean filename
                   11737: 
                   11738: =item *
                   11739: 
1.1090    raeburn  11740: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11741: userspace, probably shouldn't be called directly
                   11742: 
                   11743:   docuname: username or courseid of destination for the file
                   11744:   docudom: domain of user/course of destination for the file
                   11745:   formname: same as for userfileupload()
1.1090    raeburn  11746:   fname: filename (including subdirectories) for the file
                   11747:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11748:   allfiles: reference to hash used to store objects found by parser
                   11749:   codebase: reference to hash used for codebases of java objects found by parser
                   11750:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11751:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11752:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11753:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11754:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11755:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11756:   mimetype: reference to scalar to accommodate mime type determined
                   11757:             from File::MMagic if $parser = parse.
1.608     albertel 11758: 
                   11759:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11760:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11761:  was 'overwrite').
                   11762:  
1.608     albertel 11763: 
                   11764: =item *
                   11765: 
                   11766: renameuserfile(): renames an existing userfile to a new name
                   11767: 
                   11768:   Args:
                   11769:    docuname: username or courseid of destination for the file
                   11770:    docudom: domain of user/course of destination for the file
                   11771:    old: current file name (including any subdirs under userfiles)
                   11772:    new: desired file name (including any subdirs under userfiles)
                   11773: 
                   11774: =item *
                   11775: 
                   11776: mkdiruserfile(): creates a directory is a userfiles dir
                   11777: 
                   11778:   Args:
                   11779:    docuname: username or courseid of destination for the file
                   11780:    docudom: domain of user/course of destination for the file
                   11781:    dir: dir to create (including any subdirs under userfiles)
                   11782: 
                   11783: =item *
                   11784: 
                   11785: removeuserfile(): removes a file that exists in userfiles
                   11786: 
                   11787:   Args:
                   11788:    docuname: username or courseid of destination for the file
                   11789:    docudom: domain of user/course of destination for the file
                   11790:    fname: filname to delete (including any subdirs under userfiles)
                   11791: 
                   11792: =item *
                   11793: 
                   11794: removeuploadedurl(): convience function for removeuserfile()
                   11795: 
                   11796:   Args:
                   11797:    url:  a full /uploaded/... url to delete
                   11798: 
1.747     albertel 11799: =item * 
                   11800: 
                   11801: get_portfile_permissions():
                   11802:   Args:
                   11803:     domain: domain of user or course contain the portfolio files
                   11804:     user: name of user or num of course contain the portfolio files
                   11805:   Returns:
                   11806:     hashref of a dump of the proper file_permissions.db
                   11807:    
                   11808: 
                   11809: =item * 
                   11810: 
                   11811: get_access_controls():
                   11812: 
                   11813: Args:
                   11814:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11815:   group: (optional) the group you want the files associated with
                   11816:   file: (optional) the file you want access info on
                   11817: 
                   11818: Returns:
1.749     raeburn  11819:     a hash (keys are file names) of hashes containing
                   11820:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11821:         values are XML containing access control settings (see below) 
1.747     albertel 11822: 
                   11823: Internal notes:
                   11824: 
1.749     raeburn  11825:  access controls are stored in file_permissions.db as key=value pairs.
                   11826:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11827:         where scope -> public,guest,course,group,domains or users.
                   11828:               end -> UNIX time for end of access (0 -> no end date)
                   11829:               start -> UNIX time for start of access
                   11830: 
                   11831:     value -> XML description of access control
                   11832:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11833:             <start></start>
                   11834:             <end></end>
                   11835: 
                   11836:             <password></password>  for scope type = guest
                   11837: 
                   11838:             <domain></domain>     for scope type = course or group
                   11839:             <number></number>
                   11840:             <roles id="">
                   11841:              <role></role>
                   11842:              <access></access>
                   11843:              <section></section>
                   11844:              <group></group>
                   11845:             </roles>
                   11846: 
                   11847:             <dom></dom>         for scope type = domains
                   11848: 
                   11849:             <users>             for scope type = users
                   11850:              <user>
                   11851:               <uname></uname>
                   11852:               <udom></udom>
                   11853:              </user>
                   11854:             </users>
                   11855:            </scope> 
                   11856:               
                   11857:  Access data is also aggregated for each file in an additional key=value pair:
                   11858:  key -> path to file/file_name\0accesscontrol 
                   11859:  value -> reference to hash
                   11860:           hash contains key = value pairs
                   11861:           where key = uniqueID:scope_end_start
                   11862:                 value = UNIX time record was last updated
                   11863: 
                   11864:           Used to improve speed of look-ups of access controls for each file.  
                   11865:  
                   11866:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11867: 
                   11868: modify_access_controls():
                   11869: 
                   11870: Modifies access controls for a portfolio file
                   11871: Args
                   11872: 1. file name
                   11873: 2. reference to hash of required changes,
                   11874: 3. domain
                   11875: 4. username
                   11876:   where domain,username are the domain of the portfolio owner 
                   11877:   (either a user or a course) 
                   11878: 
                   11879: Returns:
                   11880: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11881: 2. result of deletions ('ok' or 'error', with error message).
                   11882: 3. reference to hash of any new or updated access controls.
                   11883: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11884:    key = integer (inbound ID)
                   11885:    value = uniqueID  
1.747     albertel 11886: 
1.608     albertel 11887: =back
                   11888: 
1.243     albertel 11889: =head2 HTTP Helper Routines
                   11890: 
                   11891: =over 4
                   11892: 
1.191     harris41 11893: =item *
                   11894: 
                   11895: escape() : unpack non-word characters into CGI-compatible hex codes
                   11896: 
                   11897: =item *
                   11898: 
                   11899: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11900: 
1.243     albertel 11901: =back
                   11902: 
                   11903: =head1 PRIVATE SUBROUTINES
                   11904: 
                   11905: =head2 Underlying communication routines (Shouldn't call)
                   11906: 
                   11907: =over 4
                   11908: 
                   11909: =item *
                   11910: 
                   11911: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11912: 
                   11913: =item *
                   11914: 
                   11915: reply() : uses subreply to send a message to remote machine, logs all failures
                   11916: 
                   11917: =item *
                   11918: 
                   11919: critical() : passes a critical message to another server; if cannot
                   11920: get through then place message in connection buffer directory and
                   11921: returns con_delayed, if incapable of saving message, returns
                   11922: con_failed
                   11923: 
                   11924: =item *
                   11925: 
                   11926: reconlonc() : tries to reconnect lonc client processes.
                   11927: 
                   11928: =back
                   11929: 
                   11930: =head2 Resource Access Logging
                   11931: 
                   11932: =over 4
                   11933: 
                   11934: =item *
                   11935: 
                   11936: flushcourselogs() : flush (save) buffer logs and access logs
                   11937: 
                   11938: =item *
                   11939: 
                   11940: courselog($what) : save message for course in hash
                   11941: 
                   11942: =item *
                   11943: 
                   11944: courseacclog($what) : save message for course using &courselog().  Perform
                   11945: special processing for specific resource types (problems, exams, quizzes, etc).
                   11946: 
1.191     harris41 11947: =item *
                   11948: 
                   11949: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11950: as a PerlChildExitHandler
1.243     albertel 11951: 
                   11952: =back
                   11953: 
                   11954: =head2 Other
                   11955: 
                   11956: =over 4
                   11957: 
                   11958: =item *
                   11959: 
                   11960: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11961: 
                   11962: =back
                   11963: 
                   11964: =cut
1.877     foxr     11965: 

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