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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1122  ! raeburn     4: # $Id: lonnet.pm,v 1.1121 2011/07/31 22:55:53 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) = @_;
                    311:     my (%returnhash,%whatneeded);
                    312:     if (ref($whathash) eq 'ARRAY') {
                    313:         foreach my $what (sort(keys(%{$whathash}))) {
                    314:             my $type = $whathash->{$what};
                    315:             my $hashid = $lonhost.'-'.$what;
                    316:             my ($result,$cached); 
                    317:             unless ($ignore_cache) {
                    318:                 ($result,$cached)=&is_cached_new('lonnetglobal',$hashid);
                    319:                 $returnhash{$what} = $result;
                    320:             }
                    321:             if (defined($cached)) {
                    322:                 $returnhash{$what} = $result;
                    323:             } else {
                    324:                 $whatneeded{$what} = $type;
                    325:             }
                    326:         }
                    327:         if (keys(%whatneeded) > 0) {
                    328:             my $requested = &freeze_escape(\%whatneeded);
                    329:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1122  ! raeburn   330:             unless (($rep=~/^refused/) || ($rep=~/^rejected/) || ($rep eq 'con_lost')) {
1.1121    raeburn   331:                 my @pairs=split(/\&/,$rep);
                    332:                 if ($rep !~ /^error/) {
                    333:                     foreach my $item (@pairs) {
                    334:                         my ($key,$value)=split(/=/,$item,2);
                    335:                         my $what = &unescape($key);
                    336:                         my $hashid = $lonhost.'-'.$what;
                    337:                         $returnhash{$what}=&thaw_unescape($value);
                    338:                         &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
                    339:                     }
                    340:                 }
                    341:             }
                    342:         }
                    343:     }
                    344:     return %returnhash;
                    345: }
                    346: 
1.1       albertel  347: # -------------------------------------------------- Non-critical communication
                    348: sub subreply {
                    349:     my ($cmd,$server)=@_;
1.838     albertel  350:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      351:     #
                    352:     #  With loncnew process trimming, there's a timing hole between lonc server
                    353:     #  process exit and the master server picking up the listen on the AF_UNIX
                    354:     #  socket.  In that time interval, a lock file will exist:
                    355: 
                    356:     my $lockfile=$peerfile.".lock";
                    357:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    358: 	sleep(1);
                    359:     }
                    360:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      361:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      362:     #
1.550     foxr      363:     #   We'll give the connection a few tries before abandoning it.  If
                    364:     #   connection is not possible, we'll con_lost back to the client.
                    365:     #   
                    366:     my $client;
                    367:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    368: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    369: 				      Type    => SOCK_STREAM,
                    370: 				      Timeout => 10);
1.869     albertel  371: 	if ($client) {
1.550     foxr      372: 	    last;		# Connected!
1.850     albertel  373: 	} else {
1.853     albertel  374: 	    &create_connection(&hostname($server),$server);
1.550     foxr      375: 	}
1.850     albertel  376:         sleep(1);		# Try again later if failed connection.
1.550     foxr      377:     }
                    378:     my $answer;
                    379:     if ($client) {
1.704     albertel  380: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      381: 	$answer=<$client>;
                    382: 	if (!$answer) { $answer="con_lost"; }
                    383: 	chomp($answer);
                    384:     } else {
                    385: 	$answer = 'con_lost';	# Failed connection.
                    386:     }
1.1       albertel  387:     return $answer;
                    388: }
                    389: 
                    390: sub reply {
                    391:     my ($cmd,$server)=@_;
1.838     albertel  392:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  393:     my $answer=subreply($cmd,$server);
1.65      www       394:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  395:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       396:                 " $cmd to $server returned $answer</font>");
                    397:     }
1.1       albertel  398:     return $answer;
                    399: }
                    400: 
                    401: # ----------------------------------------------------------- Send USR1 to lonc
                    402: 
                    403: sub reconlonc {
1.891     albertel  404:     my ($lonid) = @_;
                    405:     my $hostname = &hostname($lonid);
                    406:     if ($lonid) {
                    407: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    408: 	if ($hostname && -e $peerfile) {
                    409: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    410: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    411: 					     Type    => SOCK_STREAM,
                    412: 					     Timeout => 10);
                    413: 	    if ($client) {
                    414: 		print $client ("reset_retries\n");
                    415: 		my $answer=<$client>;
                    416: 		#reset just this one.
                    417: 	    }
                    418: 	}
                    419: 	return;
                    420:     }
                    421: 
1.836     www       422:     &logthis("Trying to reconnect lonc");
1.1       albertel  423:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  424:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  425: 	my $loncpid=<$fh>;
                    426:         chomp($loncpid);
                    427:         if (kill 0 => $loncpid) {
                    428: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    429:             kill USR1 => $loncpid;
                    430:             sleep 1;
1.836     www       431:          } else {
1.12      www       432: 	    &logthis(
1.672     albertel  433:                "<font color=\"blue\">WARNING:".
1.12      www       434:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  435:         }
                    436:     } else {
1.836     www       437: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  438:     }
                    439: }
                    440: 
                    441: # ------------------------------------------------------ Critical communication
1.12      www       442: 
1.1       albertel  443: sub critical {
                    444:     my ($cmd,$server)=@_;
1.838     albertel  445:     unless (&hostname($server)) {
1.672     albertel  446:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       447:                " Critical message to unknown server ($server)</font>");
                    448:         return 'no_such_host';
                    449:     }
1.1       albertel  450:     my $answer=reply($cmd,$server);
                    451:     if ($answer eq 'con_lost') {
                    452: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  453: 	my $answer=reply($cmd,$server);
1.1       albertel  454:         if ($answer eq 'con_lost') {
                    455:             my $now=time;
                    456:             my $middlename=$cmd;
1.5       www       457:             $middlename=substr($middlename,0,16);
1.1       albertel  458:             $middlename=~s/\W//g;
                    459:             my $dfilename=
1.305     www       460:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    461:             $dumpcount++;
1.1       albertel  462:             {
1.448     albertel  463: 		my $dfh;
                    464: 		if (open($dfh,">$dfilename")) {
                    465: 		    print $dfh "$cmd\n"; 
                    466: 		    close($dfh);
                    467: 		}
1.1       albertel  468:             }
                    469:             sleep 2;
                    470:             my $wcmd='';
                    471:             {
1.448     albertel  472: 		my $dfh;
                    473: 		if (open($dfh,"<$dfilename")) {
                    474: 		    $wcmd=<$dfh>; 
                    475: 		    close($dfh);
                    476: 		}
1.1       albertel  477:             }
                    478:             chomp($wcmd);
1.7       www       479:             if ($wcmd eq $cmd) {
1.672     albertel  480: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       481:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  482:                 &logperm("D:$server:$cmd");
                    483: 	        return 'con_delayed';
                    484:             } else {
1.672     albertel  485:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       486:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  487:                 &logperm("F:$server:$cmd");
                    488:                 return 'con_failed';
                    489:             }
                    490:         }
                    491:     }
                    492:     return $answer;
1.405     albertel  493: }
                    494: 
1.755     albertel  495: # ------------------------------------------- check if return value is an error
                    496: 
                    497: sub error {
                    498:     my ($result) = @_;
1.756     albertel  499:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  500: 	if ($2 == 2) { return undef; }
                    501: 	return $1;
                    502:     }
                    503:     return undef;
                    504: }
                    505: 
1.783     albertel  506: sub convert_and_load_session_env {
                    507:     my ($lonidsdir,$handle)=@_;
                    508:     my @profile;
                    509:     {
1.917     albertel  510: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    511: 	if (!$opened) {
1.915     albertel  512: 	    return 0;
                    513: 	}
1.783     albertel  514: 	flock($idf,LOCK_SH);
                    515: 	@profile=<$idf>;
                    516: 	close($idf);
                    517:     }
                    518:     my %temp_env;
                    519:     foreach my $line (@profile) {
1.786     albertel  520: 	if ($line !~ m/=/) {
                    521: 	    return 0;
                    522: 	}
1.783     albertel  523: 	chomp($line);
                    524: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    525: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    526:     }
                    527:     unlink("$lonidsdir/$handle.id");
                    528:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    529: 	    0640)) {
                    530: 	%disk_env = %temp_env;
                    531: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    532: 	untie(%disk_env);
                    533:     }
1.786     albertel  534:     return 1;
1.783     albertel  535: }
                    536: 
1.374     www       537: # ------------------------------------------- Transfer profile into environment
1.780     albertel  538: my $env_loaded;
                    539: sub transfer_profile_to_env {
1.788     albertel  540:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    541:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       542: 
1.720     albertel  543:     if (!defined($lonidsdir)) {
                    544: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    545:     }
                    546:     if (!defined($handle)) {
                    547:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    548:     }
                    549: 
1.786     albertel  550:     my $convert;
                    551:     {
1.917     albertel  552:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    553: 	if (!$opened) {
1.915     albertel  554: 	    return;
                    555: 	}
1.786     albertel  556: 	flock($idf,LOCK_SH);
                    557: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    558: 		&GDBM_READER(),0640)) {
                    559: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    560: 	    untie(%disk_env);
                    561: 	} else {
                    562: 	    $convert = 1;
                    563: 	}
                    564:     }
                    565:     if ($convert) {
                    566: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    567: 	    &logthis("Failed to load session, or convert session.");
                    568: 	}
1.374     www       569:     }
1.783     albertel  570: 
1.786     albertel  571:     my %remove;
1.783     albertel  572:     while ( my $envname = each(%env) ) {
1.433     matthew   573:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    574:             if ($time < time-300) {
1.783     albertel  575:                 $remove{$key}++;
1.433     matthew   576:             }
                    577:         }
                    578:     }
1.783     albertel  579: 
1.619     albertel  580:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  581:     $env_loaded=1;
1.783     albertel  582:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   583:         &delenv($expired_key);
1.374     www       584:     }
1.1       albertel  585: }
                    586: 
1.916     albertel  587: # ---------------------------------------------------- Check for valid session 
                    588: sub check_for_valid_session {
                    589:     my ($r) = @_;
                    590:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    591:     my $lonid=$cookies{'lonID'};
                    592:     return undef if (!$lonid);
                    593: 
                    594:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    595:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    596:     return undef if (!-e "$lonidsdir/$handle.id");
                    597: 
1.917     albertel  598:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    599:     return undef if (!$opened);
1.916     albertel  600: 
                    601:     flock($idf,LOCK_SH);
                    602:     my %disk_env;
                    603:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    604: 	    &GDBM_READER(),0640)) {
                    605: 	return undef;	
                    606:     }
                    607: 
                    608:     if (!defined($disk_env{'user.name'})
                    609: 	|| !defined($disk_env{'user.domain'})) {
                    610: 	return undef;
                    611:     }
                    612:     return $handle;
                    613: }
                    614: 
1.830     albertel  615: sub timed_flock {
                    616:     my ($file,$lock_type) = @_;
                    617:     my $failed=0;
                    618:     eval {
                    619: 	local $SIG{__DIE__}='DEFAULT';
                    620: 	local $SIG{ALRM}=sub {
                    621: 	    $failed=1;
                    622: 	    die("failed lock");
                    623: 	};
                    624: 	alarm(13);
                    625: 	flock($file,$lock_type);
                    626: 	alarm(0);
                    627:     };
                    628:     if ($failed) {
                    629: 	return undef;
                    630:     } else {
                    631: 	return 1;
                    632:     }
                    633: }
                    634: 
1.5       www       635: # ---------------------------------------------------------- Append Environment
                    636: 
                    637: sub appenv {
1.949     raeburn   638:     my ($newenv,$roles) = @_;
                    639:     if (ref($newenv) eq 'HASH') {
                    640:         foreach my $key (keys(%{$newenv})) {
                    641:             my $refused = 0;
                    642: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    643:                 $refused = 1;
                    644:                 if (ref($roles) eq 'ARRAY') {
                    645:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    646:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    647:                         $refused = 0;
                    648:                     }
                    649:                 }
                    650:             }
                    651:             if ($refused) {
                    652:                 &logthis("<font color=\"blue\">WARNING: ".
                    653:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    654:                          .'</font>');
                    655: 	        delete($newenv->{$key});
                    656:             } else {
                    657:                 $env{$key}=$newenv->{$key};
                    658:             }
                    659:         }
                    660:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    661:         if ($opened
                    662: 	    && &timed_flock($env_file,LOCK_EX)
                    663: 	    &&
                    664: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    665: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    666: 	    while (my ($key,$value) = each(%{$newenv})) {
                    667: 	        $disk_env{$key} = $value;
                    668: 	    }
                    669: 	    untie(%disk_env);
1.35      www       670:         }
1.191     harris41  671:     }
1.56      www       672:     return 'ok';
                    673: }
                    674: # ----------------------------------------------------- Delete from Environment
                    675: 
                    676: sub delenv {
1.1104    raeburn   677:     my ($delthis,$regexp,$roles) = @_;
                    678:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    679:         my $refused = 1;
                    680:         if (ref($roles) eq 'ARRAY') {
                    681:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    682:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    683:                 $refused = 0;
                    684:             }
                    685:         }
                    686:         if ($refused) {
                    687:             &logthis("<font color=\"blue\">WARNING: ".
                    688:                      "Attempt to delete from environment ".$delthis);
                    689:             return 'error';
                    690:         }
1.56      www       691:     }
1.917     albertel  692:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    693:     if ($opened
1.915     albertel  694: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  695: 	&&
                    696: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    697: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  698: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   699: 	    if ($regexp) {
                    700:                 if ($key=~/^$delthis/) {
                    701:                     delete($env{$key});
                    702:                     delete($disk_env{$key});
                    703:                 } 
                    704:             } else {
                    705:                 if ($key=~/^\Q$delthis\E/) {
                    706: 		    delete($env{$key});
                    707: 		    delete($disk_env{$key});
                    708: 	        }
                    709:             }
1.448     albertel  710: 	}
1.783     albertel  711: 	untie(%disk_env);
1.5       www       712:     }
                    713:     return 'ok';
1.369     albertel  714: }
                    715: 
1.790     albertel  716: sub get_env_multiple {
                    717:     my ($name) = @_;
                    718:     my @values;
                    719:     if (defined($env{$name})) {
                    720:         # exists is it an array
                    721:         if (ref($env{$name})) {
                    722:             @values=@{ $env{$name} };
                    723:         } else {
                    724:             $values[0]=$env{$name};
                    725:         }
                    726:     }
                    727:     return(@values);
                    728: }
                    729: 
1.958     www       730: # ------------------------------------------------------------------- Locking
                    731: 
                    732: sub set_lock {
                    733:     my ($text)=@_;
                    734:     $locknum++;
                    735:     my $id=$$.'-'.$locknum;
                    736:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    737:              'session.lock.'.$id => $text});
                    738:     return $id;
                    739: }
                    740: 
                    741: sub get_locks {
                    742:     my $num=0;
                    743:     my %texts=();
                    744:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    745:        if ($lock=~/\w/) {
                    746:           $num++;
                    747:           $texts{$lock}=$env{'session.lock.'.$lock};
                    748:        }
                    749:    }
                    750:    return ($num,%texts);
                    751: }
                    752: 
                    753: sub remove_lock {
                    754:     my ($id)=@_;
                    755:     my $newlocks='';
                    756:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    757:        if (($lock=~/\w/) && ($lock ne $id)) {
                    758:           $newlocks.=','.$lock;
                    759:        }
                    760:     }
                    761:     &appenv({'session.locks' => $newlocks});
                    762:     &delenv('session.lock.'.$id);
                    763: }
                    764: 
                    765: sub remove_all_locks {
                    766:     my $activelocks=$env{'session.locks'};
                    767:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    768:        if ($lock=~/\w/) {
                    769:           &remove_lock($lock);
                    770:        }
                    771:     }
                    772: }
                    773: 
                    774: 
1.369     albertel  775: # ------------------------------------------ Find out current server userload
                    776: sub userload {
                    777:     my $numusers=0;
                    778:     {
                    779: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    780: 	my $filename;
                    781: 	my $curtime=time;
                    782: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  783: 	    next if ($filename eq '.' || $filename eq '..');
                    784: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  785: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  786: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  787: 	}
                    788: 	closedir(LONIDS);
                    789:     }
                    790:     my $userloadpercent=0;
                    791:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    792:     if ($maxuserload) {
1.371     albertel  793: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  794:     }
1.372     albertel  795:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  796:     return $userloadpercent;
1.283     www       797: }
                    798: 
1.1       albertel  799: # ------------------------------ Find server with least workload from spare.tab
1.11      www       800: 
1.1       albertel  801: sub spareserver {
1.1083    raeburn   802:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  803:     my $spare_server;
1.370     albertel  804:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  805:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    806:                                                      :  $userloadpercent;
1.1083    raeburn   807:     my ($uint_dom,$remotesessions);
                    808:     if (($udom ne '') && (&domain($udom) ne '')) {
                    809:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    810:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    811:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    812:         $remotesessions = $udomdefaults{'remotesessions'};
                    813:     }
1.784     albertel  814:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   815:         if ($uint_dom) {
                    816:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    817:                                           $try_server));
                    818:         }
1.784     albertel  819: 	($spare_server, $lowest_load) =
                    820: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    821:     }
                    822: 
                    823:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    824: 
                    825:     if (!$found_server) {
                    826: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   827:             if ($uint_dom) {
                    828:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    829:                                              $try_server));
                    830:             }
1.784     albertel  831: 	    ($spare_server, $lowest_load) =
                    832: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    833: 	}
                    834:     }
                    835: 
                    836:     if (!$want_server_name) {
1.968     raeburn   837:         my $protocol = 'http';
                    838:         if ($protocol{$spare_server} eq 'https') {
                    839:             $protocol = $protocol{$spare_server};
                    840:         }
1.1001    raeburn   841:         if (defined($spare_server)) {
                    842:             my $hostname = &hostname($spare_server);
1.1083    raeburn   843:             if (defined($hostname)) {
1.1001    raeburn   844: 	        $spare_server = $protocol.'://'.$hostname;
                    845:             }
                    846:         }
1.784     albertel  847:     }
                    848:     return $spare_server;
                    849: }
                    850: 
                    851: sub compare_server_load {
                    852:     my ($try_server, $spare_server, $lowest_load) = @_;
                    853: 
                    854:     my $loadans     = &reply('load',    $try_server);
                    855:     my $userloadans = &reply('userload',$try_server);
                    856: 
                    857:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   858: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  859:     }
                    860: 
                    861:     my $load;
                    862:     if ($loadans =~ /\d/) {
                    863: 	if ($userloadans =~ /\d/) {
                    864: 	    #both are numbers, pick the bigger one
                    865: 	    $load = ($loadans > $userloadans) ? $loadans 
                    866: 		                              : $userloadans;
1.411     albertel  867: 	} else {
1.784     albertel  868: 	    $load = $loadans;
1.411     albertel  869: 	}
1.784     albertel  870:     } else {
                    871: 	$load = $userloadans;
                    872:     }
                    873: 
                    874:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    875: 	$spare_server = $try_server;
                    876: 	$lowest_load  = $load;
1.370     albertel  877:     }
1.784     albertel  878:     return ($spare_server,$lowest_load);
1.202     matthew   879: }
1.914     albertel  880: 
                    881: # --------------------------- ask offload servers if user already has a session
                    882: sub find_existing_session {
                    883:     my ($udom,$uname) = @_;
                    884:     foreach my $try_server (@{ $spareid{'primary'} },
                    885: 			    @{ $spareid{'default'} }) {
                    886: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    887:     }
                    888:     return;
                    889: }
                    890: 
                    891: # -------------------------------- ask if server already has a session for user
                    892: sub has_user_session {
                    893:     my ($lonid,$udom,$uname) = @_;
                    894:     my $result = &reply(join(':','userhassession',
                    895: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    896:     return 1 if ($result eq 'ok');
                    897: 
                    898:     return 0;
                    899: }
                    900: 
1.1076    raeburn   901: # --------- determine least loaded server in a user's domain which allows login
                    902: 
                    903: sub choose_server {
1.1115    raeburn   904:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   905:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   906:     my %servers = &get_servers($udom);
1.1076    raeburn   907:     my $lowest_load = 30000;
1.1116    raeburn   908:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   909:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   910:         my $loginvia;
                    911:         if ($checkloginvia) {
                    912:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   913:             if ($loginvia) {
                    914:                 my ($server,$path) = split(/:/,$loginvia);
                    915:                 ($login_host, $lowest_load) =
                    916:                     &compare_server_load($server, $login_host, $lowest_load);
                    917:                 if ($login_host eq $server) {
                    918:                     $portal_path = $path;
                    919:                 }
                    920:             } else {
                    921:                 ($login_host, $lowest_load) =
                    922:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    923:                 if ($login_host eq $lonhost) {
                    924:                     $portal_path = '';
                    925:                 }
                    926:             }
                    927:         } else {
1.1076    raeburn   928:             ($login_host, $lowest_load) =
1.1116    raeburn   929:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   930:         }
                    931:     }
                    932:     if ($login_host ne '') {
1.1116    raeburn   933:         $hostname = &hostname($login_host);
1.1076    raeburn   934:     }
1.1116    raeburn   935:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   936: }
                    937: 
1.202     matthew   938: # --------------------------------------------- Try to change a user's password
                    939: 
                    940: sub changepass {
1.799     raeburn   941:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   942:     $currentpass = &escape($currentpass);
                    943:     $newpass     = &escape($newpass);
1.1030    raeburn   944:     my $lonhost = $perlvar{'lonHostID'};
                    945:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   946: 		       $server);
                    947:     if (! $answer) {
                    948: 	&logthis("No reply on password change request to $server ".
                    949: 		 "by $uname in domain $udom.");
                    950:     } elsif ($answer =~ "^ok") {
                    951:         &logthis("$uname in $udom successfully changed their password ".
                    952: 		 "on $server.");
                    953:     } elsif ($answer =~ "^pwchange_failure") {
                    954: 	&logthis("$uname in $udom was unable to change their password ".
                    955: 		 "on $server.  The action was blocked by either lcpasswd ".
                    956: 		 "or pwchange");
                    957:     } elsif ($answer =~ "^non_authorized") {
                    958:         &logthis("$uname in $udom did not get their password correct when ".
                    959: 		 "attempting to change it on $server.");
                    960:     } elsif ($answer =~ "^auth_mode_error") {
                    961:         &logthis("$uname in $udom attempted to change their password despite ".
                    962: 		 "not being locally or internally authenticated on $server.");
                    963:     } elsif ($answer =~ "^unknown_user") {
                    964:         &logthis("$uname in $udom attempted to change their password ".
                    965: 		 "on $server but were unable to because $server is not ".
                    966: 		 "their home server.");
                    967:     } elsif ($answer =~ "^refused") {
                    968: 	&logthis("$server refused to change $uname in $udom password because ".
                    969: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   970:     } elsif ($answer =~ "invalid_client") {
                    971:         &logthis("$server refused to change $uname in $udom password because ".
                    972:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   973:     }
                    974:     return $answer;
1.1       albertel  975: }
                    976: 
1.169     harris41  977: # ----------------------- Try to determine user's current authentication scheme
                    978: 
                    979: sub queryauthenticate {
                    980:     my ($uname,$udom)=@_;
1.456     albertel  981:     my $uhome=&homeserver($uname,$udom);
                    982:     if (!$uhome) {
                    983: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    984: 	return 'no_host';
                    985:     }
                    986:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    987:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    988: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  989:     }
1.456     albertel  990:     return $answer;
1.169     harris41  991: }
                    992: 
1.1       albertel  993: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       994: 
1.1       albertel  995: sub authenticate {
1.1073    raeburn   996:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  997:     $upass=&escape($upass);
                    998:     $uname= &LONCAPA::clean_username($uname);
1.836     www       999:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1000:     my $newhome;
1.836     www      1001:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1002: # Maybe the machine was offline and only re-appeared again recently?
                   1003:         &reconlonc();
                   1004: # One more
1.952     raeburn  1005: 	$uhome=&homeserver($uname,$udom,1);
                   1006:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1007:             if (defined(&domain($udom,'primary'))) {
                   1008:                 $newhome=&domain($udom,'primary');
                   1009:             }
                   1010:             if ($newhome ne '') {
                   1011:                 $uhome = $newhome;
                   1012:             }
                   1013:         }
1.836     www      1014: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1015: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1016: 	    return 'no_host';
                   1017:         }
1.1       albertel 1018:     }
1.1073    raeburn  1019:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1020:     if ($answer eq 'authorized') {
1.952     raeburn  1021:         if ($newhome) {
                   1022:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1023:             return 'no_account_on_host'; 
                   1024:         } else {
                   1025:             &logthis("User $uname at $udom authorized by $uhome");
                   1026:             return $uhome;
                   1027:         }
1.471     albertel 1028:     }
                   1029:     if ($answer eq 'non_authorized') {
                   1030: 	&logthis("User $uname at $udom rejected by $uhome");
                   1031: 	return 'no_host'; 
1.9       www      1032:     }
1.471     albertel 1033:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1034:     return 'no_host';
                   1035: }
                   1036: 
1.1073    raeburn  1037: sub can_host_session {
1.1074    raeburn  1038:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1039:     my $canhost = 1;
1.1074    raeburn  1040:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1041:     if (ref($remotesessions) eq 'HASH') {
                   1042:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1043:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1044:                 $canhost = 0;
                   1045:             } else {
                   1046:                 $canhost = 1;
                   1047:             }
                   1048:         }
                   1049:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1050:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1051:                 $canhost = 1;
                   1052:             } else {
                   1053:                 $canhost = 0;
                   1054:             }
                   1055:         }
                   1056:         if ($canhost) {
                   1057:             if ($remotesessions->{'version'} ne '') {
                   1058:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1059:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1060:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1061:                         my $major = $1;
                   1062:                         my $minor = $2;
                   1063:                         if (($major < $reqmajor ) ||
                   1064:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1065:                             $canhost = 0;
                   1066:                         }
                   1067:                     } else {
                   1068:                         $canhost = 0;
                   1069:                     }
                   1070:                 }
                   1071:             }
                   1072:         }
                   1073:     }
                   1074:     if ($canhost) {
                   1075:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1076:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1077:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1078:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1079:                 if (($uint_dom ne '') && 
                   1080:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1081:                     $canhost = 0;
                   1082:                 } else {
                   1083:                     $canhost = 1;
                   1084:                 }
                   1085:             }
                   1086:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1087:                 if (($uint_dom ne '') && 
                   1088:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1089:                     $canhost = 1;
                   1090:                 } else {
                   1091:                     $canhost = 0;
                   1092:                 }
                   1093:             }
                   1094:         }
                   1095:     }
                   1096:     return $canhost;
                   1097: }
                   1098: 
1.1083    raeburn  1099: sub spare_can_host {
                   1100:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1101:     my $canhost=1;
                   1102:     my @intdoms;
                   1103:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1104:     if (ref($internet_names) eq 'ARRAY') {
                   1105:         @intdoms = @{$internet_names};
                   1106:     }
                   1107:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1108:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1109:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1110:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1111:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1112:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1113:                                      $remotesessions,
                   1114:                                      $defdomdefaults{'hostedsessions'});
                   1115:     }
                   1116:     return $canhost;
                   1117: }
                   1118: 
1.1       albertel 1119: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1120: 
1.599     albertel 1121: my %homecache;
1.1       albertel 1122: sub homeserver {
1.230     stredwic 1123:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1124:     my $index="$uname:$udom";
1.426     albertel 1125: 
1.599     albertel 1126:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1127: 
                   1128:     my %servers = &get_servers($udom,'library');
                   1129:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1130:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1131: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1132: 
                   1133: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1134: 	if ($answer eq 'found') {
                   1135: 	    delete($badServerCache{$tryserver}); 
                   1136: 	    return $homecache{$index}=$tryserver;
                   1137: 	} elsif ($answer eq 'no_host') {
                   1138: 	    $badServerCache{$tryserver}=1;
                   1139: 	}
1.1       albertel 1140:     }    
                   1141:     return 'no_host';
1.70      www      1142: }
                   1143: 
                   1144: # ------------------------------------- Find the usernames behind a list of IDs
                   1145: 
                   1146: sub idget {
                   1147:     my ($udom,@ids)=@_;
                   1148:     my %returnhash=();
                   1149:     
1.841     albertel 1150:     my %servers = &get_servers($udom,'library');
                   1151:     foreach my $tryserver (keys(%servers)) {
                   1152: 	my $idlist=join('&',@ids);
                   1153: 	$idlist=~tr/A-Z/a-z/; 
                   1154: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1155: 	my @answer=();
                   1156: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1157: 	    @answer=split(/\&/,$reply);
                   1158: 	}                    ;
                   1159: 	my $i;
                   1160: 	for ($i=0;$i<=$#ids;$i++) {
                   1161: 	    if ($answer[$i]) {
                   1162: 		$returnhash{$ids[$i]}=$answer[$i];
                   1163: 	    } 
                   1164: 	}
                   1165:     } 
1.70      www      1166:     return %returnhash;
                   1167: }
                   1168: 
                   1169: # ------------------------------------- Find the IDs behind a list of usernames
                   1170: 
                   1171: sub idrget {
                   1172:     my ($udom,@unames)=@_;
                   1173:     my %returnhash=();
1.800     albertel 1174:     foreach my $uname (@unames) {
                   1175:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1176:     }
1.70      www      1177:     return %returnhash;
                   1178: }
                   1179: 
                   1180: # ------------------------------- Store away a list of names and associated IDs
                   1181: 
                   1182: sub idput {
                   1183:     my ($udom,%ids)=@_;
                   1184:     my %servers=();
1.800     albertel 1185:     foreach my $uname (keys(%ids)) {
                   1186: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1187:         my $uhom=&homeserver($uname,$udom);
1.70      www      1188:         if ($uhom ne 'no_host') {
1.800     albertel 1189:             my $id=&escape($ids{$uname});
1.70      www      1190:             $id=~tr/A-Z/a-z/;
1.800     albertel 1191:             my $esc_unam=&escape($uname);
1.70      www      1192: 	    if ($servers{$uhom}) {
1.800     albertel 1193: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1194:             } else {
1.800     albertel 1195:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1196:             }
                   1197:         }
1.191     harris41 1198:     }
1.800     albertel 1199:     foreach my $server (keys(%servers)) {
                   1200:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1201:     }
1.344     www      1202: }
                   1203: 
1.1023    raeburn  1204: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1205: sub dump_dom {
1.1023    raeburn  1206:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1207:     if (!$udom) {
                   1208:         $udom=$env{'user.domain'};
                   1209:     }
                   1210:     my %returnhash;
1.1023    raeburn  1211:     if ($udom) {
                   1212:         my $uname = &get_domainconfiguser($udom);
                   1213:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1214:     }
                   1215:     return %returnhash;
                   1216: }
                   1217: 
1.1023    raeburn  1218: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1219: 
                   1220: sub get_dom {
1.860     raeburn  1221:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1222:     my $items='';
                   1223:     foreach my $item (@$storearr) {
                   1224:         $items.=&escape($item).'&';
                   1225:     }
                   1226:     $items=~s/\&$//;
1.860     raeburn  1227:     if (!$udom) {
                   1228:         $udom=$env{'user.domain'};
                   1229:         if (defined(&domain($udom,'primary'))) {
                   1230:             $uhome=&domain($udom,'primary');
                   1231:         } else {
1.874     albertel 1232:             undef($uhome);
1.860     raeburn  1233:         }
                   1234:     } else {
                   1235:         if (!$uhome) {
                   1236:             if (defined(&domain($udom,'primary'))) {
                   1237:                 $uhome=&domain($udom,'primary');
                   1238:             }
                   1239:         }
                   1240:     }
                   1241:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1242:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1243:         my %returnhash;
1.875     albertel 1244:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1245:             return %returnhash;
                   1246:         }
1.806     raeburn  1247:         my @pairs=split(/\&/,$rep);
                   1248:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1249:             return @pairs;
                   1250:         }
                   1251:         my $i=0;
                   1252:         foreach my $item (@$storearr) {
                   1253:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1254:             $i++;
                   1255:         }
                   1256:         return %returnhash;
                   1257:     } else {
1.880     banghart 1258:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1259:     }
                   1260: }
                   1261: 
                   1262: # -------------------------------------------- put items in domain db files 
                   1263: 
                   1264: sub put_dom {
1.860     raeburn  1265:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1266:     if (!$udom) {
                   1267:         $udom=$env{'user.domain'};
                   1268:         if (defined(&domain($udom,'primary'))) {
                   1269:             $uhome=&domain($udom,'primary');
                   1270:         } else {
1.874     albertel 1271:             undef($uhome);
1.860     raeburn  1272:         }
                   1273:     } else {
                   1274:         if (!$uhome) {
                   1275:             if (defined(&domain($udom,'primary'))) {
                   1276:                 $uhome=&domain($udom,'primary');
                   1277:             }
                   1278:         }
                   1279:     } 
                   1280:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1281:         my $items='';
                   1282:         foreach my $item (keys(%$storehash)) {
                   1283:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1284:         }
                   1285:         $items=~s/\&$//;
                   1286:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1287:     } else {
1.860     raeburn  1288:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1289:     }
                   1290: }
                   1291: 
1.1023    raeburn  1292: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1293: sub newput_dom {
1.1023    raeburn  1294:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1295:     my $result;
                   1296:     if (!$udom) {
                   1297:         $udom=$env{'user.domain'};
                   1298:     }
1.1023    raeburn  1299:     if ($udom) {
                   1300:         my $uname = &get_domainconfiguser($udom);
                   1301:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1302:     }
                   1303:     return $result;
                   1304: }
                   1305: 
1.1023    raeburn  1306: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1307: sub del_dom {
1.1023    raeburn  1308:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1309:     if (ref($storearr) eq 'ARRAY') {
                   1310:         if (!$udom) {
                   1311:             $udom=$env{'user.domain'};
                   1312:         }
1.1023    raeburn  1313:         if ($udom) {
                   1314:             my $uname = &get_domainconfiguser($udom); 
                   1315:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1316:         }
                   1317:     }
                   1318: }
                   1319: 
1.1023    raeburn  1320: # ----------------------------------construct domainconfig user for a domain 
                   1321: sub get_domainconfiguser {
                   1322:     my ($udom) = @_;
                   1323:     return $udom.'-domainconfig';
                   1324: }
                   1325: 
1.837     raeburn  1326: sub retrieve_inst_usertypes {
                   1327:     my ($udom) = @_;
                   1328:     my (%returnhash,@order);
1.989     raeburn  1329:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1330:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1331:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1332:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1333:         @order = @{$domdefs{'inststatusorder'}};
                   1334:     } else {
                   1335:         if (defined(&domain($udom,'primary'))) {
                   1336:             my $uhome=&domain($udom,'primary');
                   1337:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1338:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1339:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1340:                 return (\%returnhash,\@order);
                   1341:             }
                   1342:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1343:             my @pairs=split(/\&/,$hashitems);
                   1344:             foreach my $item (@pairs) {
                   1345:                 my ($key,$value)=split(/=/,$item,2);
                   1346:                 $key = &unescape($key);
                   1347:                 next if ($key =~ /^error: 2 /);
                   1348:                 $returnhash{$key}=&thaw_unescape($value);
                   1349:             }
                   1350:             my @esc_order = split(/\&/,$orderitems);
                   1351:             foreach my $item (@esc_order) {
                   1352:                 push(@order,&unescape($item));
                   1353:             }
                   1354:         } else {
                   1355:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1356:         }
                   1357:     }
                   1358:     return (\%returnhash,\@order);
                   1359: }
                   1360: 
1.868     raeburn  1361: sub is_domainimage {
                   1362:     my ($url) = @_;
                   1363:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1364:         if (&domain($1) ne '') {
                   1365:             return '1';
                   1366:         }
                   1367:     }
                   1368:     return;
                   1369: }
                   1370: 
1.899     raeburn  1371: sub inst_directory_query {
                   1372:     my ($srch) = @_;
                   1373:     my $udom = $srch->{'srchdomain'};
                   1374:     my %results;
                   1375:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1376:     my $outcome;
1.899     raeburn  1377:     if ($homeserver ne '') {
1.904     albertel 1378: 	my $queryid=&reply("querysend:instdirsearch:".
                   1379: 			   &escape($srch->{'srchby'}).':'.
                   1380: 			   &escape($srch->{'srchterm'}).':'.
                   1381: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1382: 	my $host=&hostname($homeserver);
                   1383: 	if ($queryid !~/^\Q$host\E\_/) {
                   1384: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1385: 	    return;
                   1386: 	}
                   1387: 	my $response = &get_query_reply($queryid);
                   1388: 	my $maxtries = 5;
                   1389: 	my $tries = 1;
                   1390: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1391: 	    $response = &get_query_reply($queryid);
                   1392: 	    $tries ++;
                   1393: 	}
                   1394: 
                   1395:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1396:             if ($response eq 'unavailable') {
                   1397:                 $outcome = $response;
                   1398:             } else {
                   1399:                 $outcome = 'ok';
                   1400:                 my @matches = split(/\n/,$response);
                   1401:                 foreach my $match (@matches) {
                   1402:                     my ($key,$value) = split(/=/,$match);
                   1403:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1404:                 }
1.899     raeburn  1405:             }
                   1406:         }
                   1407:     }
1.909     raeburn  1408:     return ($outcome,%results);
1.899     raeburn  1409: }
                   1410: 
                   1411: sub usersearch {
                   1412:     my ($srch) = @_;
                   1413:     my $dom = $srch->{'srchdomain'};
                   1414:     my %results;
                   1415:     my %libserv = &all_library();
                   1416:     my $query = 'usersearch';
                   1417:     foreach my $tryserver (keys(%libserv)) {
                   1418:         if (&host_domain($tryserver) eq $dom) {
                   1419:             my $host=&hostname($tryserver);
                   1420:             my $queryid=
1.911     raeburn  1421:                 &reply("querysend:".&escape($query).':'.
                   1422:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1423:                        &escape($srch->{'srchtype'}).':'.
                   1424:                        &escape($srch->{'srchterm'}),$tryserver);
                   1425:             if ($queryid !~/^\Q$host\E\_/) {
                   1426:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1427:                 next;
1.899     raeburn  1428:             }
                   1429:             my $reply = &get_query_reply($queryid);
                   1430:             my $maxtries = 1;
                   1431:             my $tries = 1;
                   1432:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1433:                 $reply = &get_query_reply($queryid);
                   1434:                 $tries ++;
                   1435:             }
                   1436:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1437:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1438:             } else {
1.911     raeburn  1439:                 my @matches;
                   1440:                 if ($reply =~ /\n/) {
                   1441:                     @matches = split(/\n/,$reply);
                   1442:                 } else {
                   1443:                     @matches = split(/\&/,$reply);
                   1444:                 }
1.899     raeburn  1445:                 foreach my $match (@matches) {
                   1446:                     my ($uname,$udom,%userhash);
1.911     raeburn  1447:                     foreach my $entry (split(/:/,$match)) {
                   1448:                         my ($key,$value) =
                   1449:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1450:                         $userhash{$key} = $value;
                   1451:                         if ($key eq 'username') {
                   1452:                             $uname = $value;
                   1453:                         } elsif ($key eq 'domain') {
                   1454:                             $udom = $value;
1.911     raeburn  1455:                         }
1.899     raeburn  1456:                     }
                   1457:                     $results{$uname.':'.$udom} = \%userhash;
                   1458:                 }
                   1459:             }
                   1460:         }
                   1461:     }
                   1462:     return %results;
                   1463: }
                   1464: 
1.912     raeburn  1465: sub get_instuser {
                   1466:     my ($udom,$uname,$id) = @_;
                   1467:     my $homeserver = &domain($udom,'primary');
                   1468:     my ($outcome,%results);
                   1469:     if ($homeserver ne '') {
                   1470:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1471:                            &escape($id).':'.&escape($udom),$homeserver);
                   1472:         my $host=&hostname($homeserver);
                   1473:         if ($queryid !~/^\Q$host\E\_/) {
                   1474:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1475:             return;
                   1476:         }
                   1477:         my $response = &get_query_reply($queryid);
                   1478:         my $maxtries = 5;
                   1479:         my $tries = 1;
                   1480:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1481:             $response = &get_query_reply($queryid);
                   1482:             $tries ++;
                   1483:         }
                   1484:         if (!&error($response) && $response ne 'refused') {
                   1485:             if ($response eq 'unavailable') {
                   1486:                 $outcome = $response;
                   1487:             } else {
                   1488:                 $outcome = 'ok';
                   1489:                 my @matches = split(/\n/,$response);
                   1490:                 foreach my $match (@matches) {
                   1491:                     my ($key,$value) = split(/=/,$match);
                   1492:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1493:                 }
                   1494:             }
                   1495:         }
                   1496:     }
                   1497:     my %userinfo;
                   1498:     if (ref($results{$uname}) eq 'HASH') {
                   1499:         %userinfo = %{$results{$uname}};
                   1500:     } 
                   1501:     return ($outcome,%userinfo);
                   1502: }
                   1503: 
                   1504: sub inst_rulecheck {
1.923     raeburn  1505:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1506:     my %returnhash;
                   1507:     if ($udom ne '') {
                   1508:         if (ref($rules) eq 'ARRAY') {
                   1509:             @{$rules} = map {&escape($_);} (@{$rules});
                   1510:             my $rulestr = join(':',@{$rules});
                   1511:             my $homeserver=&domain($udom,'primary');
                   1512:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1513:                 my $response;
                   1514:                 if ($item eq 'username') {                
                   1515:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1516:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1517:                                               $homeserver));
1.923     raeburn  1518:                 } elsif ($item eq 'id') {
                   1519:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1520:                                               ':'.&escape($id).':'.$rulestr,
                   1521:                                               $homeserver));
1.945     raeburn  1522:                 } elsif ($item eq 'selfcreate') {
                   1523:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1524:                                                &escape($udom).':'.&escape($uname).
                   1525:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1526:                 }
1.912     raeburn  1527:                 if ($response ne 'refused') {
                   1528:                     my @pairs=split(/\&/,$response);
                   1529:                     foreach my $item (@pairs) {
                   1530:                         my ($key,$value)=split(/=/,$item,2);
                   1531:                         $key = &unescape($key);
                   1532:                         next if ($key =~ /^error: 2 /);
                   1533:                         $returnhash{$key}=&thaw_unescape($value);
                   1534:                     }
                   1535:                 }
                   1536:             }
                   1537:         }
                   1538:     }
                   1539:     return %returnhash;
                   1540: }
                   1541: 
                   1542: sub inst_userrules {
1.923     raeburn  1543:     my ($udom,$check) = @_;
1.912     raeburn  1544:     my (%ruleshash,@ruleorder);
                   1545:     if ($udom ne '') {
                   1546:         my $homeserver=&domain($udom,'primary');
                   1547:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1548:             my $response;
                   1549:             if ($check eq 'id') {
                   1550:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1551:                                  $homeserver);
1.943     raeburn  1552:             } elsif ($check eq 'email') {
                   1553:                 $response=&reply('instemailrules:'.&escape($udom),
                   1554:                                  $homeserver);
1.923     raeburn  1555:             } else {
                   1556:                 $response=&reply('instuserrules:'.&escape($udom),
                   1557:                                  $homeserver);
                   1558:             }
1.912     raeburn  1559:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1560:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1561:                 ($response ne 'no_such_host')) {
                   1562:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1563:                 my @pairs=split(/\&/,$hashitems);
                   1564:                 foreach my $item (@pairs) {
                   1565:                     my ($key,$value)=split(/=/,$item,2);
                   1566:                     $key = &unescape($key);
                   1567:                     next if ($key =~ /^error: 2 /);
                   1568:                     $ruleshash{$key}=&thaw_unescape($value);
                   1569:                 }
                   1570:                 my @esc_order = split(/\&/,$orderitems);
                   1571:                 foreach my $item (@esc_order) {
                   1572:                     push(@ruleorder,&unescape($item));
                   1573:                 }
                   1574:             }
                   1575:         }
                   1576:     }
                   1577:     return (\%ruleshash,\@ruleorder);
                   1578: }
                   1579: 
1.976     raeburn  1580: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1581: 
                   1582: sub get_domain_defaults {
                   1583:     my ($domain) = @_;
                   1584:     my $cachetime = 60*60*24;
                   1585:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1586:     if (defined($cached)) {
                   1587:         if (ref($result) eq 'HASH') {
                   1588:             return %{$result};
                   1589:         }
                   1590:     }
                   1591:     my %domdefaults;
                   1592:     my %domconfig =
1.989     raeburn  1593:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1594:                                   'requestcourses','inststatus',
1.1073    raeburn  1595:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1596:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1597:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1598:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1599:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1600:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1601:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1602:     } else {
                   1603:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1604:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1605:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1606:     }
1.976     raeburn  1607:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1608:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1609:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1610:         } else {
                   1611:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1612:         } 
                   1613:         my @usertools = ('aboutme','blog','portfolio');
                   1614:         foreach my $item (@usertools) {
                   1615:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1616:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1617:             }
                   1618:         }
                   1619:     }
1.985     raeburn  1620:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1621:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1622:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1623:         }
                   1624:     }
1.989     raeburn  1625:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1626:         foreach my $item ('inststatustypes','inststatusorder') {
                   1627:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1628:         }
                   1629:     }
1.1047    raeburn  1630:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1631:         foreach my $item ('canuse_pdfforms') {
                   1632:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1633:         }
                   1634:     }
1.1073    raeburn  1635:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1636:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1637:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1638:         }
                   1639:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1640:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1641:         }
                   1642:     }
1.943     raeburn  1643:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1644:                                   $cachetime);
                   1645:     return %domdefaults;
                   1646: }
                   1647: 
1.344     www      1648: # --------------------------------------------------- Assign a key to a student
                   1649: 
                   1650: sub assign_access_key {
1.364     www      1651: #
                   1652: # a valid key looks like uname:udom#comments
                   1653: # comments are being appended
                   1654: #
1.498     www      1655:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1656:     $kdom=
1.620     albertel 1657:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1658:     $knum=
1.620     albertel 1659:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1660:     $cdom=
1.620     albertel 1661:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1662:     $cnum=
1.620     albertel 1663:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1664:     $udom=$env{'user.name'} unless (defined($udom));
                   1665:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1666:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1667:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1668:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1669:                                                   # assigned to this person
                   1670:                                                   # - this should not happen,
1.345     www      1671:                                                   # unless something went wrong
                   1672:                                                   # the first time around
                   1673: # ready to assign
1.364     www      1674:         $logentry=$1.'; '.$logentry;
1.496     www      1675:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1676:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1677: # key now belongs to user
1.346     www      1678: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1679:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1680:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1681:                 return 'ok';
                   1682:             } else {
                   1683:                 return 
                   1684:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1685: 	    }
                   1686:         } else {
                   1687:             return 'error: Could not assign key, try again later.';
                   1688:         }
1.364     www      1689:     } elsif (!$existing{$ckey}) {
1.345     www      1690: # the key does not exist
                   1691: 	return 'error: The key does not exist';
                   1692:     } else {
                   1693: # the key is somebody else's
                   1694: 	return 'error: The key is already in use';
                   1695:     }
1.344     www      1696: }
                   1697: 
1.364     www      1698: # ------------------------------------------ put an additional comment on a key
                   1699: 
                   1700: sub comment_access_key {
                   1701: #
                   1702: # a valid key looks like uname:udom#comments
                   1703: # comments are being appended
                   1704: #
                   1705:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1706:     $cdom=
1.620     albertel 1707:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1708:     $cnum=
1.620     albertel 1709:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1710:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1711:     if ($existing{$ckey}) {
                   1712:         $existing{$ckey}.='; '.$logentry;
                   1713: # ready to assign
1.367     www      1714:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1715:                                                  $cdom,$cnum) eq 'ok') {
                   1716: 	    return 'ok';
                   1717:         } else {
                   1718: 	    return 'error: Count not store comment.';
                   1719:         }
                   1720:     } else {
                   1721: # the key does not exist
                   1722: 	return 'error: The key does not exist';
                   1723:     }
                   1724: }
                   1725: 
1.344     www      1726: # ------------------------------------------------------ Generate a set of keys
                   1727: 
                   1728: sub generate_access_keys {
1.364     www      1729:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1730:     $cdom=
1.620     albertel 1731:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1732:     $cnum=
1.620     albertel 1733:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1734:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1735:     unless (($cdom) && ($cnum)) { return 0; }
                   1736:     if ($number>10000) { return 0; }
                   1737:     sleep(2); # make sure don't get same seed twice
                   1738:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1739:     my $total=0;
                   1740:     for (my $i=1;$i<=$number;$i++) {
                   1741:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1742:                   sprintf("%lx",int(100000*rand)).'-'.
                   1743:                   sprintf("%lx",int(100000*rand));
                   1744:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1745:        $newkey=~s/0/h/g; # and also 0 and O
                   1746:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1747:        if ($existing{$newkey}) {
                   1748:            $i--;
                   1749:        } else {
1.364     www      1750: 	  if (&put('accesskeys',
                   1751:               { $newkey => '# generated '.localtime().
1.620     albertel 1752:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1753:                            '; '.$logentry },
                   1754: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1755:               $total++;
                   1756: 	  }
                   1757:        }
                   1758:     }
1.620     albertel 1759:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1760:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1761:     return $total;
                   1762: }
                   1763: 
                   1764: # ------------------------------------------------------- Validate an accesskey
                   1765: 
                   1766: sub validate_access_key {
                   1767:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1768:     $cdom=
1.620     albertel 1769:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1770:     $cnum=
1.620     albertel 1771:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1772:     $udom=$env{'user.domain'} unless (defined($udom));
                   1773:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1774:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1775:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1776: }
                   1777: 
                   1778: # ------------------------------------- Find the section of student in a course
1.652     albertel 1779: sub devalidate_getsection_cache {
                   1780:     my ($udom,$unam,$courseid)=@_;
                   1781:     my $hashid="$udom:$unam:$courseid";
                   1782:     &devalidate_cache_new('getsection',$hashid);
                   1783: }
1.298     matthew  1784: 
1.815     albertel 1785: sub courseid_to_courseurl {
                   1786:     my ($courseid) = @_;
                   1787:     #already url style courseid
                   1788:     return $courseid if ($courseid =~ m{^/});
                   1789: 
                   1790:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1791: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1792: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1793: 	return "/$cdom/$cnum";
                   1794:     }
                   1795: 
                   1796:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1797:     if (exists($courseinfo{'num'})) {
                   1798: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1799:     }
                   1800: 
                   1801:     return undef;
                   1802: }
                   1803: 
1.298     matthew  1804: sub getsection {
                   1805:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1806:     my $cachetime=1800;
1.551     albertel 1807: 
                   1808:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1809:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1810:     if (defined($cached)) { return $result; }
                   1811: 
1.298     matthew  1812:     my %Pending; 
                   1813:     my %Expired;
                   1814:     #
                   1815:     # Each role can either have not started yet (pending), be active, 
                   1816:     #    or have expired.
                   1817:     #
                   1818:     # If there is an active role, we are done.
                   1819:     #
                   1820:     # If there is more than one role which has not started yet, 
                   1821:     #     choose the one which will start sooner
                   1822:     # If there is one role which has not started yet, return it.
                   1823:     #
                   1824:     # If there is more than one expired role, choose the one which ended last.
                   1825:     # If there is a role which has expired, return it.
                   1826:     #
1.815     albertel 1827:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1828:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1829:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1830:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1831:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1832:         my $section=$1;
                   1833:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1834:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1835:         my $now=time;
1.548     albertel 1836:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1837:             $Expired{$end}=$section;
                   1838:             next;
                   1839:         }
1.548     albertel 1840:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1841:             $Pending{$start}=$section;
                   1842:             next;
                   1843:         }
1.599     albertel 1844:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1845:     }
                   1846:     #
                   1847:     # Presumedly there will be few matching roles from the above
                   1848:     # loop and the sorting time will be negligible.
                   1849:     if (scalar(keys(%Pending))) {
                   1850:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1851:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1852:     } 
                   1853:     if (scalar(keys(%Expired))) {
                   1854:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1855:         my $time = pop(@sorted);
1.599     albertel 1856:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1857:     }
1.599     albertel 1858:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1859: }
1.70      www      1860: 
1.599     albertel 1861: sub save_cache {
                   1862:     &purge_remembered();
1.722     albertel 1863:     #&Apache::loncommon::validate_page();
1.620     albertel 1864:     undef(%env);
1.780     albertel 1865:     undef($env_loaded);
1.599     albertel 1866: }
1.452     albertel 1867: 
1.599     albertel 1868: my $to_remember=-1;
                   1869: my %remembered;
                   1870: my %accessed;
                   1871: my $kicks=0;
                   1872: my $hits=0;
1.849     albertel 1873: sub make_key {
                   1874:     my ($name,$id) = @_;
1.872     albertel 1875:     if (length($id) > 65 
                   1876: 	&& length(&escape($id)) > 200) {
                   1877: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1878:     }
1.849     albertel 1879:     return &escape($name.':'.$id);
                   1880: }
                   1881: 
1.599     albertel 1882: sub devalidate_cache_new {
                   1883:     my ($name,$id,$debug) = @_;
                   1884:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1885:     $id=&make_key($name,$id);
1.599     albertel 1886:     $memcache->delete($id);
                   1887:     delete($remembered{$id});
                   1888:     delete($accessed{$id});
                   1889: }
                   1890: 
                   1891: sub is_cached_new {
                   1892:     my ($name,$id,$debug) = @_;
1.849     albertel 1893:     $id=&make_key($name,$id);
1.599     albertel 1894:     if (exists($remembered{$id})) {
                   1895: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1896: 	$accessed{$id}=[&gettimeofday()];
                   1897: 	$hits++;
                   1898: 	return ($remembered{$id},1);
                   1899:     }
                   1900:     my $value = $memcache->get($id);
                   1901:     if (!(defined($value))) {
                   1902: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1903: 	return (undef,undef);
1.416     albertel 1904:     }
1.599     albertel 1905:     if ($value eq '__undef__') {
                   1906: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1907: 	$value=undef;
                   1908:     }
                   1909:     &make_room($id,$value,$debug);
                   1910:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1911:     return ($value,1);
                   1912: }
                   1913: 
                   1914: sub do_cache_new {
                   1915:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1916:     $id=&make_key($name,$id);
1.599     albertel 1917:     my $setvalue=$value;
                   1918:     if (!defined($setvalue)) {
                   1919: 	$setvalue='__undef__';
                   1920:     }
1.623     albertel 1921:     if (!defined($time) ) {
                   1922: 	$time=600;
                   1923:     }
1.599     albertel 1924:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1925:     my $result = $memcache->set($id,$setvalue,$time);
                   1926:     if (! $result) {
1.872     albertel 1927: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1928: 	$memcache->disconnect_all();
1.872     albertel 1929:     }
1.600     albertel 1930:     # need to make a copy of $value
1.919     albertel 1931:     &make_room($id,$value,$debug);
1.599     albertel 1932:     return $value;
                   1933: }
                   1934: 
                   1935: sub make_room {
                   1936:     my ($id,$value,$debug)=@_;
1.919     albertel 1937: 
                   1938:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1939:                                     : $value;
1.599     albertel 1940:     if ($to_remember<0) { return; }
                   1941:     $accessed{$id}=[&gettimeofday()];
                   1942:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1943:     my $to_kick;
                   1944:     my $max_time=0;
                   1945:     foreach my $other (keys(%accessed)) {
                   1946: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1947: 	    $to_kick=$other;
                   1948: 	    $max_time=&tv_interval($accessed{$other});
                   1949: 	}
                   1950:     }
                   1951:     delete($remembered{$to_kick});
                   1952:     delete($accessed{$to_kick});
                   1953:     $kicks++;
                   1954:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1955:     return;
                   1956: }
                   1957: 
1.599     albertel 1958: sub purge_remembered {
1.604     albertel 1959:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1960:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1961:     undef(%remembered);
                   1962:     undef(%accessed);
1.428     albertel 1963: }
1.70      www      1964: # ------------------------------------- Read an entry from a user's environment
                   1965: 
                   1966: sub userenvironment {
                   1967:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1968:     my $items;
                   1969:     foreach my $item (@what) {
                   1970:         $items.=&escape($item).'&';
                   1971:     }
                   1972:     $items=~s/\&$//;
1.70      www      1973:     my %returnhash=();
1.1009    raeburn  1974:     my $uhome = &homeserver($unam,$udom);
                   1975:     unless ($uhome eq 'no_host') {
                   1976:         my @answer=split(/\&/, 
                   1977:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1978:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1979:             return %returnhash;
                   1980:         }
1.1009    raeburn  1981:         my $i;
                   1982:         for ($i=0;$i<=$#what;$i++) {
                   1983: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1984:         }
1.70      www      1985:     }
                   1986:     return %returnhash;
1.1       albertel 1987: }
                   1988: 
1.617     albertel 1989: # ---------------------------------------------------------- Get a studentphoto
                   1990: sub studentphoto {
                   1991:     my ($udom,$unam,$ext) = @_;
                   1992:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1993:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1994:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1995:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1996:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1997:             } else {
                   1998:                 my ($result,$perm_reqd)=
1.707     albertel 1999: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2000:                 if ($result eq 'ok') {
                   2001:                     if (!($perm_reqd eq 'yes')) {
                   2002:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2003:                     }
                   2004:                 }
                   2005:             }
                   2006:         }
                   2007:     } else {
                   2008:         my ($result,$perm_reqd) = 
1.707     albertel 2009: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2010:         if ($result eq 'ok') {
                   2011:             if (!($perm_reqd eq 'yes')) {
                   2012:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2013:             }
                   2014:         }
                   2015:     }
                   2016:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2017: }
                   2018: 
                   2019: sub retrievestudentphoto {
                   2020:     my ($udom,$unam,$ext,$type) = @_;
                   2021:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2022:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2023:     if ($ret eq 'ok') {
                   2024:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2025:         if ($type eq 'thumbnail') {
                   2026:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2027:         }
                   2028:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2029:         return $tokenurl;
                   2030:     } else {
                   2031:         if ($type eq 'thumbnail') {
                   2032:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2033:         } else { 
                   2034:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2035:         }
1.617     albertel 2036:     }
                   2037: }
                   2038: 
1.263     www      2039: # -------------------------------------------------------------------- New chat
                   2040: 
                   2041: sub chatsend {
1.724     raeburn  2042:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2043:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2044:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2045:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2046:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2047: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2048: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2049: }
                   2050: 
                   2051: # ------------------------------------------ Find current version of a resource
                   2052: 
                   2053: sub getversion {
                   2054:     my $fname=&clutter(shift);
                   2055:     unless ($fname=~/^\/res\//) { return -1; }
                   2056:     return &currentversion(&filelocation('',$fname));
                   2057: }
                   2058: 
                   2059: sub currentversion {
                   2060:     my $fname=shift;
                   2061:     my $author=$fname;
                   2062:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2063:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2064:     my $home=&homeserver($uname,$udom);
1.292     www      2065:     if ($home eq 'no_host') { 
                   2066:         return -1; 
                   2067:     }
1.1112    www      2068:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2069:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2070: 	return -1;
                   2071:     }
1.1112    www      2072:     return $answer;
1.263     www      2073: }
                   2074: 
1.1111    www      2075: #
                   2076: # Return special version number of resource if set by override, empty otherwise
                   2077: #
                   2078: sub usedversion {
                   2079:     my $fname=shift;
                   2080:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2081:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2082:     if ($urlversion) { return $urlversion; }
                   2083:     return '';
                   2084: }
                   2085: 
1.1       albertel 2086: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2087: 
1.1       albertel 2088: sub subscribe {
                   2089:     my $fname=shift;
1.761     raeburn  2090:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2091:     $fname=~s/[\n\r]//g;
1.1       albertel 2092:     my $author=$fname;
                   2093:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2094:     my ($udom,$uname)=split(/\//,$author);
                   2095:     my $home=homeserver($uname,$udom);
1.335     albertel 2096:     if ($home eq 'no_host') {
                   2097:         return 'not_found';
1.1       albertel 2098:     }
                   2099:     my $answer=reply("sub:$fname",$home);
1.64      www      2100:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2101: 	$answer.=' by '.$home;
                   2102:     }
1.1       albertel 2103:     return $answer;
                   2104: }
                   2105:     
1.8       www      2106: # -------------------------------------------------------------- Replicate file
                   2107: 
                   2108: sub repcopy {
                   2109:     my $filename=shift;
1.23      www      2110:     $filename=~s/\/+/\//g;
1.607     raeburn  2111:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2112:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2113:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2114: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2115: 	return &repcopy_userfile($filename);
                   2116:     }
1.532     albertel 2117:     $filename=~s/[\n\r]//g;
1.8       www      2118:     my $transname="$filename.in.transfer";
1.828     www      2119: # FIXME: this should flock
1.607     raeburn  2120:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2121:     my $remoteurl=subscribe($filename);
1.64      www      2122:     if ($remoteurl =~ /^con_lost by/) {
                   2123: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2124:            return 'unavailable';
1.8       www      2125:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2126: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2127: 	   return 'not_found';
1.64      www      2128:     } elsif ($remoteurl =~ /^rejected by/) {
                   2129: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2130:            return 'forbidden';
1.20      www      2131:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2132:            return 'ok';
1.8       www      2133:     } else {
1.290     www      2134:         my $author=$filename;
                   2135:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2136:         my ($udom,$uname)=split(/\//,$author);
                   2137:         my $home=homeserver($uname,$udom);
                   2138:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2139:            my @parts=split(/\//,$filename);
                   2140:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2141:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2142:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2143: 	       return 'bad_request';
1.8       www      2144:            }
                   2145:            my $count;
                   2146:            for ($count=5;$count<$#parts;$count++) {
                   2147:                $path.="/$parts[$count]";
                   2148:                if ((-e $path)!=1) {
                   2149: 		   mkdir($path,0777);
                   2150:                }
                   2151:            }
                   2152:            my $ua=new LWP::UserAgent;
                   2153:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2154:            my $response=$ua->request($request,$transname);
                   2155:            if ($response->is_error()) {
                   2156: 	       unlink($transname);
                   2157:                my $message=$response->status_line;
1.672     albertel 2158:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2159:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2160:                return 'unavailable';
1.8       www      2161:            } else {
1.16      www      2162: 	       if ($remoteurl!~/\.meta$/) {
                   2163:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2164:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2165:                   if ($mresponse->is_error()) {
                   2166: 		      unlink($filename.'.meta');
                   2167:                       &logthis(
1.672     albertel 2168:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2169:                   }
                   2170: 	       }
1.8       www      2171:                rename($transname,$filename);
1.607     raeburn  2172:                return 'ok';
1.8       www      2173:            }
1.290     www      2174:        }
1.8       www      2175:     }
1.330     www      2176: }
                   2177: 
                   2178: # ------------------------------------------------ Get server side include body
                   2179: sub ssi_body {
1.381     albertel 2180:     my ($filelink,%form)=@_;
1.606     matthew  2181:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2182:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2183:     }
1.953     www      2184:     my $output='';
                   2185:     my $response;
1.980     raeburn  2186:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2187:        ($output,$response)=&externalssi($filelink);
1.953     www      2188:     } else {
1.1004    droeschl 2189:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2190:        $filelink .= 'inhibitmenu=yes';
1.953     www      2191:        ($output,$response)=&ssi($filelink,%form);
                   2192:     }
1.778     albertel 2193:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2194:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2195:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2196:     if (wantarray) {
                   2197:         return ($output, $response);
                   2198:     } else {
                   2199:         return $output;
                   2200:     }
1.8       www      2201: }
                   2202: 
1.15      www      2203: # --------------------------------------------------------- Server Side Include
                   2204: 
1.782     albertel 2205: sub absolute_url {
                   2206:     my ($host_name) = @_;
                   2207:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2208:     if ($host_name eq '') {
                   2209: 	$host_name = $ENV{'SERVER_NAME'};
                   2210:     }
                   2211:     return $protocol.$host_name;
                   2212: }
                   2213: 
1.942     foxr     2214: #
                   2215: #   Server side include.
                   2216: # Parameters:
                   2217: #  fn     Possibly encrypted resource name/id.
                   2218: #  form   Hash that describes how the rendering should be done
                   2219: #         and other things.
1.944     foxr     2220: # Returns:
1.950     raeburn  2221: #   Scalar context: The content of the response.
                   2222: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2223: #     
1.15      www      2224: sub ssi {
                   2225: 
1.944     foxr     2226:     my ($fn,%form)=@_;
1.15      www      2227:     my $ua=new LWP::UserAgent;
1.23      www      2228:     my $request;
1.711     albertel 2229: 
                   2230:     $form{'no_update_last_known'}=1;
1.895     albertel 2231:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2232:     if (%form) {
1.782     albertel 2233:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2234:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2235:     } else {
1.782     albertel 2236:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2237:     }
                   2238: 
1.15      www      2239:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2240:     my $response=$ua->request($request);
                   2241: 
1.944     foxr     2242:     if (wantarray) {
                   2243: 	return ($response->content, $response);
                   2244:     } else {
                   2245: 	return $response->content;
1.942     foxr     2246:     }
1.324     www      2247: }
                   2248: 
                   2249: sub externalssi {
                   2250:     my ($url)=@_;
                   2251:     my $ua=new LWP::UserAgent;
                   2252:     my $request=new HTTP::Request('GET',$url);
                   2253:     my $response=$ua->request($request);
1.954     raeburn  2254:     if (wantarray) {
                   2255:         return ($response->content, $response);
                   2256:     } else {
                   2257:         return $response->content;
                   2258:     }
1.15      www      2259: }
1.254     www      2260: 
1.492     albertel 2261: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2262: 
                   2263: sub allowuploaded {
                   2264:     my ($srcurl,$url)=@_;
                   2265:     $url=&clutter(&declutter($url));
                   2266:     my $dir=$url;
                   2267:     $dir=~s/\/[^\/]+$//;
                   2268:     my %httpref=();
                   2269:     my $httpurl=&hreflocation('',$url);
                   2270:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2271:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2272: }
1.477     raeburn  2273: 
1.478     albertel 2274: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2275: # input: action, courseID, current domain, intended
1.637     raeburn  2276: #        path to file, source of file, instruction to parse file for objects,
                   2277: #        ref to hash for embedded objects,
                   2278: #        ref to hash for codebase of java objects.
1.1095    raeburn  2279: #        reference to scalar to accommodate mime type determined
                   2280: #          from File::MMagic if $parser = parse.
1.637     raeburn  2281: #
1.485     raeburn  2282: # output: url to file (if action was uploaddoc), 
                   2283: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2284: #
1.478     albertel 2285: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2286: # course.
1.477     raeburn  2287: #
1.478     albertel 2288: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2289: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2290: #          course's home server.
1.477     raeburn  2291: #
1.478     albertel 2292: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2293: #          be copied from $source (current location) to 
                   2294: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2295: #         and will then be copied to
                   2296: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2297: #         course's home server.
1.485     raeburn  2298: #
1.481     raeburn  2299: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2300: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2301: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2302: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2303: #         in course's home server.
1.637     raeburn  2304: #
1.477     raeburn  2305: 
                   2306: sub process_coursefile {
1.1095    raeburn  2307:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2308:         $mimetype)=@_;
1.477     raeburn  2309:     my $fetchresult;
1.638     albertel 2310:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2311:     if ($action eq 'propagate') {
1.638     albertel 2312:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2313: 			     $home);
1.481     raeburn  2314:     } else {
1.477     raeburn  2315:         my $fpath = '';
                   2316:         my $fname = $file;
1.478     albertel 2317:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2318:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2319:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2320:         if ($action eq 'copy') {
                   2321:             if ($source eq '') {
                   2322:                 $fetchresult = 'no source file';
                   2323:                 return $fetchresult;
                   2324:             } else {
                   2325:                 my $destination = $filepath.'/'.$fname;
                   2326:                 rename($source,$destination);
                   2327:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2328:                                  $home);
1.481     raeburn  2329:             }
                   2330:         } elsif ($action eq 'uploaddoc') {
                   2331:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2332:             print $fh $env{'form.'.$source};
1.481     raeburn  2333:             close($fh);
1.637     raeburn  2334:             if ($parser eq 'parse') {
1.1024    raeburn  2335:                 my $mm = new File::MMagic;
1.1095    raeburn  2336:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2337:                 if ($type eq 'text/html') {
1.1024    raeburn  2338:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2339:                     unless ($parse_result eq 'ok') {
                   2340:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2341:                     }
1.637     raeburn  2342:                 }
1.1095    raeburn  2343:                 if (ref($mimetype)) {
                   2344:                     $$mimetype = $type;
                   2345:                 } 
1.637     raeburn  2346:             }
1.477     raeburn  2347:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2348:                                  $home);
1.481     raeburn  2349:             if ($fetchresult eq 'ok') {
                   2350:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2351:             } else {
                   2352:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2353:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2354:                 return '/adm/notfound.html';
                   2355:             }
1.477     raeburn  2356:         }
                   2357:     }
1.485     raeburn  2358:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2359:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2360:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2361:     }
                   2362:     return $fetchresult;
                   2363: }
                   2364: 
1.637     raeburn  2365: sub build_filepath {
                   2366:     my ($fpath) = @_;
                   2367:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2368:     unless ($fpath eq '') {
                   2369:         my @parts=split('/',$fpath);
                   2370:         foreach my $part (@parts) {
                   2371:             $filepath.= '/'.$part;
                   2372:             if ((-e $filepath)!=1) {
                   2373:                 mkdir($filepath,0777);
                   2374:             }
                   2375:         }
                   2376:     }
                   2377:     return $filepath;
                   2378: }
                   2379: 
                   2380: sub store_edited_file {
1.638     albertel 2381:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2382:     my $file = $primary_url;
                   2383:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2384:     my $fpath = '';
                   2385:     my $fname = $file;
                   2386:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2387:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2388:     my $filepath = &build_filepath($fpath);
                   2389:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2390:     print $fh $content;
                   2391:     close($fh);
1.638     albertel 2392:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2393:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2394: 			  $home);
1.637     raeburn  2395:     if ($$fetchresult eq 'ok') {
                   2396:         return '/uploaded/'.$fpath.'/'.$fname;
                   2397:     } else {
1.638     albertel 2398:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2399: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2400:         return '/adm/notfound.html';
                   2401:     }
                   2402: }
                   2403: 
1.531     albertel 2404: sub clean_filename {
1.831     albertel 2405:     my ($fname,$args)=@_;
1.315     www      2406: # Replace Windows backslashes by forward slashes
1.257     www      2407:     $fname=~s/\\/\//g;
1.831     albertel 2408:     if (!$args->{'keep_path'}) {
                   2409:         # Get rid of everything but the actual filename
                   2410: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2411:     }
1.315     www      2412: # Replace spaces by underscores
                   2413:     $fname=~s/\s+/\_/g;
                   2414: # Replace all other weird characters by nothing
1.831     albertel 2415:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2416: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2417: # numbers
                   2418:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2419:     return $fname;
                   2420: }
1.1051    raeburn  2421: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2422: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2423: # image with the same aspect ratio as the original, but with dimensions which do 
                   2424: # not exceed $resizewidth and $resizeheight.
                   2425:  
1.984     neumanie 2426: sub resizeImage {
1.1051    raeburn  2427:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2428:     my $ima = Image::Magick->new;
                   2429:     my $resized;
                   2430:     if (-e $img_path) {
                   2431:         $ima->Read($img_path);
                   2432:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2433:             my $width = $ima->Get('width');
                   2434:             my $height = $ima->Get('height');
                   2435:             if ($width > $resizewidth) {
                   2436: 	        my $factor = $width/$resizewidth;
                   2437:                 my $newheight = $height/$factor;
                   2438:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2439:                 $resized = 1;
                   2440:             }
                   2441:         }
                   2442:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2443:             my $width = $ima->Get('width');
                   2444:             my $height = $ima->Get('height');
                   2445:             if ($height > $resizeheight) {
                   2446:                 my $factor = $height/$resizeheight;
                   2447:                 my $newwidth = $width/$factor;
                   2448:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2449:                 $resized = 1;
                   2450:             }
                   2451:         }
                   2452:         if ($resized) {
                   2453:             $ima->Write($img_path);
                   2454:         }
                   2455:     }
                   2456:     return;
1.977     amueller 2457: }
                   2458: 
1.608     albertel 2459: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2460: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2461: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2462: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2463: #                                    canceloverwrite, or ''. 
                   2464: #                   if 'coursedoc': upload to the current course
                   2465: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2466: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2467: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2468: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2469: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2470: #        $allfiles - reference to hash for embedded objects
                   2471: #        $codebase - reference to hash for codebase of java objects
                   2472: #        $desuname - username for permanent storage of uploaded file
                   2473: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2474: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2475: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2476: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2477: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2478: #        $mimetype - reference to scalar to accommodate mime type determined
                   2479: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2480: # 
1.686     albertel 2481: # output: url of file in userspace, or error: <message> 
                   2482: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2483: 
1.531     albertel 2484: sub userfileupload {
1.1090    raeburn  2485:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2486:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2487:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2488:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2489:     $fname=&clean_filename($fname);
1.1090    raeburn  2490:     # See if there is anything left
1.257     www      2491:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2492:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2493:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2494:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2495:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2496:         my $now = time;
1.1090    raeburn  2497:         my $filepath;
1.1095    raeburn  2498:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2499:              $filepath = 'tmp/helprequests/'.$now;
                   2500:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2501:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2502:                          '_'.$env{'user.domain'}.'/pending';
                   2503:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2504:             my ($docuname,$docudom);
                   2505:             if ($destudom) {
                   2506:                 $docudom = $destudom;
                   2507:             } else {
                   2508:                 $docudom = $env{'user.domain'};
                   2509:             }
                   2510:             if ($destuname) {
                   2511:                 $docuname = $destuname;
                   2512:             } else {
                   2513:                 $docuname = $env{'user.name'};
                   2514:             }
                   2515:             if (exists($env{'form.group'})) {
                   2516:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2517:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2518:             }
                   2519:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2520:             if ($context eq 'canceloverwrite') {
                   2521:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2522:                 if (-e  $tempfile) {
                   2523:                     my @info = stat($tempfile);
                   2524:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2525:                         unlink($tempfile);
                   2526:                     }
                   2527:                 }
                   2528:                 return;
1.523     raeburn  2529:             }
                   2530:         }
1.1090    raeburn  2531:         # Create the directory if not present
1.741     raeburn  2532:         my @parts=split(/\//,$filepath);
                   2533:         my $fullpath = $perlvar{'lonDaemons'};
                   2534:         for (my $i=0;$i<@parts;$i++) {
                   2535:             $fullpath .= '/'.$parts[$i];
                   2536:             if ((-e $fullpath)!=1) {
                   2537:                 mkdir($fullpath,0777);
                   2538:             }
                   2539:         }
                   2540:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2541:         print $fh $env{'form.'.$formname};
                   2542:         close($fh);
1.1090    raeburn  2543:         if ($context eq 'existingfile') {
                   2544:             my @info = stat($fullpath.'/'.$fname);
                   2545:             return ($fullpath.'/'.$fname,$info[9]);
                   2546:         } else {
                   2547:             return $fullpath.'/'.$fname;
                   2548:         }
1.523     raeburn  2549:     }
1.995     raeburn  2550:     if ($subdir eq 'scantron') {
                   2551:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2552:     } else {
1.995     raeburn  2553:         $fname="$subdir/$fname";
                   2554:     }
1.1090    raeburn  2555:     if ($context eq 'coursedoc') {
1.638     albertel 2556: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2557: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2558:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2559:             return &finishuserfileupload($docuname,$docudom,
                   2560: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2561: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2562:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2563:         } else {
1.620     albertel 2564:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2565:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2566: 				       $fname,$formname,$parser,
1.1095    raeburn  2567: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2568:         }
1.719     banghart 2569:     } elsif (defined($destuname)) {
                   2570:         my $docuname=$destuname;
                   2571:         my $docudom=$destudom;
1.860     raeburn  2572: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2573: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2574:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2575:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2576:     } else {
1.638     albertel 2577:         my $docuname=$env{'user.name'};
                   2578:         my $docudom=$env{'user.domain'};
1.714     raeburn  2579:         if (exists($env{'form.group'})) {
                   2580:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2581:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2582:         }
1.860     raeburn  2583: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2584: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2585:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2586:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2587:     }
1.271     www      2588: }
                   2589: 
                   2590: sub finishuserfileupload {
1.860     raeburn  2591:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2592:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2593:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2594:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2595:   
1.860     raeburn  2596:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2597:     $file=$fname;
                   2598:     if ($fname=~m|/|) {
                   2599:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2600: 	$path.=$fnamepath.'/';
                   2601:     }
1.259     www      2602:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2603:     my $count;
                   2604:     for ($count=4;$count<=$#parts;$count++) {
                   2605:         $filepath.="/$parts[$count]";
                   2606:         if ((-e $filepath)!=1) {
                   2607: 	    mkdir($filepath,0777);
                   2608:         }
                   2609:     }
1.984     neumanie 2610: 
1.258     www      2611: # Save the file
                   2612:     {
1.701     albertel 2613: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2614: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2615: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2616: 	    return '/adm/notfound.html';
                   2617: 	}
1.1090    raeburn  2618:         if ($context eq 'overwrite') {
1.1117    foxr     2619:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2620:             my $target = $filepath.'/'.$file;
                   2621:             if (-e $source) {
                   2622:                 my @info = stat($source);
                   2623:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2624:                     unless (&File::Copy::move($source,$target)) {
                   2625:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2626:                         return "Moving from $source failed";
                   2627:                     }
                   2628:                 } else {
                   2629:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2630:                 }
                   2631:             } else {
                   2632:                 return "Temporary file: $source missing";
                   2633:             }
                   2634:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2635: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2636: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2637: 	    return '/adm/notfound.html';
                   2638: 	}
1.570     albertel 2639: 	close(FH);
1.1051    raeburn  2640:         if ($resizewidth && $resizeheight) {
                   2641:             my $mm = new File::MMagic;
                   2642:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2643:             if ($mime_type =~ m{^image/}) {
                   2644: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2645:             }  
1.977     amueller 2646: 	}
1.258     www      2647:     }
1.637     raeburn  2648:     if ($parser eq 'parse') {
1.1024    raeburn  2649:         my $mm = new File::MMagic;
1.1095    raeburn  2650:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2651:         if ($type eq 'text/html') {
1.1024    raeburn  2652:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2653:                                                        $allfiles,$codebase);
                   2654:             unless ($parse_result eq 'ok') {
                   2655:                 &logthis('Failed to parse '.$filepath.$file.
                   2656: 	   	         ' for embedded media: '.$parse_result); 
                   2657:             }
1.637     raeburn  2658:         }
1.1095    raeburn  2659:         if (ref($mimetype)) {
                   2660:             $$mimetype = $type;
                   2661:         }
1.637     raeburn  2662:     }
1.860     raeburn  2663:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2664:         my $input = $filepath.'/'.$file;
                   2665:         my $output = $filepath.'/'.'tn-'.$file;
                   2666:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2667:         system("convert -sample $thumbsize $input $output");
                   2668:         if (-e $filepath.'/'.'tn-'.$file) {
                   2669:             $fetchthumb  = 1; 
                   2670:         }
                   2671:     }
1.858     raeburn  2672:  
1.259     www      2673: # Notify homeserver to grep it
                   2674: #
1.984     neumanie 2675:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2676:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2677:     if ($fetchresult eq 'ok') {
1.860     raeburn  2678:         if ($fetchthumb) {
                   2679:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2680:             if ($thumbresult ne 'ok') {
                   2681:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2682:                          $docuhome.': '.$thumbresult);
                   2683:             }
                   2684:         }
1.259     www      2685: #
1.258     www      2686: # Return the URL to it
1.494     albertel 2687:         return '/uploaded/'.$path.$file;
1.263     www      2688:     } else {
1.494     albertel 2689:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2690: 		 ': '.$fetchresult);
1.263     www      2691:         return '/adm/notfound.html';
1.858     raeburn  2692:     }
1.493     albertel 2693: }
                   2694: 
1.637     raeburn  2695: sub extract_embedded_items {
1.961     raeburn  2696:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2697:     my @state = ();
                   2698:     my %javafiles = (
                   2699:                       codebase => '',
                   2700:                       code => '',
                   2701:                       archive => ''
                   2702:                     );
                   2703:     my %mediafiles = (
                   2704:                       src => '',
                   2705:                       movie => '',
                   2706:                      );
1.648     raeburn  2707:     my $p;
                   2708:     if ($content) {
                   2709:         $p = HTML::LCParser->new($content);
                   2710:     } else {
1.961     raeburn  2711:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2712:     }
1.641     albertel 2713:     while (my $t=$p->get_token()) {
1.640     albertel 2714: 	if ($t->[0] eq 'S') {
                   2715: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2716: 	    push(@state, $tagname);
1.648     raeburn  2717:             if (lc($tagname) eq 'allow') {
                   2718:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2719:             }
1.640     albertel 2720: 	    if (lc($tagname) eq 'img') {
                   2721: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2722: 	    }
1.886     albertel 2723: 	    if (lc($tagname) eq 'a') {
                   2724: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2725: 	    }
1.645     raeburn  2726:             if (lc($tagname) eq 'script') {
                   2727:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2728:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2729:                 } else {
                   2730:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2731:                 }
                   2732:             }
                   2733:             if (lc($tagname) eq 'link') {
                   2734:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2735:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2736:                 }
                   2737:             }
1.640     albertel 2738: 	    if (lc($tagname) eq 'object' ||
                   2739: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2740: 		foreach my $item (keys(%javafiles)) {
                   2741: 		    $javafiles{$item} = '';
                   2742: 		}
                   2743: 	    }
                   2744: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2745: 		my $name = lc($attr->{'name'});
                   2746: 		foreach my $item (keys(%javafiles)) {
                   2747: 		    if ($name eq $item) {
                   2748: 			$javafiles{$item} = $attr->{'value'};
                   2749: 			last;
                   2750: 		    }
                   2751: 		}
                   2752: 		foreach my $item (keys(%mediafiles)) {
                   2753: 		    if ($name eq $item) {
                   2754: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2755: 			last;
                   2756: 		    }
                   2757: 		}
                   2758: 	    }
                   2759: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2760: 		foreach my $item (keys(%javafiles)) {
                   2761: 		    if ($attr->{$item}) {
                   2762: 			$javafiles{$item} = $attr->{$item};
                   2763: 			last;
                   2764: 		    }
                   2765: 		}
                   2766: 		foreach my $item (keys(%mediafiles)) {
                   2767: 		    if ($attr->{$item}) {
                   2768: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2769: 			last;
                   2770: 		    }
                   2771: 		}
                   2772: 	    }
                   2773: 	} elsif ($t->[0] eq 'E') {
                   2774: 	    my ($tagname) = ($t->[1]);
                   2775: 	    if ($javafiles{'codebase'} ne '') {
                   2776: 		$javafiles{'codebase'} .= '/';
                   2777: 	    }  
                   2778: 	    if (lc($tagname) eq 'applet' ||
                   2779: 		lc($tagname) eq 'object' ||
                   2780: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2781: 		) {
                   2782: 		foreach my $item (keys(%javafiles)) {
                   2783: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2784: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2785: 			&add_filetype($allfiles,$file,$item);
                   2786: 		    }
                   2787: 		}
                   2788: 	    } 
                   2789: 	    pop @state;
                   2790: 	}
                   2791:     }
1.637     raeburn  2792:     return 'ok';
                   2793: }
                   2794: 
1.639     albertel 2795: sub add_filetype {
                   2796:     my ($allfiles,$file,$type)=@_;
                   2797:     if (exists($allfiles->{$file})) {
                   2798: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2799: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2800: 	}
                   2801:     } else {
                   2802: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2803:     }
                   2804: }
                   2805: 
1.493     albertel 2806: sub removeuploadedurl {
1.984     neumanie 2807:     my ($url)=@_;	
                   2808:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2809:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2810: }
                   2811: 
                   2812: sub removeuserfile {
                   2813:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2814:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2815:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2816:     if ($result eq 'ok') {	
1.798     raeburn  2817:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2818:             my $metafile = $fname.'.meta';
                   2819:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2820: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2821:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2822:             my $sqlresult = 
1.823     albertel 2823:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2824:                                         'portfolio_metadata',$group,
                   2825:                                         'delete');
1.798     raeburn  2826:         }
                   2827:     }
                   2828:     return $result;
1.257     www      2829: }
1.15      www      2830: 
1.530     albertel 2831: sub mkdiruserfile {
                   2832:     my ($docuname,$docudom,$dir)=@_;
                   2833:     my $home=&homeserver($docuname,$docudom);
                   2834:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2835: }
                   2836: 
1.531     albertel 2837: sub renameuserfile {
                   2838:     my ($docuname,$docudom,$old,$new)=@_;
                   2839:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2840:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2841:                         &escape("$old").':'.&escape("$new"),$home);
                   2842:     if ($result eq 'ok') {
                   2843:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2844:             my $oldmeta = $old.'.meta';
                   2845:             my $newmeta = $new.'.meta';
                   2846:             my $metaresult = 
                   2847:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2848: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2849:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2850:             my $sqlresult = 
1.823     albertel 2851:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2852:                                         'portfolio_metadata',$group,
                   2853:                                         'delete');
1.798     raeburn  2854:         }
                   2855:     }
                   2856:     return $result;
1.531     albertel 2857: }
                   2858: 
1.14      www      2859: # ------------------------------------------------------------------------- Log
                   2860: 
                   2861: sub log {
                   2862:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2863:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2864: }
                   2865: 
                   2866: # ------------------------------------------------------------------ Course Log
1.352     www      2867: #
                   2868: # This routine flushes several buffers of non-mission-critical nature
                   2869: #
1.157     www      2870: 
                   2871: sub flushcourselogs {
1.352     www      2872:     &logthis('Flushing log buffers');
                   2873: #
                   2874: # course logs
                   2875: # This is a log of all transactions in a course, which can be used
                   2876: # for data mining purposes
                   2877: #
                   2878: # It also collects the courseid database, which lists last transaction
                   2879: # times and course titles for all courseids
                   2880: #
                   2881:     my %courseidbuffer=();
1.921     raeburn  2882:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2883:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2884: 		          &escape($courselogs{$crsid}),
                   2885: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2886: 	    delete $courselogs{$crsid};
                   2887:         } else {
                   2888:             &logthis('Failed to flush log buffer for '.$crsid);
                   2889:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2890:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2891:                         " exceeded maximum size, deleting.</font>");
                   2892:                delete $courselogs{$crsid};
                   2893:             }
1.352     www      2894:         }
1.920     raeburn  2895:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2896:             'description' => $coursedescrbuf{$crsid},
                   2897:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2898:             'type'        => $coursetypebuf{$crsid},
                   2899:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2900:         };
1.191     harris41 2901:     }
1.352     www      2902: #
                   2903: # Write course id database (reverse lookup) to homeserver of courses 
                   2904: # Is used in pickcourse
                   2905: #
1.840     albertel 2906:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2907:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2908:                                     $courseidbuffer{$crs_home},
                   2909:                                     $crs_home,'timeonly');
1.352     www      2910:     }
                   2911: #
                   2912: # File accesses
                   2913: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2914: #
1.449     matthew  2915:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2916:         if ($entry =~ /___count$/) {
                   2917:             my ($dom,$name);
1.807     albertel 2918:             ($dom,$name,undef)=
1.811     albertel 2919: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2920:             if (! defined($dom) || $dom eq '' || 
                   2921:                 ! defined($name) || $name eq '') {
1.620     albertel 2922:                 my $cid = $env{'request.course.id'};
                   2923:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2924:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2925:             }
1.450     matthew  2926:             my $value = $accesshash{$entry};
                   2927:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2928:             my %temphash=($url => $value);
1.449     matthew  2929:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2930:             if ($result eq 'ok') {
                   2931:                 delete $accesshash{$entry};
                   2932:             } elsif ($result eq 'unknown_cmd') {
                   2933:                 # Target server has old code running on it.
1.450     matthew  2934:                 my %temphash=($entry => $value);
1.449     matthew  2935:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2936:                     delete $accesshash{$entry};
                   2937:                 }
                   2938:             }
                   2939:         } else {
1.811     albertel 2940:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2941:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2942:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2943:                 delete $accesshash{$entry};
                   2944:             }
1.185     www      2945:         }
1.191     harris41 2946:     }
1.352     www      2947: #
                   2948: # Roles
                   2949: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2950: #
1.800     albertel 2951:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2952:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2953: 	    split(/\:/,$entry);
                   2954:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2955:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2956:                 $rudom,$runame) eq 'ok') {
                   2957: 	    delete $userrolehash{$entry};
                   2958:         }
                   2959:     }
1.662     raeburn  2960: #
                   2961: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2962: #
                   2963:     my %domrolebuffer = ();
1.1000    raeburn  2964:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2965:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2966:         if ($domrolebuffer{$rudom}) {
                   2967:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2968:                       '='.&escape($domainrolehash{$entry});
                   2969:         } else {
                   2970:             $domrolebuffer{$rudom}.=&escape($entry).
                   2971:                       '='.&escape($domainrolehash{$entry});
                   2972:         }
                   2973:         delete $domainrolehash{$entry};
                   2974:     }
                   2975:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2976: 	my %servers = &get_servers($dom,'library');
                   2977: 	foreach my $tryserver (keys(%servers)) {
                   2978: 	    unless (&reply('domroleput:'.$dom.':'.
                   2979: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2980: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2981: 	    }
1.662     raeburn  2982:         }
                   2983:     }
1.186     www      2984:     $dumpcount++;
1.157     www      2985: }
                   2986: 
                   2987: sub courselog {
                   2988:     my $what=shift;
1.158     www      2989:     $what=time.':'.$what;
1.620     albertel 2990:     unless ($env{'request.course.id'}) { return ''; }
                   2991:     $coursedombuf{$env{'request.course.id'}}=
                   2992:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2993:     $coursenumbuf{$env{'request.course.id'}}=
                   2994:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2995:     $coursehombuf{$env{'request.course.id'}}=
                   2996:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2997:     $coursedescrbuf{$env{'request.course.id'}}=
                   2998:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2999:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3000:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3001:     $courseownerbuf{$env{'request.course.id'}}=
                   3002:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3003:     $coursetypebuf{$env{'request.course.id'}}=
                   3004:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3005:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3006: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3007:     } else {
1.620     albertel 3008: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3009:     }
1.620     albertel 3010:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3011: 	&flushcourselogs();
                   3012:     }
1.158     www      3013: }
                   3014: 
                   3015: sub courseacclog {
                   3016:     my $fnsymb=shift;
1.620     albertel 3017:     unless ($env{'request.course.id'}) { return ''; }
                   3018:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3019:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3020:         $what.=':POST';
1.583     matthew  3021:         # FIXME: Probably ought to escape things....
1.800     albertel 3022: 	foreach my $key (keys(%env)) {
                   3023:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3024:                 my $formitem = $1;
                   3025:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3026:                     $what.=':'.$formitem.'='.$env{$key};
                   3027:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3028:                     $what.=':'.$formitem.'='.$env{$key};
                   3029:                 }
1.158     www      3030:             }
1.191     harris41 3031:         }
1.583     matthew  3032:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3033:         # FIXME: We should not be depending on a form parameter that someone
                   3034:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3035:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3036:             $what.= ':POST';
                   3037:             # FIXME: Probably ought to escape things....
                   3038:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3039:                                  'crsdiscuss') {
1.620     albertel 3040:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3041:             }
                   3042:         }
1.158     www      3043:     }
                   3044:     &courselog($what);
1.149     www      3045: }
                   3046: 
1.185     www      3047: sub countacc {
                   3048:     my $url=&declutter(shift);
1.458     matthew  3049:     return if (! defined($url) || $url eq '');
1.620     albertel 3050:     unless ($env{'request.course.id'}) { return ''; }
                   3051:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3052:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3053:     $accesshash{$key}++;
1.185     www      3054: }
1.349     www      3055: 
1.361     www      3056: sub linklog {
                   3057:     my ($from,$to)=@_;
                   3058:     $from=&declutter($from);
                   3059:     $to=&declutter($to);
                   3060:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3061:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3062: }
                   3063:   
1.349     www      3064: sub userrolelog {
                   3065:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3066:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3067:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3068:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3069:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3070:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3071:        $userrolehash
                   3072:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3073:                     =$tend.':'.$tstart;
1.662     raeburn  3074:     }
1.898     albertel 3075:     if (($env{'request.role'} =~ /dc\./) &&
                   3076: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3077: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3078: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3079:          ($trole=~/^co/))) {
1.898     albertel 3080:        $userrolehash
                   3081:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3082:                     =$tend.':'.$tstart;
                   3083:     }
1.662     raeburn  3084:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3085:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3086:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3087:         ($trole=~/^sc/)) {
                   3088:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3089:        $domainrolehash
                   3090:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3091:                     = $tend.':'.$tstart;
                   3092:     }
1.351     www      3093: }
                   3094: 
1.957     raeburn  3095: sub courserolelog {
                   3096:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3097:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3098:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3099:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3100:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3101:         ($trole eq 'co')) {
1.957     raeburn  3102:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3103:             my $cdom = $1;
                   3104:             my $cnum = $2;
                   3105:             my $sec = $3;
                   3106:             my $namespace = 'rolelog';
                   3107:             my %storehash = (
                   3108:                                role    => $trole,
                   3109:                                start   => $tstart,
                   3110:                                end     => $tend,
                   3111:                                selfenroll => $selfenroll,
                   3112:                                context    => $context,
                   3113:                             );
                   3114:             if ($trole eq 'gr') {
                   3115:                 $namespace = 'groupslog';
                   3116:                 $storehash{'group'} = $sec;
                   3117:             } else {
                   3118:                 $storehash{'section'} = $sec;
                   3119:             }
                   3120:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3121:             if (($trole ne 'st') || ($sec ne '')) {
                   3122:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3123:             }
1.957     raeburn  3124:         }
                   3125:     }
                   3126:     return;
                   3127: }
                   3128: 
1.351     www      3129: sub get_course_adv_roles {
1.948     raeburn  3130:     my ($cid,$codes) = @_;
1.620     albertel 3131:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3132:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3133:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3134:     my %nothide=();
1.800     albertel 3135:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3136:         if ($user !~ /:/) {
                   3137: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3138:         } else {
                   3139:             $nothide{$user}=1;
                   3140:         }
1.470     www      3141:     }
1.351     www      3142:     my %returnhash=();
                   3143:     my %dumphash=
                   3144:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3145:     my $now=time;
1.997     raeburn  3146:     my %privileged;
1.1000    raeburn  3147:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3148: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3149:         if (($tstart) && ($tstart<0)) { next; }
                   3150:         if (($tend) && ($tend<$now)) { next; }
                   3151:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3152:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3153: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3154:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3155:             my %dompersonnel =
1.998     raeburn  3156:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3157:             $privileged{$domain} = {};
                   3158:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3159:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3160:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3161:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3162:                         $privileged{$udom}{$uname} = 1;
                   3163:                     }
                   3164:                 }
                   3165:             }
                   3166:         }
                   3167:         if ((exists($privileged{$domain}{$username})) && 
                   3168:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3169: 	if ($role eq 'cr') { next; }
1.948     raeburn  3170:         if ($codes) {
                   3171:             if ($section) { $role .= ':'.$section; }
                   3172:             if ($returnhash{$role}) {
                   3173:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3174:             } else {
                   3175:                 $returnhash{$role}=$username.':'.$domain;
                   3176:             }
1.351     www      3177:         } else {
1.988     raeburn  3178:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3179:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3180:             if ($returnhash{$key}) {
                   3181: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3182:             } else {
                   3183:                 $returnhash{$key}=$username.':'.$domain;
                   3184:             }
1.351     www      3185:         }
1.948     raeburn  3186:     }
1.400     www      3187:     return %returnhash;
                   3188: }
                   3189: 
                   3190: sub get_my_roles {
1.937     raeburn  3191:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3192:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3193:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3194:     my (%dumphash,%nothide);
1.1086    raeburn  3195:     if ($context eq 'userroles') {
                   3196:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3197:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3198:     } else {
                   3199:         %dumphash=
1.400     www      3200:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3201:         if ($hidepriv) {
                   3202:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3203:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3204:                 if ($user !~ /:/) {
                   3205:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3206:                 } else {
                   3207:                     $nothide{$user} = 1;
                   3208:                 }
                   3209:             }
                   3210:         }
1.858     raeburn  3211:     }
1.400     www      3212:     my %returnhash=();
                   3213:     my $now=time;
1.999     raeburn  3214:     my %privileged;
1.800     albertel 3215:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3216:         my ($role,$tend,$tstart);
                   3217:         if ($context eq 'userroles') {
                   3218: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3219:         } else {
                   3220:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3221:         }
1.400     www      3222:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3223:         my $status = 'active';
1.939     raeburn  3224:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3225:             $status = 'previous';
                   3226:         } 
                   3227:         if (($tstart) && ($now<$tstart)) {
                   3228:             $status = 'future';
                   3229:         }
                   3230:         if (ref($types) eq 'ARRAY') {
                   3231:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3232:                 next;
                   3233:             } 
                   3234:         } else {
                   3235:             if ($status ne 'active') {
                   3236:                 next;
                   3237:             }
                   3238:         }
1.867     raeburn  3239:         my ($rolecode,$username,$domain,$section,$area);
                   3240:         if ($context eq 'userroles') {
                   3241:             ($area,$rolecode) = split(/_/,$entry);
                   3242:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3243:         } else {
                   3244:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3245:         }
1.832     raeburn  3246:         if (ref($roledoms) eq 'ARRAY') {
                   3247:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3248:                 next;
                   3249:             }
                   3250:         }
                   3251:         if (ref($roles) eq 'ARRAY') {
                   3252:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3253:                 if ($role =~ /^cr\//) {
                   3254:                     if (!grep(/^cr$/,@{$roles})) {
                   3255:                         next;
                   3256:                     }
1.1104    raeburn  3257:                 } elsif ($role =~ /^gr\//) {
                   3258:                     if (!grep(/^gr$/,@{$roles})) {
                   3259:                         next;
                   3260:                     }
1.922     raeburn  3261:                 } else {
                   3262:                     next;
                   3263:                 }
1.832     raeburn  3264:             }
1.867     raeburn  3265:         }
1.937     raeburn  3266:         if ($hidepriv) {
1.999     raeburn  3267:             if ($context eq 'userroles') {
                   3268:                 if ((&privileged($username,$domain)) &&
                   3269:                     (!$nothide{$username.':'.$domain})) {
                   3270:                     next;
                   3271:                 }
                   3272:             } else {
                   3273:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3274:                     my %dompersonnel =
                   3275:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3276:                     $privileged{$domain} = {};
                   3277:                     if (keys(%dompersonnel)) {
                   3278:                         foreach my $server (keys(%dompersonnel)) {
                   3279:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3280:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3281:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3282:                                     $privileged{$udom}{$uname} = $trole;
                   3283:                                 }
                   3284:                             }
                   3285:                         }
                   3286:                     }
                   3287:                 }
                   3288:                 if (exists($privileged{$domain}{$username})) {
                   3289:                     if (!$nothide{$username.':'.$domain}) {
                   3290:                         next;
                   3291:                     }
                   3292:                 }
1.937     raeburn  3293:             }
                   3294:         }
1.933     raeburn  3295:         if ($withsec) {
                   3296:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3297:                 $tstart.':'.$tend;
                   3298:         } else {
                   3299:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3300:         }
1.832     raeburn  3301:     }
1.373     www      3302:     return %returnhash;
1.399     www      3303: }
                   3304: 
                   3305: # ----------------------------------------------------- Frontpage Announcements
                   3306: #
                   3307: #
                   3308: 
                   3309: sub postannounce {
                   3310:     my ($server,$text)=@_;
1.844     albertel 3311:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3312:     unless ($text=~/\w/) { $text=''; }
                   3313:     return &reply('setannounce:'.&escape($text),$server);
                   3314: }
                   3315: 
                   3316: sub getannounce {
1.448     albertel 3317: 
                   3318:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3319: 	my $announcement='';
1.800     albertel 3320: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3321: 	close($fh);
1.399     www      3322: 	if ($announcement=~/\w/) { 
                   3323: 	    return 
                   3324:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3325:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3326: 	} else {
                   3327: 	    return '';
                   3328: 	}
                   3329:     } else {
                   3330: 	return '';
                   3331:     }
1.351     www      3332: }
1.353     www      3333: 
                   3334: # ---------------------------------------------------------- Course ID routines
                   3335: # Deal with domain's nohist_courseid.db files
                   3336: #
                   3337: 
                   3338: sub courseidput {
1.921     raeburn  3339:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3340:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3341:     my $outcome;
                   3342:     if ($caller eq 'timeonly') {
                   3343:         my $cids = '';
                   3344:         foreach my $item (keys(%$storehash)) {
                   3345:             $cids.=&escape($item).'&';
                   3346:         }
                   3347:         $cids=~s/\&$//;
                   3348:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3349:                           $coursehome);       
                   3350:     } else {
                   3351:         my $items = '';
                   3352:         foreach my $item (keys(%$storehash)) {
                   3353:             $items.= &escape($item).'='.
                   3354:                      &freeze_escape($$storehash{$item}).'&';
                   3355:         }
                   3356:         $items=~s/\&$//;
                   3357:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3358:                           $coursehome);
1.918     raeburn  3359:     }
                   3360:     if ($outcome eq 'unknown_cmd') {
                   3361:         my $what;
                   3362:         foreach my $cid (keys(%$storehash)) {
                   3363:             $what .= &escape($cid).'=';
1.921     raeburn  3364:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3365:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3366:             }
                   3367:             $what =~ s/\:$/&/;
                   3368:         }
                   3369:         $what =~ s/\&$//;  
                   3370:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3371:     } else {
                   3372:         return $outcome;
                   3373:     }
1.353     www      3374: }
                   3375: 
                   3376: sub courseiddump {
1.921     raeburn  3377:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3378:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3379:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3380:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3381:     my $as_hash = 1;
                   3382:     my %returnhash;
                   3383:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3384:     my %libserv = &all_library();
                   3385:     foreach my $tryserver (keys(%libserv)) {
                   3386:         if ( (  $hostidflag == 1 
                   3387: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3388: 	     || (!defined($hostidflag)) ) {
                   3389: 
1.918     raeburn  3390: 	    if (($domfilter eq '') ||
                   3391: 		(&host_domain($tryserver) eq $domfilter)) {
                   3392:                 my $rep = 
                   3393:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3394:                          $sincefilter.':'.&escape($descfilter).':'.
                   3395:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3396:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3397:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3398:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3399:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3400:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3401:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3402:                          &escape($creationcontext).':'.$domcloner,
                   3403:                          $tryserver);
1.918     raeburn  3404:                 my @pairs=split(/\&/,$rep);
                   3405:                 foreach my $item (@pairs) {
                   3406:                     my ($key,$value)=split(/\=/,$item,2);
                   3407:                     $key = &unescape($key);
                   3408:                     next if ($key =~ /^error: 2 /);
                   3409:                     my $result = &thaw_unescape($value);
                   3410:                     if (ref($result) eq 'HASH') {
                   3411:                         $returnhash{$key}=$result;
                   3412:                     } else {
1.921     raeburn  3413:                         my @responses = split(/:/,$value);
                   3414:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3415:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3416:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3417:                         }
1.1008    raeburn  3418:                     }
1.353     www      3419:                 }
                   3420:             }
                   3421:         }
                   3422:     }
                   3423:     return %returnhash;
                   3424: }
                   3425: 
1.1055    raeburn  3426: sub courselastaccess {
                   3427:     my ($cdom,$cnum,$hostidref) = @_;
                   3428:     my %returnhash;
                   3429:     if ($cdom && $cnum) {
                   3430:         my $chome = &homeserver($cnum,$cdom);
                   3431:         if ($chome ne 'no_host') {
                   3432:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3433:             &extract_lastaccess(\%returnhash,$rep);
                   3434:         }
                   3435:     } else {
                   3436:         if (!$cdom) { $cdom=''; }
                   3437:         my %libserv = &all_library();
                   3438:         foreach my $tryserver (keys(%libserv)) {
                   3439:             if (ref($hostidref) eq 'ARRAY') {
                   3440:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3441:             } 
                   3442:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3443:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3444:                 &extract_lastaccess(\%returnhash,$rep);
                   3445:             }
                   3446:         }
                   3447:     }
                   3448:     return %returnhash;
                   3449: }
                   3450: 
                   3451: sub extract_lastaccess {
                   3452:     my ($returnhash,$rep) = @_;
                   3453:     if (ref($returnhash) eq 'HASH') {
                   3454:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3455:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3456:                  $rep eq '') {
                   3457:             my @pairs=split(/\&/,$rep);
                   3458:             foreach my $item (@pairs) {
                   3459:                 my ($key,$value)=split(/\=/,$item,2);
                   3460:                 $key = &unescape($key);
                   3461:                 next if ($key =~ /^error: 2 /);
                   3462:                 $returnhash->{$key} = &thaw_unescape($value);
                   3463:             }
                   3464:         }
                   3465:     }
                   3466:     return;
                   3467: }
                   3468: 
1.658     raeburn  3469: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3470: 
                   3471: sub dcmailput {
1.685     raeburn  3472:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3473:     my $status = &Apache::lonnet::critical(
1.740     www      3474:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3475:        &escape($message),$server);
1.662     raeburn  3476:     return $status;
                   3477: }
                   3478: 
1.658     raeburn  3479: sub dcmaildump {
                   3480:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3481:     my %returnhash=();
1.846     albertel 3482: 
                   3483:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3484:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3485:                                                          &escape($enddate).':';
                   3486: 	my @esc_senders=map { &escape($_)} @$senders;
                   3487: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3488: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3489:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3490:             if (($key) && ($value)) {
                   3491:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3492:             }
                   3493:         }
                   3494:     }
                   3495:     return %returnhash;
                   3496: }
1.662     raeburn  3497: # ---------------------------------------------------------- Domain roles
                   3498: 
                   3499: sub get_domain_roles {
                   3500:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3501:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3502:         $startdate = '.';
                   3503:     }
1.1018    raeburn  3504:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3505:         $enddate = '.';
                   3506:     }
1.922     raeburn  3507:     my $rolelist;
                   3508:     if (ref($roles) eq 'ARRAY') {
                   3509:         $rolelist = join(':',@{$roles});
                   3510:     }
1.662     raeburn  3511:     my %personnel = ();
1.841     albertel 3512: 
                   3513:     my %servers = &get_servers($dom,'library');
                   3514:     foreach my $tryserver (keys(%servers)) {
                   3515: 	%{$personnel{$tryserver}}=();
                   3516: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3517: 					    &escape($startdate).':'.
                   3518: 					    &escape($enddate).':'.
                   3519: 					    &escape($rolelist), $tryserver))) {
                   3520: 	    my ($key,$value) = split(/\=/,$line,2);
                   3521: 	    if (($key) && ($value)) {
                   3522: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3523: 	    }
                   3524: 	}
1.662     raeburn  3525:     }
                   3526:     return %personnel;
                   3527: }
1.658     raeburn  3528: 
1.1057    www      3529: # ----------------------------------------------------------- Interval timing 
1.149     www      3530: 
1.504     albertel 3531: sub get_first_access {
                   3532:     my ($type,$argsymb)=@_;
1.790     albertel 3533:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3534:     if ($argsymb) { $symb=$argsymb; }
                   3535:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3536:     if ($type eq 'course') {
                   3537: 	$res='course';
                   3538:     } elsif ($type eq 'map') {
1.588     albertel 3539: 	$res=&symbread($map);
                   3540:     } else {
                   3541: 	$res=$symb;
                   3542:     }
                   3543:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3544:     return $times{"$courseid\0$res"};
1.504     albertel 3545: }
                   3546: 
                   3547: sub set_first_access {
                   3548:     my ($type)=@_;
1.790     albertel 3549:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3550:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3551:     if ($type eq 'course') {
                   3552: 	$res='course';
                   3553:     } elsif ($type eq 'map') {
1.588     albertel 3554: 	$res=&symbread($map);
                   3555:     } else {
                   3556: 	$res=$symb;
                   3557:     }
                   3558:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3559:     if (!$firstaccess) {
1.588     albertel 3560: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3561:     }
                   3562:     return 'already_set';
1.504     albertel 3563: }
                   3564: 
1.110     www      3565: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3566: 
                   3567: sub expirespread {
                   3568:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3569:     my $cid=$env{'request.course.id'}; 
1.110     www      3570:     if ($cid) {
                   3571:        my $now=time;
                   3572:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3573:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3574:                             $env{'course.'.$cid.'.num'}.
1.110     www      3575: 	        	    ':nohist_expirationdates:'.
                   3576:                             &escape($key).'='.$now,
1.620     albertel 3577:                             $env{'course.'.$cid.'.home'})
1.110     www      3578:     }
                   3579:     return 'ok';
1.14      www      3580: }
                   3581: 
1.109     www      3582: # ----------------------------------------------------- Devalidate Spreadsheets
                   3583: 
                   3584: sub devalidate {
1.325     www      3585:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3586:     my $cid=$env{'request.course.id'}; 
1.109     www      3587:     if ($cid) {
1.391     matthew  3588:         # delete the stored spreadsheets for
                   3589:         # - the student level sheet of this user in course's homespace
                   3590:         # - the assessment level sheet for this resource 
                   3591:         #   for this user in user's homespace
1.553     albertel 3592: 	# - current conditional state info
1.325     www      3593: 	my $key=$uname.':'.$udom.':';
1.109     www      3594:         my $status=
1.299     matthew  3595: 	    &del('nohist_calculatedsheets',
1.391     matthew  3596: 		 [$key.'studentcalc:'],
1.620     albertel 3597: 		 $env{'course.'.$cid.'.domain'},
                   3598: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3599: 		.' '.
                   3600: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3601: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3602:         unless ($status eq 'ok ok') {
                   3603:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3604:                     $uname.' at '.$udom.' for '.
1.109     www      3605: 		    $symb.': '.$status);
1.133     albertel 3606:         }
1.553     albertel 3607: 	&delenv('user.state.'.$cid);
1.109     www      3608:     }
                   3609: }
                   3610: 
1.265     albertel 3611: sub get_scalar {
                   3612:     my ($string,$end) = @_;
                   3613:     my $value;
                   3614:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3615: 	$value = $1;
                   3616:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3617: 	$value = $1;
                   3618:     }
                   3619:     return &unescape($value);
                   3620: }
                   3621: 
                   3622: sub array2str {
                   3623:   my (@array) = @_;
                   3624:   my $result=&arrayref2str(\@array);
                   3625:   $result=~s/^__ARRAY_REF__//;
                   3626:   $result=~s/__END_ARRAY_REF__$//;
                   3627:   return $result;
                   3628: }
                   3629: 
1.204     albertel 3630: sub arrayref2str {
                   3631:   my ($arrayref) = @_;
1.265     albertel 3632:   my $result='__ARRAY_REF__';
1.204     albertel 3633:   foreach my $elem (@$arrayref) {
1.265     albertel 3634:     if(ref($elem) eq 'ARRAY') {
                   3635:       $result.=&arrayref2str($elem).'&';
                   3636:     } elsif(ref($elem) eq 'HASH') {
                   3637:       $result.=&hashref2str($elem).'&';
                   3638:     } elsif(ref($elem)) {
                   3639:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3640:     } else {
                   3641:       $result.=&escape($elem).'&';
                   3642:     }
                   3643:   }
                   3644:   $result=~s/\&$//;
1.265     albertel 3645:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3646:   return $result;
                   3647: }
                   3648: 
1.168     albertel 3649: sub hash2str {
1.204     albertel 3650:   my (%hash) = @_;
                   3651:   my $result=&hashref2str(\%hash);
1.265     albertel 3652:   $result=~s/^__HASH_REF__//;
                   3653:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3654:   return $result;
                   3655: }
                   3656: 
                   3657: sub hashref2str {
                   3658:   my ($hashref)=@_;
1.265     albertel 3659:   my $result='__HASH_REF__';
1.800     albertel 3660:   foreach my $key (sort(keys(%$hashref))) {
                   3661:     if (ref($key) eq 'ARRAY') {
                   3662:       $result.=&arrayref2str($key).'=';
                   3663:     } elsif (ref($key) eq 'HASH') {
                   3664:       $result.=&hashref2str($key).'=';
                   3665:     } elsif (ref($key)) {
1.265     albertel 3666:       $result.='=';
1.800     albertel 3667:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3668:     } else {
1.800     albertel 3669: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3670:     }
                   3671: 
1.800     albertel 3672:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3673:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3674:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3675:       $result.=&hashref2str($hashref->{$key}).'&';
                   3676:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3677:        $result.='&';
1.800     albertel 3678:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3679:     } else {
1.800     albertel 3680:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3681:     }
                   3682:   }
1.168     albertel 3683:   $result=~s/\&$//;
1.265     albertel 3684:   $result .= '__END_HASH_REF__';
1.168     albertel 3685:   return $result;
                   3686: }
                   3687: 
                   3688: sub str2hash {
1.265     albertel 3689:     my ($string)=@_;
                   3690:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3691:     return %$hash;
                   3692: }
                   3693: 
                   3694: sub str2hashref {
1.168     albertel 3695:   my ($string) = @_;
1.265     albertel 3696: 
                   3697:   my %hash;
                   3698: 
                   3699:   if($string !~ /^__HASH_REF__/) {
                   3700:       if (! ($string eq '' || !defined($string))) {
                   3701: 	  $hash{'error'}='Not hash reference';
                   3702:       }
                   3703:       return (\%hash, $string);
                   3704:   }
                   3705: 
                   3706:   $string =~ s/^__HASH_REF__//;
                   3707: 
                   3708:   while($string !~ /^__END_HASH_REF__/) {
                   3709:       #key
                   3710:       my $key='';
                   3711:       if($string =~ /^__HASH_REF__/) {
                   3712:           ($key, $string)=&str2hashref($string);
                   3713:           if(defined($key->{'error'})) {
                   3714:               $hash{'error'}='Bad data';
                   3715:               return (\%hash, $string);
                   3716:           }
                   3717:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3718:           ($key, $string)=&str2arrayref($string);
                   3719:           if($key->[0] eq 'Array reference error') {
                   3720:               $hash{'error'}='Bad data';
                   3721:               return (\%hash, $string);
                   3722:           }
                   3723:       } else {
                   3724:           $string =~ s/^(.*?)=//;
1.267     albertel 3725: 	  $key=&unescape($1);
1.265     albertel 3726:       }
                   3727:       $string =~ s/^=//;
                   3728: 
                   3729:       #value
                   3730:       my $value='';
                   3731:       if($string =~ /^__HASH_REF__/) {
                   3732:           ($value, $string)=&str2hashref($string);
                   3733:           if(defined($value->{'error'})) {
                   3734:               $hash{'error'}='Bad data';
                   3735:               return (\%hash, $string);
                   3736:           }
                   3737:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3738:           ($value, $string)=&str2arrayref($string);
                   3739:           if($value->[0] eq 'Array reference error') {
                   3740:               $hash{'error'}='Bad data';
                   3741:               return (\%hash, $string);
                   3742:           }
                   3743:       } else {
                   3744: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3745:       }
                   3746:       $string =~ s/^&//;
                   3747: 
                   3748:       $hash{$key}=$value;
1.204     albertel 3749:   }
1.265     albertel 3750: 
                   3751:   $string =~ s/^__END_HASH_REF__//;
                   3752: 
                   3753:   return (\%hash, $string);
1.204     albertel 3754: }
                   3755: 
                   3756: sub str2array {
1.265     albertel 3757:     my ($string)=@_;
                   3758:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3759:     return @$array;
                   3760: }
                   3761: 
                   3762: sub str2arrayref {
1.204     albertel 3763:   my ($string) = @_;
1.265     albertel 3764:   my @array;
                   3765: 
                   3766:   if($string !~ /^__ARRAY_REF__/) {
                   3767:       if (! ($string eq '' || !defined($string))) {
                   3768: 	  $array[0]='Array reference error';
                   3769:       }
                   3770:       return (\@array, $string);
                   3771:   }
                   3772: 
                   3773:   $string =~ s/^__ARRAY_REF__//;
                   3774: 
                   3775:   while($string !~ /^__END_ARRAY_REF__/) {
                   3776:       my $value='';
                   3777:       if($string =~ /^__HASH_REF__/) {
                   3778:           ($value, $string)=&str2hashref($string);
                   3779:           if(defined($value->{'error'})) {
                   3780:               $array[0] ='Array reference error';
                   3781:               return (\@array, $string);
                   3782:           }
                   3783:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3784:           ($value, $string)=&str2arrayref($string);
                   3785:           if($value->[0] eq 'Array reference error') {
                   3786:               $array[0] ='Array reference error';
                   3787:               return (\@array, $string);
                   3788:           }
                   3789:       } else {
                   3790: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3791:       }
                   3792:       $string =~ s/^&//;
                   3793: 
                   3794:       push(@array, $value);
1.191     harris41 3795:   }
1.265     albertel 3796: 
                   3797:   $string =~ s/^__END_ARRAY_REF__//;
                   3798: 
                   3799:   return (\@array, $string);
1.168     albertel 3800: }
                   3801: 
1.167     albertel 3802: # -------------------------------------------------------------------Temp Store
                   3803: 
1.168     albertel 3804: sub tmpreset {
                   3805:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3806:   if (!$symb) {
                   3807:     $symb=&symbread();
1.620     albertel 3808:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3809:   }
                   3810:   $symb=escape($symb);
                   3811: 
1.620     albertel 3812:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3813:   $namespace=~s/\//\_/g;
                   3814:   $namespace=~s/\W//g;
                   3815: 
1.620     albertel 3816:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3817:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3818:   if ($domain eq 'public' && $stuname eq 'public') {
                   3819:       $stuname=$ENV{'REMOTE_ADDR'};
                   3820:   }
1.1117    foxr     3821:   my $path=LONCAPA::tempdir();
1.168     albertel 3822:   my %hash;
                   3823:   if (tie(%hash,'GDBM_File',
                   3824: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3825: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3826:     foreach my $key (keys(%hash)) {
1.180     albertel 3827:       if ($key=~ /:$symb/) {
1.168     albertel 3828: 	delete($hash{$key});
                   3829:       }
                   3830:     }
                   3831:   }
                   3832: }
                   3833: 
1.167     albertel 3834: sub tmpstore {
1.168     albertel 3835:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3836: 
                   3837:   if (!$symb) {
                   3838:     $symb=&symbread();
1.620     albertel 3839:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3840:   }
                   3841:   $symb=escape($symb);
                   3842: 
                   3843:   if (!$namespace) {
                   3844:     # I don't think we would ever want to store this for a course.
                   3845:     # it seems this will only be used if we don't have a course.
1.620     albertel 3846:     #$namespace=$env{'request.course.id'};
1.168     albertel 3847:     #if (!$namespace) {
1.620     albertel 3848:       $namespace=$env{'request.state'};
1.168     albertel 3849:     #}
                   3850:   }
                   3851:   $namespace=~s/\//\_/g;
                   3852:   $namespace=~s/\W//g;
1.620     albertel 3853:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3854:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3855:   if ($domain eq 'public' && $stuname eq 'public') {
                   3856:       $stuname=$ENV{'REMOTE_ADDR'};
                   3857:   }
1.168     albertel 3858:   my $now=time;
                   3859:   my %hash;
1.1117    foxr     3860:   my $path=LONCAPA::tempdir();
1.168     albertel 3861:   if (tie(%hash,'GDBM_File',
                   3862: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3863: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3864:     $hash{"version:$symb"}++;
                   3865:     my $version=$hash{"version:$symb"};
                   3866:     my $allkeys=''; 
                   3867:     foreach my $key (keys(%$storehash)) {
                   3868:       $allkeys.=$key.':';
1.591     albertel 3869:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3870:     }
                   3871:     $hash{"$version:$symb:timestamp"}=$now;
                   3872:     $allkeys.='timestamp';
                   3873:     $hash{"$version:keys:$symb"}=$allkeys;
                   3874:     if (untie(%hash)) {
                   3875:       return 'ok';
                   3876:     } else {
                   3877:       return "error:$!";
                   3878:     }
                   3879:   } else {
                   3880:     return "error:$!";
                   3881:   }
                   3882: }
1.167     albertel 3883: 
1.168     albertel 3884: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3885: 
1.168     albertel 3886: sub tmprestore {
                   3887:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3888: 
1.168     albertel 3889:   if (!$symb) {
                   3890:     $symb=&symbread();
1.620     albertel 3891:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3892:   }
                   3893:   $symb=escape($symb);
                   3894: 
1.620     albertel 3895:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3896: 
1.620     albertel 3897:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3898:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3899:   if ($domain eq 'public' && $stuname eq 'public') {
                   3900:       $stuname=$ENV{'REMOTE_ADDR'};
                   3901:   }
1.168     albertel 3902:   my %returnhash;
                   3903:   $namespace=~s/\//\_/g;
                   3904:   $namespace=~s/\W//g;
                   3905:   my %hash;
1.1117    foxr     3906:   my $path=LONCAPA::tempdir();
1.168     albertel 3907:   if (tie(%hash,'GDBM_File',
                   3908: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3909: 	  &GDBM_READER(),0640)) {
1.168     albertel 3910:     my $version=$hash{"version:$symb"};
                   3911:     $returnhash{'version'}=$version;
                   3912:     my $scope;
                   3913:     for ($scope=1;$scope<=$version;$scope++) {
                   3914:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3915:       my @keys=split(/:/,$vkeys);
                   3916:       my $key;
                   3917:       $returnhash{"$scope:keys"}=$vkeys;
                   3918:       foreach $key (@keys) {
1.591     albertel 3919: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3920: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3921:       }
                   3922:     }
1.168     albertel 3923:     if (!(untie(%hash))) {
                   3924:       return "error:$!";
                   3925:     }
                   3926:   } else {
                   3927:     return "error:$!";
                   3928:   }
                   3929:   return %returnhash;
1.167     albertel 3930: }
                   3931: 
1.9       www      3932: # ----------------------------------------------------------------------- Store
                   3933: 
                   3934: sub store {
1.124     www      3935:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3936:     my $home='';
                   3937: 
1.168     albertel 3938:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3939: 
1.213     www      3940:     $symb=&symbclean($symb);
1.122     albertel 3941:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3942: 
1.620     albertel 3943:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3944:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3945: 
                   3946:     &devalidate($symb,$stuname,$domain);
1.109     www      3947: 
                   3948:     $symb=escape($symb);
1.187     www      3949:     if (!$namespace) { 
1.620     albertel 3950:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3951:           return ''; 
                   3952:        } 
                   3953:     }
1.620     albertel 3954:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3955: 
                   3956:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3957:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3958: 
1.12      www      3959:     my $namevalue='';
1.800     albertel 3960:     foreach my $key (keys(%$storehash)) {
                   3961:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3962:     }
1.12      www      3963:     $namevalue=~s/\&$//;
1.187     www      3964:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3965:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3966: }
                   3967: 
1.47      www      3968: # -------------------------------------------------------------- Critical Store
                   3969: 
                   3970: sub cstore {
1.124     www      3971:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3972:     my $home='';
                   3973: 
1.168     albertel 3974:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3975: 
1.213     www      3976:     $symb=&symbclean($symb);
1.122     albertel 3977:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3978: 
1.620     albertel 3979:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3980:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3981: 
                   3982:     &devalidate($symb,$stuname,$domain);
1.109     www      3983: 
                   3984:     $symb=escape($symb);
1.187     www      3985:     if (!$namespace) { 
1.620     albertel 3986:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3987:           return ''; 
                   3988:        } 
                   3989:     }
1.620     albertel 3990:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3991: 
                   3992:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3993:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3994: 
1.47      www      3995:     my $namevalue='';
1.800     albertel 3996:     foreach my $key (keys(%$storehash)) {
                   3997:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3998:     }
1.47      www      3999:     $namevalue=~s/\&$//;
1.187     www      4000:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4001:     return critical
                   4002:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4003: }
                   4004: 
1.9       www      4005: # --------------------------------------------------------------------- Restore
                   4006: 
                   4007: sub restore {
1.124     www      4008:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4009:     my $home='';
                   4010: 
1.168     albertel 4011:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4012: 
1.122     albertel 4013:     if (!$symb) {
                   4014:       unless ($symb=escape(&symbread())) { return ''; }
                   4015:     } else {
1.213     www      4016:       $symb=&escape(&symbclean($symb));
1.122     albertel 4017:     }
1.188     www      4018:     if (!$namespace) { 
1.620     albertel 4019:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4020:           return ''; 
                   4021:        } 
                   4022:     }
1.620     albertel 4023:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4024:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4025:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4026:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4027: 
1.12      www      4028:     my %returnhash=();
1.800     albertel 4029:     foreach my $line (split(/\&/,$answer)) {
                   4030: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4031:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4032:     }
1.75      www      4033:     my $version;
                   4034:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4035:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4036:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4037:        }
1.75      www      4038:     }
1.13      www      4039:     return %returnhash;
1.34      www      4040: }
                   4041: 
                   4042: # ---------------------------------------------------------- Course Description
1.1118    foxr     4043: #
                   4044: #  
1.34      www      4045: 
                   4046: sub coursedescription {
1.731     albertel 4047:     my ($courseid,$args)=@_;
1.34      www      4048:     $courseid=~s/^\///;
1.49      www      4049:     $courseid=~s/\_/\//g;
1.34      www      4050:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4051:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4052:     my $normalid=$cdomain.'_'.$cnum;
                   4053:     # need to always cache even if we get errors otherwise we keep 
                   4054:     # trying and trying and trying to get the course description.
                   4055:     my %envhash=();
                   4056:     my %returnhash=();
1.731     albertel 4057:     
                   4058:     my $expiretime=600;
                   4059:     if ($env{'request.course.id'} eq $normalid) {
                   4060: 	$expiretime=120;
                   4061:     }
                   4062: 
                   4063:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4064:     if (!$args->{'freshen_cache'}
                   4065: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4066: 	foreach my $key (keys(%env)) {
                   4067: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4068: 	    my ($setting) = $1;
                   4069: 	    $returnhash{$setting} = $env{$key};
                   4070: 	}
                   4071: 	return %returnhash;
                   4072:     }
                   4073: 
1.1118    foxr     4074:     # get the data again
                   4075: 
1.731     albertel 4076:     if (!$args->{'one_time'}) {
                   4077: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4078:     }
1.811     albertel 4079: 
1.34      www      4080:     if ($chome ne 'no_host') {
1.302     albertel 4081:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4082:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4083: 	   my $username = $env{'user.name'}; # Defult username
                   4084: 	   if(defined $args->{'user'}) {
                   4085: 	       $username = $args->{'user'};
                   4086: 	   }
1.129     albertel 4087:            $returnhash{'home'}= $chome;
                   4088: 	   $returnhash{'domain'} = $cdomain;
                   4089: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4090:            if (!defined($returnhash{'type'})) {
                   4091:                $returnhash{'type'} = 'Course';
                   4092:            }
1.130     albertel 4093:            while (my ($name,$value) = each %returnhash) {
1.53      www      4094:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4095:            }
1.270     www      4096:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4097:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4098: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4099:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4100:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4101:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4102:        }
                   4103:     }
1.731     albertel 4104:     if (!$args->{'one_time'}) {
1.949     raeburn  4105: 	&appenv(\%envhash);
1.731     albertel 4106:     }
1.302     albertel 4107:     return %returnhash;
1.461     www      4108: }
                   4109: 
1.1080    raeburn  4110: sub update_released_required {
                   4111:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4112:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4113:         $cid = $env{'request.course.id'};
                   4114:         $cdom = $env{'course.'.$cid.'.domain'};
                   4115:         $cnum = $env{'course.'.$cid.'.num'};
                   4116:         $chome = $env{'course.'.$cid.'.home'};
                   4117:     }
                   4118:     if ($needsrelease) {
                   4119:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4120:         my $needsupdate;
                   4121:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4122:             $needsupdate = 1;
                   4123:         } else {
                   4124:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4125:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4126:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4127:                 $needsupdate = 1;
                   4128:             }
                   4129:         }
                   4130:         if ($needsupdate) {
                   4131:             my %needshash = (
                   4132:                              'internal.releaserequired' => $needsrelease,
                   4133:                             );
                   4134:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4135:             if ($putresult eq 'ok') {
                   4136:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4137:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4138:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4139:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4140:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4141:                 }
                   4142:             }
                   4143:         }
                   4144:     }
                   4145:     return;
                   4146: }
                   4147: 
1.461     www      4148: # -------------------------------------------------See if a user is privileged
                   4149: 
                   4150: sub privileged {
                   4151:     my ($username,$domain)=@_;
                   4152:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4153: 			&homeserver($username,$domain));
1.1033    raeburn  4154:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4155:         ($rolesdump =~ /^error:/)) {
                   4156:         return 0;
                   4157:     }
1.461     www      4158:     my $now=time;
                   4159:     if ($rolesdump ne '') {
1.800     albertel 4160:         foreach my $entry (split(/&/,$rolesdump)) {
                   4161: 	    if ($entry!~/^rolesdef_/) {
                   4162: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4163: 		$area=~s/\_\w\w$//;
                   4164: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4165: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4166: 		    my $active=1;
                   4167: 		    if ($tend) {
                   4168: 			if ($tend<$now) { $active=0; }
                   4169: 		    }
                   4170: 		    if ($tstart) {
                   4171: 			if ($tstart>$now) { $active=0; }
                   4172: 		    }
                   4173: 		    if ($active) { return 1; }
                   4174: 		}
                   4175: 	    }
                   4176: 	}
                   4177:     }
                   4178:     return 0;
1.9       www      4179: }
1.1       albertel 4180: 
1.103     harris41 4181: # -------------------------------------------------------- Get user privileges
1.11      www      4182: 
                   4183: sub rolesinit {
                   4184:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4185:     my $now=time;
                   4186:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4187:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4188:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4189:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4190:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4191:         return \%userroles;
                   4192:     }
1.11      www      4193:     my %allroles=();
1.678     raeburn  4194:     my %allgroups=();   
1.11      www      4195: 
                   4196:     if ($rolesdump ne '') {
1.800     albertel 4197:         foreach my $entry (split(/&/,$rolesdump)) {
                   4198: 	  if ($entry!~/^rolesdef_/) {
                   4199:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4200: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4201:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4202: 	    if ($role=~/^cr/) { 
1.807     albertel 4203: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4204: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4205: 		    ($tend,$tstart)=split('_',$trest);
                   4206: 		} else {
                   4207: 		    $trole=$role;
                   4208: 		}
1.678     raeburn  4209:             } elsif ($role =~ m|^gr/|) {
                   4210:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4211:                 next if ($tstart eq '-1');
1.678     raeburn  4212:                 ($trole,$group_privs) = split(/\//,$trole);
                   4213:                 $group_privs = &unescape($group_privs);
1.587     albertel 4214: 	    } else {
                   4215: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4216: 	    }
1.743     albertel 4217: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4218: 					 $username);
                   4219: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4220:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4221:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4222:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4223: 		my $spec=$trole.'.'.$area;
                   4224: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4225: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4226:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4227:                 } elsif ($trole eq 'gr') {
                   4228:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4229: 		} else {
1.567     raeburn  4230:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4231: 		}
1.12      www      4232:             }
1.662     raeburn  4233:           }
1.191     harris41 4234:         }
1.743     albertel 4235:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4236:         $userroles{'user.adv'}    = $adv;
                   4237: 	$userroles{'user.author'} = $author;
1.620     albertel 4238:         $env{'user.adv'}=$adv;
1.11      www      4239:     }
1.743     albertel 4240:     return \%userroles;  
1.11      www      4241: }
                   4242: 
1.567     raeburn  4243: sub set_arearole {
                   4244:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4245: # log the associated role with the area
                   4246:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4247:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4248: }
                   4249: 
                   4250: sub custom_roleprivs {
                   4251:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4252:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4253:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4254:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4255:         my ($rdummy,$roledef)=
                   4256:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4257:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4258:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4259:             if (defined($syspriv)) {
1.1043    raeburn  4260:                 if ($trest =~ /^$match_community$/) {
                   4261:                     $syspriv =~ s/bre\&S//; 
                   4262:                 }
1.567     raeburn  4263:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4264:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4265:             }
                   4266:             if ($tdomain ne '') {
                   4267:                 if (defined($dompriv)) {
                   4268:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4269:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4270:                 }
                   4271:                 if (($trest ne '') && (defined($coursepriv))) {
                   4272:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4273:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4274:                 }
                   4275:             }
                   4276:         }
                   4277:     }
                   4278: }
                   4279: 
1.678     raeburn  4280: sub group_roleprivs {
                   4281:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4282:     my $access = 1;
                   4283:     my $now = time;
                   4284:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4285:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4286:     if ($access) {
1.811     albertel 4287:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4288:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4289:     }
                   4290: }
1.567     raeburn  4291: 
                   4292: sub standard_roleprivs {
                   4293:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4294:     if (defined($pr{$trole.':s'})) {
                   4295:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4296:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4297:     }
                   4298:     if ($tdomain ne '') {
                   4299:         if (defined($pr{$trole.':d'})) {
                   4300:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4301:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4302:         }
                   4303:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4304:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4305:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4306:         }
                   4307:     }
                   4308: }
                   4309: 
                   4310: sub set_userprivs {
1.1064    raeburn  4311:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4312:     my $author=0;
                   4313:     my $adv=0;
1.678     raeburn  4314:     my %grouproles = ();
                   4315:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4316:         my @groupkeys; 
1.1000    raeburn  4317:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4318:             push(@groupkeys,$role);
                   4319:         }
                   4320:         if (ref($groups_roles) eq 'HASH') {
                   4321:             foreach my $key (keys(%{$groups_roles})) {
                   4322:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4323:                     push(@groupkeys,$key);
                   4324:                 }
                   4325:             }
                   4326:         }
                   4327:         if (@groupkeys > 0) {
                   4328:             foreach my $role (@groupkeys) {
                   4329:                 my ($trole,$area,$sec,$extendedarea);
                   4330:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4331:                     $trole = $1;
                   4332:                     $area = $2;
                   4333:                     $sec = $3;
                   4334:                     $extendedarea = $area.$sec;
                   4335:                     if (exists($$allgroups{$area})) {
                   4336:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4337:                             my $spec = $trole.'.'.$extendedarea;
                   4338:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4339:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4340:                         }
1.678     raeburn  4341:                     }
                   4342:                 }
                   4343:             }
                   4344:         }
                   4345:     }
1.800     albertel 4346:     foreach my $group (keys(%grouproles)) {
                   4347:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4348:     }
1.800     albertel 4349:     foreach my $role (keys(%{$allroles})) {
                   4350:         my %thesepriv;
1.941     raeburn  4351:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4352:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4353:             if ($item ne '') {
                   4354:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4355:                 if ($restrictions eq '') {
                   4356:                     $thesepriv{$privilege}='F';
                   4357:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4358:                     $thesepriv{$privilege}.=$restrictions;
                   4359:                 }
                   4360:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4361:             }
                   4362:         }
                   4363:         my $thesestr='';
1.1104    raeburn  4364:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4365: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4366: 	}
                   4367:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4368:     }
                   4369:     return ($author,$adv);
                   4370: }
                   4371: 
1.994     raeburn  4372: sub role_status {
1.1104    raeburn  4373:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4374:     my @pwhere = ();
                   4375:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4376:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4377:         unless (!defined($$role) || $$role eq '') {
                   4378:             $$where=join('.',@pwhere);
                   4379:             $$trolecode=$$role.'.'.$$where;
                   4380:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4381:             $$tstatus='is';
1.1104    raeburn  4382:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4383:                 $$tstatus='future';
1.1034    raeburn  4384:                 if ($$tstart<$now) {
                   4385:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4386:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4387:                             my (%allroles,%allgroups,$group_privs,
                   4388:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4389:                             my %userroles = (
                   4390:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4391:                             );
1.1064    raeburn  4392:                             @rolecodes = ('cm'); 
1.1002    raeburn  4393:                             my $spec=$$role.'.'.$$where;
                   4394:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4395:                             if ($$role =~ /^cr\//) {
                   4396:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4397:                                 push(@rolecodes,'cr');
1.1002    raeburn  4398:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4399:                                 push(@rolecodes,$$role);
1.1002    raeburn  4400:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4401:                                                     $env{'user.name'});
1.1064    raeburn  4402:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4403:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4404:                                 $group_privs = &unescape($group_privs);
                   4405:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4406:                                 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  4407:                                 &get_groups_roles($tdomain,$trest,
                   4408:                                                   \%course_roles,\@rolecodes,
                   4409:                                                   \%groups_roles);
1.1002    raeburn  4410:                             } else {
1.1064    raeburn  4411:                                 push(@rolecodes,$$role);
1.1002    raeburn  4412:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4413:                             }
1.1064    raeburn  4414:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4415:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4416:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4417:                         }
                   4418:                     }
1.1034    raeburn  4419:                     $$tstatus = 'is';
1.1002    raeburn  4420:                 }
1.994     raeburn  4421:             }
                   4422:             if ($$tend) {
1.1104    raeburn  4423:                 if ($$tend<$update) {
1.994     raeburn  4424:                     $$tstatus='expired';
                   4425:                 } elsif ($$tend<$now) {
                   4426:                     $$tstatus='will_not';
                   4427:                 }
                   4428:             }
                   4429:         }
                   4430:     }
                   4431: }
                   4432: 
1.1104    raeburn  4433: sub get_groups_roles {
                   4434:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4435:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4436:                   (ref($rolecodes) eq 'ARRAY') && 
                   4437:                   (ref($groups_roles) eq 'HASH')); 
                   4438:     if (keys(%{$cdom_courseroles}) > 0) {
                   4439:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4440:         if ($cdom ne '' && $cnum ne '') {
                   4441:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4442:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4443:                     my $crsrole = $1;
                   4444:                     my $crssec = $2;
                   4445:                     if ($crsrole =~ /^cr/) {
                   4446:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4447:                             push(@{$rolecodes},'cr');
                   4448:                         }
                   4449:                     } else {
                   4450:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4451:                             push(@{$rolecodes},$crsrole);
                   4452:                         }
                   4453:                     }
                   4454:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4455:                     if ($crssec ne '') {
                   4456:                         $rolekey .= "/$crssec";
                   4457:                     }
                   4458:                     $rolekey .= './';
                   4459:                     $groups_roles->{$rolekey} = $rolecodes;
                   4460:                 }
                   4461:             }
                   4462:         }
                   4463:     }
                   4464:     return;
                   4465: }
                   4466: 
                   4467: sub delete_env_groupprivs {
                   4468:     my ($where,$courseroles,$possroles) = @_;
                   4469:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4470:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4471:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4472:         %{$courseroles->{$udom}} =
                   4473:             &get_my_roles('','','userroles',['active'],
                   4474:                           $possroles,[$udom],1);
                   4475:     }
                   4476:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4477:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4478:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4479:             my $area = '/'.$cdom.'/'.$cnum;
                   4480:             my $privkey = "user.priv.$crsrole.$area";
                   4481:             if ($crssec ne '') {
                   4482:                 $privkey .= '/'.$crssec;
                   4483:             }
                   4484:             $privkey .= ".$area/$group";
                   4485:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4486:         }
                   4487:     }
                   4488:     return;
                   4489: }
                   4490: 
1.994     raeburn  4491: sub check_adhoc_privs {
1.1104    raeburn  4492:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4493:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4494:     if ($env{$cckey}) {
                   4495:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4496:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4497:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4498:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4499:         }
                   4500:     } else {
1.1088    raeburn  4501:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4502:     }
                   4503: }
                   4504: 
                   4505: sub set_adhoc_privileges {
                   4506: # role can be cc or ca
1.1088    raeburn  4507:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4508:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4509:     my $spec = $role.'.'.$area;
                   4510:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4511:                                   $env{'user.name'});
                   4512:     my %ccrole = ();
                   4513:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4514:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4515:     &appenv(\%userroles,[$role,'cm']);
                   4516:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4517:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4518:         &appenv( {'request.role'        => $spec,
                   4519:                   'request.role.domain' => $dcdom,
                   4520:                   'request.course.sec'  => ''
                   4521:                  }
                   4522:                );
                   4523:         my $tadv=0;
                   4524:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4525:         &appenv({'request.role.adv'    => $tadv});
                   4526:     }
1.994     raeburn  4527: }
                   4528: 
1.12      www      4529: # --------------------------------------------------------------- get interface
                   4530: 
                   4531: sub get {
1.131     albertel 4532:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4533:    my $items='';
1.800     albertel 4534:    foreach my $item (@$storearr) {
                   4535:        $items.=&escape($item).'&';
1.191     harris41 4536:    }
1.12      www      4537:    $items=~s/\&$//;
1.620     albertel 4538:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4539:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4540:    my $uhome=&homeserver($uname,$udomain);
                   4541: 
1.133     albertel 4542:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4543:    my @pairs=split(/\&/,$rep);
1.273     albertel 4544:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4545:      return @pairs;
                   4546:    }
1.15      www      4547:    my %returnhash=();
1.42      www      4548:    my $i=0;
1.800     albertel 4549:    foreach my $item (@$storearr) {
                   4550:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4551:       $i++;
1.191     harris41 4552:    }
1.15      www      4553:    return %returnhash;
1.27      www      4554: }
                   4555: 
                   4556: # --------------------------------------------------------------- del interface
                   4557: 
                   4558: sub del {
1.133     albertel 4559:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4560:    my $items='';
1.800     albertel 4561:    foreach my $item (@$storearr) {
                   4562:        $items.=&escape($item).'&';
1.191     harris41 4563:    }
1.984     neumanie 4564: 
1.27      www      4565:    $items=~s/\&$//;
1.620     albertel 4566:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4567:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4568:    my $uhome=&homeserver($uname,$udomain);
                   4569:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4570: }
                   4571: 
                   4572: # -------------------------------------------------------------- dump interface
                   4573: 
                   4574: sub dump {
1.1086    raeburn  4575:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4576:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4577:     if (!$uname) { $uname=$env{'user.name'}; }
                   4578:     my $uhome=&homeserver($uname,$udomain);
                   4579:     if ($regexp) {
                   4580: 	$regexp=&escape($regexp);
                   4581:     } else {
                   4582: 	$regexp='.';
                   4583:     }
1.1086    raeburn  4584:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4585:     my @pairs=split(/\&/,$rep);
                   4586:     my %returnhash=();
1.1098    foxr     4587:     if (!($rep =~ /^error/ )) {
                   4588: 	foreach my $item (@pairs) {
                   4589: 	    my ($key,$value)=split(/=/,$item,2);
                   4590: 	    $key = &unescape($key);
                   4591: 	    next if ($key =~ /^error: 2 /);
                   4592: 	    $returnhash{$key}=&thaw_unescape($value);
                   4593: 	}
1.755     albertel 4594:     }
                   4595:     return %returnhash;
1.407     www      4596: }
                   4597: 
1.1098    foxr     4598: 
1.717     albertel 4599: # --------------------------------------------------------- dumpstore interface
                   4600: 
                   4601: sub dumpstore {
                   4602:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4603:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4604:    if (!$uname) { $uname=$env{'user.name'}; }
                   4605:    my $uhome=&homeserver($uname,$udomain);
                   4606:    if ($regexp) {
                   4607:        $regexp=&escape($regexp);
                   4608:    } else {
                   4609:        $regexp='.';
                   4610:    }
                   4611:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4612:    my @pairs=split(/\&/,$rep);
                   4613:    my %returnhash=();
                   4614:    foreach my $item (@pairs) {
                   4615:        my ($key,$value)=split(/=/,$item,2);
                   4616:        next if ($key =~ /^error: 2 /);
                   4617:        $returnhash{$key}=&thaw_unescape($value);
                   4618:    }
                   4619:    return %returnhash;
1.717     albertel 4620: }
                   4621: 
1.407     www      4622: # -------------------------------------------------------------- keys interface
                   4623: 
                   4624: sub getkeys {
                   4625:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4626:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4627:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4628:    my $uhome=&homeserver($uname,$udomain);
                   4629:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4630:    my @keyarray=();
1.800     albertel 4631:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4632:       next if ($key =~ /^error: 2 /);
1.800     albertel 4633:       push(@keyarray,&unescape($key));
1.407     www      4634:    }
                   4635:    return @keyarray;
1.318     matthew  4636: }
                   4637: 
1.319     matthew  4638: # --------------------------------------------------------------- currentdump
                   4639: sub currentdump {
1.328     matthew  4640:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4641:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4642:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4643:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4644:    my $uhome = &homeserver($sname,$sdom);
                   4645:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4646:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4647:    #
1.318     matthew  4648:    my %returnhash=();
1.319     matthew  4649:    #
                   4650:    if ($rep eq "unknown_cmd") { 
                   4651:        # an old lond will not know currentdump
                   4652:        # Do a dump and make it look like a currentdump
1.822     albertel 4653:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4654:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4655:        my %hash = @tmp;
                   4656:        @tmp=();
1.424     matthew  4657:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4658:    } else {
                   4659:        my @pairs=split(/\&/,$rep);
1.800     albertel 4660:        foreach my $pair (@pairs) {
                   4661:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4662:            my ($symb,$param) = split(/:/,$key);
                   4663:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4664:                                                         &thaw_unescape($value);
1.319     matthew  4665:        }
1.191     harris41 4666:    }
1.12      www      4667:    return %returnhash;
1.424     matthew  4668: }
                   4669: 
                   4670: sub convert_dump_to_currentdump{
                   4671:     my %hash = %{shift()};
                   4672:     my %returnhash;
                   4673:     # Code ripped from lond, essentially.  The only difference
                   4674:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4675:     # we might run in to problems with parameter names =~ /^v\./
                   4676:     while (my ($key,$value) = each(%hash)) {
                   4677:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4678: 	$symb  = &unescape($symb);
                   4679: 	$param = &unescape($param);
1.424     matthew  4680:         next if ($v eq 'version' || $symb eq 'keys');
                   4681:         next if (exists($returnhash{$symb}) &&
                   4682:                  exists($returnhash{$symb}->{$param}) &&
                   4683:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4684:         $returnhash{$symb}->{$param}=$value;
                   4685:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4686:     }
                   4687:     #
                   4688:     # Remove all of the keys in the hashes which keep track of
                   4689:     # the version of the parameter.
                   4690:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4691:         # use a foreach because we are going to delete from the hash.
                   4692:         foreach my $key (keys(%$param_hash)) {
                   4693:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4694:         }
                   4695:     }
                   4696:     return \%returnhash;
1.12      www      4697: }
                   4698: 
1.627     albertel 4699: # ------------------------------------------------------ critical inc interface
                   4700: 
                   4701: sub cinc {
                   4702:     return &inc(@_,'critical');
                   4703: }
                   4704: 
1.449     matthew  4705: # --------------------------------------------------------------- inc interface
                   4706: 
                   4707: sub inc {
1.627     albertel 4708:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4709:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4710:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4711:     my $uhome=&homeserver($uname,$udomain);
                   4712:     my $items='';
                   4713:     if (! ref($store)) {
                   4714:         # got a single value, so use that instead
                   4715:         $items = &escape($store).'=&';
                   4716:     } elsif (ref($store) eq 'SCALAR') {
                   4717:         $items = &escape($$store).'=&';        
                   4718:     } elsif (ref($store) eq 'ARRAY') {
                   4719:         $items = join('=&',map {&escape($_);} @{$store});
                   4720:     } elsif (ref($store) eq 'HASH') {
                   4721:         while (my($key,$value) = each(%{$store})) {
                   4722:             $items.= &escape($key).'='.&escape($value).'&';
                   4723:         }
                   4724:     }
                   4725:     $items=~s/\&$//;
1.627     albertel 4726:     if ($critical) {
                   4727: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4728:     } else {
                   4729: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4730:     }
1.449     matthew  4731: }
                   4732: 
1.12      www      4733: # --------------------------------------------------------------- put interface
                   4734: 
                   4735: sub put {
1.134     albertel 4736:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4737:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4738:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4739:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4740:    my $items='';
1.800     albertel 4741:    foreach my $item (keys(%$storehash)) {
                   4742:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4743:    }
1.12      www      4744:    $items=~s/\&$//;
1.134     albertel 4745:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4746: }
                   4747: 
1.631     albertel 4748: # ------------------------------------------------------------ newput interface
                   4749: 
                   4750: sub newput {
                   4751:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4752:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4753:    if (!$uname) { $uname=$env{'user.name'}; }
                   4754:    my $uhome=&homeserver($uname,$udomain);
                   4755:    my $items='';
                   4756:    foreach my $key (keys(%$storehash)) {
                   4757:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4758:    }
                   4759:    $items=~s/\&$//;
                   4760:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4761: }
                   4762: 
                   4763: # ---------------------------------------------------------  putstore interface
                   4764: 
1.524     raeburn  4765: sub putstore {
1.715     albertel 4766:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4767:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4768:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4769:    my $uhome=&homeserver($uname,$udomain);
                   4770:    my $items='';
1.715     albertel 4771:    foreach my $key (keys(%$storehash)) {
                   4772:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4773:    }
1.715     albertel 4774:    $items=~s/\&$//;
1.716     albertel 4775:    my $esc_symb=&escape($symb);
                   4776:    my $esc_v=&escape($version);
1.715     albertel 4777:    my $reply =
1.716     albertel 4778:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4779: 	      $uhome);
                   4780:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4781:        # gfall back to way things use to be done
1.715     albertel 4782:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4783: 			    $uname);
1.524     raeburn  4784:    }
1.715     albertel 4785:    return $reply;
                   4786: }
                   4787: 
                   4788: sub old_putstore {
1.716     albertel 4789:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4790:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4791:     if (!$uname) { $uname=$env{'user.name'}; }
                   4792:     my $uhome=&homeserver($uname,$udomain);
                   4793:     my %newstorehash;
1.800     albertel 4794:     foreach my $item (keys(%$storehash)) {
                   4795: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4796: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4797:     }
                   4798:     my $items='';
                   4799:     my %allitems = ();
1.800     albertel 4800:     foreach my $item (keys(%newstorehash)) {
                   4801: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4802: 	    my $key = $1.':keys:'.$2;
                   4803: 	    $allitems{$key} .= $3.':';
                   4804: 	}
1.800     albertel 4805: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4806:     }
1.800     albertel 4807:     foreach my $item (keys(%allitems)) {
                   4808: 	$allitems{$item} =~ s/\:$//;
                   4809: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4810:     }
                   4811:     $items=~s/\&$//;
                   4812:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4813: }
                   4814: 
1.47      www      4815: # ------------------------------------------------------ critical put interface
                   4816: 
                   4817: sub cput {
1.134     albertel 4818:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4819:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4820:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4821:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4822:    my $items='';
1.800     albertel 4823:    foreach my $item (keys(%$storehash)) {
                   4824:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4825:    }
1.47      www      4826:    $items=~s/\&$//;
1.134     albertel 4827:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4828: }
                   4829: 
                   4830: # -------------------------------------------------------------- eget interface
                   4831: 
                   4832: sub eget {
1.133     albertel 4833:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4834:    my $items='';
1.800     albertel 4835:    foreach my $item (@$storearr) {
                   4836:        $items.=&escape($item).'&';
1.191     harris41 4837:    }
1.12      www      4838:    $items=~s/\&$//;
1.620     albertel 4839:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4840:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4841:    my $uhome=&homeserver($uname,$udomain);
                   4842:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4843:    my @pairs=split(/\&/,$rep);
                   4844:    my %returnhash=();
1.42      www      4845:    my $i=0;
1.800     albertel 4846:    foreach my $item (@$storearr) {
                   4847:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4848:       $i++;
1.191     harris41 4849:    }
1.12      www      4850:    return %returnhash;
                   4851: }
                   4852: 
1.667     albertel 4853: # ------------------------------------------------------------ tmpput interface
                   4854: sub tmpput {
1.802     raeburn  4855:     my ($storehash,$server,$context)=@_;
1.667     albertel 4856:     my $items='';
1.800     albertel 4857:     foreach my $item (keys(%$storehash)) {
                   4858: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4859:     }
                   4860:     $items=~s/\&$//;
1.802     raeburn  4861:     if (defined($context)) {
                   4862:         $items .= ':'.&escape($context);
                   4863:     }
1.667     albertel 4864:     return &reply("tmpput:$items",$server);
                   4865: }
                   4866: 
                   4867: # ------------------------------------------------------------ tmpget interface
                   4868: sub tmpget {
1.688     albertel 4869:     my ($token,$server)=@_;
                   4870:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4871:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4872:     my %returnhash;
                   4873:     foreach my $item (split(/\&/,$rep)) {
                   4874: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4875:         next if ($key =~ /^error: 2 /);
1.667     albertel 4876: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4877:     }
                   4878:     return %returnhash;
                   4879: }
                   4880: 
1.1113    raeburn  4881: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4882: sub tmpdel {
                   4883:     my ($token,$server)=@_;
                   4884:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4885:     return &reply("tmpdel:$token",$server);
                   4886: }
                   4887: 
1.765     albertel 4888: # -------------------------------------------------- portfolio access checking
                   4889: 
                   4890: sub portfolio_access {
1.766     albertel 4891:     my ($requrl) = @_;
1.765     albertel 4892:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4893:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4894:     if ($result) {
                   4895:         my %setters;
                   4896:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4897:             my ($startblock,$endblock) =
                   4898:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4899:             if ($startblock && $endblock) {
                   4900:                 return 'B';
                   4901:             }
                   4902:         } else {
                   4903:             my ($startblock,$endblock) =
                   4904:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4905:             if ($startblock && $endblock) {
                   4906:                 return 'B';
                   4907:             }
                   4908:         }
                   4909:     }
1.765     albertel 4910:     if ($result eq 'ok') {
1.766     albertel 4911:        return 'F';
1.765     albertel 4912:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4913:        return 'A';
1.765     albertel 4914:     }
1.766     albertel 4915:     return '';
1.765     albertel 4916: }
                   4917: 
                   4918: sub get_portfolio_access {
1.767     albertel 4919:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4920: 
                   4921:     if (!ref($access_hash)) {
                   4922: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4923: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4924: 						   $file_name);
                   4925: 	$access_hash = $access_controls{$file_name};
                   4926:     }
                   4927: 
1.765     albertel 4928:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4929:     my $now = time;
                   4930:     if (ref($access_hash) eq 'HASH') {
                   4931:         foreach my $key (keys(%{$access_hash})) {
                   4932:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4933:             if ($start > $now) {
                   4934:                 next;
                   4935:             }
                   4936:             if ($end && $end<$now) {
                   4937:                 next;
                   4938:             }
                   4939:             if ($scope eq 'public') {
                   4940:                 $public = $key;
                   4941:                 last;
                   4942:             } elsif ($scope eq 'guest') {
                   4943:                 $guest = $key;
                   4944:             } elsif ($scope eq 'domains') {
                   4945:                 push(@domains,$key);
                   4946:             } elsif ($scope eq 'users') {
                   4947:                 push(@users,$key);
                   4948:             } elsif ($scope eq 'course') {
                   4949:                 push(@courses,$key);
                   4950:             } elsif ($scope eq 'group') {
                   4951:                 push(@groups,$key);
                   4952:             }
                   4953:         }
                   4954:         if ($public) {
                   4955:             return 'ok';
                   4956:         }
                   4957:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4958:             if ($guest) {
                   4959:                 return $guest;
                   4960:             }
                   4961:         } else {
                   4962:             if (@domains > 0) {
                   4963:                 foreach my $domkey (@domains) {
                   4964:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4965:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4966:                             return 'ok';
                   4967:                         }
                   4968:                     }
                   4969:                 }
                   4970:             }
                   4971:             if (@users > 0) {
                   4972:                 foreach my $userkey (@users) {
1.865     raeburn  4973:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4974:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4975:                             if (ref($item) eq 'HASH') {
                   4976:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4977:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4978:                                     return 'ok';
                   4979:                                 }
                   4980:                             }
                   4981:                         }
                   4982:                     } 
1.765     albertel 4983:                 }
                   4984:             }
                   4985:             my %roleshash;
                   4986:             my @courses_and_groups = @courses;
                   4987:             push(@courses_and_groups,@groups); 
                   4988:             if (@courses_and_groups > 0) {
                   4989:                 my (%allgroups,%allroles); 
                   4990:                 my ($start,$end,$role,$sec,$group);
                   4991:                 foreach my $envkey (%env) {
1.1060    raeburn  4992:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4993:                         my $cid = $2.'_'.$3; 
                   4994:                         if ($1 eq 'gr') {
                   4995:                             $group = $4;
                   4996:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4997:                         } else {
                   4998:                             if ($4 eq '') {
                   4999:                                 $sec = 'none';
                   5000:                             } else {
                   5001:                                 $sec = $4;
                   5002:                             }
                   5003:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5004:                         }
1.811     albertel 5005:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5006:                         my $cid = $2.'_'.$3;
                   5007:                         if ($4 eq '') {
                   5008:                             $sec = 'none';
                   5009:                         } else {
                   5010:                             $sec = $4;
                   5011:                         }
                   5012:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5013:                     }
                   5014:                 }
                   5015:                 if (keys(%allroles) == 0) {
                   5016:                     return;
                   5017:                 }
                   5018:                 foreach my $key (@courses_and_groups) {
                   5019:                     my %content = %{$$access_hash{$key}};
                   5020:                     my $cnum = $content{'number'};
                   5021:                     my $cdom = $content{'domain'};
                   5022:                     my $cid = $cdom.'_'.$cnum;
                   5023:                     if (!exists($allroles{$cid})) {
                   5024:                         next;
                   5025:                     }    
                   5026:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5027:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5028:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5029:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5030:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5031:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5032:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5033:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5034:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5035:                                         if (grep/^all$/,@sections) {
                   5036:                                             return 'ok';
                   5037:                                         } else {
                   5038:                                             if (grep/^$sec$/,@sections) {
                   5039:                                                 return 'ok';
                   5040:                                             }
                   5041:                                         }
                   5042:                                     }
                   5043:                                 }
                   5044:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5045:                                     if (grep/^none$/,@groups) {
                   5046:                                         return 'ok';
                   5047:                                     }
                   5048:                                 } else {
                   5049:                                     if (grep/^all$/,@groups) {
                   5050:                                         return 'ok';
                   5051:                                     } 
                   5052:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5053:                                         if (grep/^$group$/,@groups) {
                   5054:                                             return 'ok';
                   5055:                                         }
                   5056:                                     }
                   5057:                                 } 
                   5058:                             }
                   5059:                         }
                   5060:                     }
                   5061:                 }
                   5062:             }
                   5063:             if ($guest) {
                   5064:                 return $guest;
                   5065:             }
                   5066:         }
                   5067:     }
                   5068:     return;
                   5069: }
                   5070: 
                   5071: sub course_group_datechecker {
                   5072:     my ($dates,$now,$status) = @_;
                   5073:     my ($start,$end) = split(/\./,$dates);
                   5074:     if (!$start && !$end) {
                   5075:         return 'ok';
                   5076:     }
                   5077:     if (grep/^active$/,@{$status}) {
                   5078:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5079:             return 'ok';
                   5080:         }
                   5081:     }
                   5082:     if (grep/^previous$/,@{$status}) {
                   5083:         if ($end > $now ) {
                   5084:             return 'ok';
                   5085:         }
                   5086:     }
                   5087:     if (grep/^future$/,@{$status}) {
                   5088:         if ($start > $now) {
                   5089:             return 'ok';
                   5090:         }
                   5091:     }
                   5092:     return; 
                   5093: }
                   5094: 
                   5095: sub parse_portfolio_url {
                   5096:     my ($url) = @_;
                   5097: 
                   5098:     my ($type,$udom,$unum,$group,$file_name);
                   5099:     
1.823     albertel 5100:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5101: 	$type = 1;
                   5102:         $udom = $1;
                   5103:         $unum = $2;
                   5104:         $file_name = $3;
1.823     albertel 5105:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5106: 	$type = 2;
                   5107:         $udom = $1;
                   5108:         $unum = $2;
                   5109:         $group = $3;
                   5110:         $file_name = $3.'/'.$4;
                   5111:     }
                   5112:     if (wantarray) {
                   5113: 	return ($type,$udom,$unum,$file_name,$group);
                   5114:     }
                   5115:     return $type;
                   5116: }
                   5117: 
                   5118: sub is_portfolio_url {
                   5119:     my ($url) = @_;
                   5120:     return scalar(&parse_portfolio_url($url));
                   5121: }
                   5122: 
1.798     raeburn  5123: sub is_portfolio_file {
                   5124:     my ($file) = @_;
1.820     raeburn  5125:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5126:         return 1;
                   5127:     }
                   5128:     return;
                   5129: }
                   5130: 
1.976     raeburn  5131: sub usertools_access {
1.1084    raeburn  5132:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5133:     my ($access,%tools);
                   5134:     if ($context eq '') {
                   5135:         $context = 'tools';
                   5136:     }
                   5137:     if ($context eq 'requestcourses') {
                   5138:         %tools = (
                   5139:                       official   => 1,
                   5140:                       unofficial => 1,
1.1006    raeburn  5141:                       community  => 1,
1.985     raeburn  5142:                  );
                   5143:     } else {
                   5144:         %tools = (
                   5145:                       aboutme   => 1,
                   5146:                       blog      => 1,
                   5147:                       portfolio => 1,
                   5148:                  );
                   5149:     }
1.976     raeburn  5150:     return if (!defined($tools{$tool}));
                   5151: 
                   5152:     if ((!defined($udom)) || (!defined($uname))) {
                   5153:         $udom = $env{'user.domain'};
                   5154:         $uname = $env{'user.name'};
                   5155:     }
                   5156: 
1.978     raeburn  5157:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5158:         if ($action ne 'reload') {
1.985     raeburn  5159:             if ($context eq 'requestcourses') {
                   5160:                 return $env{'environment.canrequest.'.$tool};
                   5161:             } else {
                   5162:                 return $env{'environment.availabletools.'.$tool};
                   5163:             }
                   5164:         }
1.976     raeburn  5165:     }
                   5166: 
                   5167:     my ($toolstatus,$inststatus);
                   5168: 
1.985     raeburn  5169:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5170:          ($action ne 'reload')) {
                   5171:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5172:         $inststatus = $env{'environment.inststatus'};
                   5173:     } else {
1.1084    raeburn  5174:         if (ref($userenvref) eq 'HASH') {
                   5175:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5176:             $inststatus = $userenvref->{'inststatus'};
                   5177:         } else {
                   5178:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5179:             $toolstatus = $userenv{$context.'.'.$tool};
                   5180:             $inststatus = $userenv{'inststatus'};
                   5181:         }
1.976     raeburn  5182:     }
                   5183: 
                   5184:     if ($toolstatus ne '') {
                   5185:         if ($toolstatus) {
                   5186:             $access = 1;
                   5187:         } else {
                   5188:             $access = 0;
                   5189:         }
                   5190:         return $access;
                   5191:     }
                   5192: 
1.1084    raeburn  5193:     my ($is_adv,%domdef);
                   5194:     if (ref($is_advref) eq 'HASH') {
                   5195:         $is_adv = $is_advref->{'is_adv'};
                   5196:     } else {
                   5197:         $is_adv = &is_advanced_user($udom,$uname);
                   5198:     }
                   5199:     if (ref($domdefref) eq 'HASH') {
                   5200:         %domdef = %{$domdefref};
                   5201:     } else {
                   5202:         %domdef = &get_domain_defaults($udom);
                   5203:     }
1.976     raeburn  5204:     if (ref($domdef{$tool}) eq 'HASH') {
                   5205:         if ($is_adv) {
                   5206:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5207:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5208:                     $access = 1;
                   5209:                 } else {
                   5210:                     $access = 0;
                   5211:                 }
                   5212:                 return $access;
                   5213:             }
                   5214:         }
                   5215:         if ($inststatus ne '') {
                   5216:             my ($hasaccess,$hasnoaccess);
                   5217:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5218:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5219:                     if ($domdef{$tool}{$affiliation}) {
                   5220:                         $hasaccess = 1;
                   5221:                     } else {
                   5222:                         $hasnoaccess = 1;
                   5223:                     }
                   5224:                 }
                   5225:             }
                   5226:             if ($hasaccess || $hasnoaccess) {
                   5227:                 if ($hasaccess) {
                   5228:                     $access = 1;
                   5229:                 } elsif ($hasnoaccess) {
                   5230:                     $access = 0; 
                   5231:                 }
                   5232:                 return $access;
                   5233:             }
                   5234:         } else {
                   5235:             if ($domdef{$tool}{'default'} ne '') {
                   5236:                 if ($domdef{$tool}{'default'}) {
                   5237:                     $access = 1;
                   5238:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5239:                     $access = 0;
                   5240:                 }
                   5241:                 return $access;
                   5242:             }
                   5243:         }
                   5244:     } else {
1.985     raeburn  5245:         if ($context eq 'tools') {
                   5246:             $access = 1;
                   5247:         } else {
                   5248:             $access = 0;
                   5249:         }
1.976     raeburn  5250:         return $access;
                   5251:     }
                   5252: }
                   5253: 
1.1050    raeburn  5254: sub is_course_owner {
                   5255:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5256:     if (($udom eq '') || ($uname eq '')) {
                   5257:         $udom = $env{'user.domain'};
                   5258:         $uname = $env{'user.name'};
                   5259:     }
                   5260:     unless (($udom eq '') || ($uname eq '')) {
                   5261:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5262:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5263:                 return 1;
                   5264:             } else {
                   5265:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5266:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5267:                     return 1;
                   5268:                 }
                   5269:             }
                   5270:         }
                   5271:     }
                   5272:     return;
                   5273: }
                   5274: 
1.976     raeburn  5275: sub is_advanced_user {
                   5276:     my ($udom,$uname) = @_;
1.1085    raeburn  5277:     if ($udom ne '' && $uname ne '') {
                   5278:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5279:             return $env{'user.adv'};  
                   5280:         }
                   5281:     }
1.976     raeburn  5282:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5283:     my %allroles;
                   5284:     my $is_adv;
                   5285:     foreach my $role (keys(%roleshash)) {
                   5286:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5287:         my $area = '/'.$tdomain.'/'.$trest;
                   5288:         if ($sec ne '') {
                   5289:             $area .= '/'.$sec;
                   5290:         }
                   5291:         if (($area ne '') && ($trole ne '')) {
                   5292:             my $spec=$trole.'.'.$area;
                   5293:             if ($trole =~ /^cr\//) {
                   5294:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5295:             } elsif ($trole ne 'gr') {
                   5296:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5297:             }
                   5298:         }
                   5299:     }
                   5300:     foreach my $role (keys(%allroles)) {
                   5301:         last if ($is_adv);
                   5302:         foreach my $item (split(/:/,$allroles{$role})) {
                   5303:             if ($item ne '') {
                   5304:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5305:                 if ($privilege eq 'adv') {
                   5306:                     $is_adv = 1;
                   5307:                     last;
                   5308:                 }
                   5309:             }
                   5310:         }
                   5311:     }
                   5312:     return $is_adv;
                   5313: }
1.798     raeburn  5314: 
1.1035    raeburn  5315: sub check_can_request {
1.1036    raeburn  5316:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5317:     my $canreq = 0;
                   5318:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5319:     my @options = ('approval','validate','autolimit');
                   5320:     my $optregex = join('|',@options);
                   5321:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5322:         foreach my $type (@{$types}) {
                   5323:             if (&usertools_access($env{'user.name'},
                   5324:                                   $env{'user.domain'},
                   5325:                                   $type,undef,'requestcourses')) {
                   5326:                 $canreq ++;
1.1036    raeburn  5327:                 if (ref($request_domains) eq 'HASH') {
                   5328:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5329:                 }
1.1035    raeburn  5330:                 if ($dom eq $env{'user.domain'}) {
                   5331:                     $can_request->{$type} = 1;
                   5332:                 }
                   5333:             }
                   5334:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5335:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5336:                 if (@curr > 0) {
1.1036    raeburn  5337:                     foreach my $item (@curr) {
                   5338:                         if (ref($request_domains) eq 'HASH') {
                   5339:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5340:                             if ($otherdom ne '') {
                   5341:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5342:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5343:                                         push(@{$request_domains->{$type}},$otherdom);
                   5344:                                     }
                   5345:                                 } else {
                   5346:                                     push(@{$request_domains->{$type}},$otherdom);
                   5347:                                 }
                   5348:                             }
                   5349:                         }
                   5350:                     }
                   5351:                     unless($dom eq $env{'user.domain'}) {
                   5352:                         $canreq ++;
1.1035    raeburn  5353:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5354:                             $can_request->{$type} = 1;
                   5355:                         }
                   5356:                     }
                   5357:                 }
                   5358:             }
                   5359:         }
                   5360:     }
                   5361:     return $canreq;
                   5362: }
                   5363: 
1.341     www      5364: # ---------------------------------------------- Custom access rule evaluation
                   5365: 
                   5366: sub customaccess {
                   5367:     my ($priv,$uri)=@_;
1.807     albertel 5368:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5369:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5370:     $udom = &LONCAPA::clean_domain($udom);
                   5371:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5372:     my $access=0;
1.800     albertel 5373:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5374: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5375: 	if ($type eq 'user') {
                   5376: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5377: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5378: 		if ($tdom) {
                   5379: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5380: 		}
1.896     albertel 5381: 		if ($tuname) {
                   5382: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5383: 		}
                   5384: 		$access=($effect eq 'allow');
                   5385: 		last;
                   5386: 	    }
                   5387: 	} else {
                   5388: 	    if ($role) {
                   5389: 		if ($role ne $urole) { next; }
                   5390: 	    }
                   5391: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5392: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5393: 		if ($tdom) {
                   5394: 		    if ($tdom ne $udom) { next; }
                   5395: 		}
                   5396: 		if ($tcrs) {
                   5397: 		    if ($tcrs ne $ucrs) { next; }
                   5398: 		}
                   5399: 		if ($tsec) {
                   5400: 		    if ($tsec ne $usec) { next; }
                   5401: 		}
                   5402: 		$access=($effect eq 'allow');
                   5403: 		last;
                   5404: 	    }
                   5405: 	    if ($realm eq '' && $role eq '') {
                   5406: 		$access=($effect eq 'allow');
                   5407: 	    }
1.402     bowersj2 5408: 	}
1.341     www      5409:     }
                   5410:     return $access;
                   5411: }
                   5412: 
1.103     harris41 5413: # ------------------------------------------------- Check for a user privilege
1.12      www      5414: 
                   5415: sub allowed {
1.810     raeburn  5416:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5417:     my $ver_orguri=$uri;
1.439     www      5418:     $uri=&deversion($uri);
1.152     www      5419:     my $orguri=$uri;
1.52      www      5420:     $uri=&declutter($uri);
1.809     raeburn  5421: 
1.810     raeburn  5422:     if ($priv eq 'evb') {
                   5423: # Evade communication block restrictions for specified role in a course
                   5424:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5425:             return $1;
                   5426:         } else {
                   5427:             return;
                   5428:         }
                   5429:     }
                   5430: 
1.620     albertel 5431:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5432: # Free bre access to adm and meta resources
1.775     albertel 5433:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5434: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5435: 	&& ($priv eq 'bre')) {
1.14      www      5436: 	return 'F';
1.159     www      5437:     }
                   5438: 
1.545     banghart 5439: # Free bre access to user's own portfolio contents
1.714     raeburn  5440:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5441:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5442: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5443:         my %setters;
                   5444:         my ($startblock,$endblock) = 
                   5445:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5446:         if ($startblock && $endblock) {
                   5447:             return 'B';
                   5448:         } else {
                   5449:             return 'F';
                   5450:         }
1.545     banghart 5451:     }
                   5452: 
1.762     raeburn  5453: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5454:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5455:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5456:         if (exists($env{'request.course.id'})) {
                   5457:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5458:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5459:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5460:                 my $courseprivid=$env{'request.course.id'};
                   5461:                 $courseprivid=~s/\_/\//;
                   5462:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5463:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5464:                     return $1; 
1.762     raeburn  5465:                 } else {
                   5466:                     if ($env{'request.course.sec'}) {
                   5467:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5468:                     }
                   5469:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5470:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5471:                         return $2;
                   5472:                     }
1.714     raeburn  5473:                 }
                   5474:             }
                   5475:         }
                   5476:     }
                   5477: 
1.159     www      5478: # Free bre to public access
                   5479: 
                   5480:     if ($priv eq 'bre') {
1.238     www      5481:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5482: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5483:            return 'F'; 
                   5484:         }
1.238     www      5485:         if ($copyright eq 'priv') {
                   5486:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5487: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5488: 		return '';
                   5489:             }
                   5490:         }
                   5491:         if ($copyright eq 'domain') {
                   5492:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5493: 	    unless (($env{'user.domain'} eq $1) ||
                   5494:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5495: 		return '';
                   5496:             }
1.262     matthew  5497:         }
1.620     albertel 5498:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5499:             # Library role, so allow browsing of resources in this domain.
                   5500:             return 'F';
1.238     www      5501:         }
1.341     www      5502:         if ($copyright eq 'custom') {
                   5503: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5504:         }
1.14      www      5505:     }
1.264     matthew  5506:     # Domain coordinator is trying to create a course
1.620     albertel 5507:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5508:         # uri is the requested domain in this case.
                   5509:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5510:         # a role of dc for the domain in question.
1.620     albertel 5511:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5512:     }
1.29      www      5513: 
1.52      www      5514:     my $thisallowed='';
                   5515:     my $statecond=0;
                   5516:     my $courseprivid='';
                   5517: 
1.1039    raeburn  5518:     my $ownaccess;
1.1043    raeburn  5519:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5520:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5521:         if ($uri eq '') {
                   5522:             $ownaccess = 1;
                   5523:         } else {
                   5524:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5525:                 my $udom = $env{'user.domain'};
                   5526:                 my $uname = $env{'user.name'};
                   5527:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5528:                     $ownaccess = 1;
1.1040    raeburn  5529:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5530:                     unless ($uri =~ m{\.\./}) {
                   5531:                         $ownaccess = 1;
                   5532:                     }
                   5533:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5534:                     my $now = time;
                   5535:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5536:                         my $adom = $1;
                   5537:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5538:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5539:                                 my ($start,$end) = split('.',$env{$key});
                   5540:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5541:                                     $ownaccess = 1;
                   5542:                                     last;
                   5543:                                 }
                   5544:                             }
                   5545:                         }
                   5546:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5547:                         my $adom = $1;
                   5548:                         my $aname = $2;
1.1042    raeburn  5549:                         foreach my $role ('ca','aa') { 
                   5550:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5551:                                 my ($start,$end) =
                   5552:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5553:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5554:                                     $ownaccess = 1;
                   5555:                                     last;
                   5556:                                 }
1.1039    raeburn  5557:                             }
                   5558:                         }
                   5559:                     }
                   5560:                 }
                   5561:             }
                   5562:         }
                   5563:     }
                   5564: 
1.52      www      5565: # Course
                   5566: 
1.620     albertel 5567:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5568:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5569:             $thisallowed.=$1;
                   5570:         }
1.52      www      5571:     }
1.29      www      5572: 
1.52      www      5573: # Domain
                   5574: 
1.620     albertel 5575:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5576:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5577:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5578:             $thisallowed.=$1;
                   5579:         }
1.12      www      5580:     }
1.52      www      5581: 
                   5582: # Course: uri itself is a course
1.66      www      5583:     my $courseuri=$uri;
                   5584:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5585:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5586: 
1.620     albertel 5587:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5588:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5589:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5590:             $thisallowed.=$1;
                   5591:         }
1.12      www      5592:     }
1.29      www      5593: 
1.665     albertel 5594: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5595: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5596:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5597: 	$thisallowed='';
1.671     raeburn  5598:         my ($match)=&is_on_map($uri);
                   5599:         if ($match) {
                   5600:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5601:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5602:                 $thisallowed.=$1;
                   5603:             }
                   5604:         } else {
1.705     albertel 5605:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5606:             if ($refuri) {
                   5607:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5608:                     $thisallowed='F';
1.671     raeburn  5609:                 } else {
                   5610:                     $refuri=&declutter($refuri);
                   5611:                     my ($match) = &is_on_map($refuri);
                   5612:                     if ($match) {
                   5613:                         $thisallowed='F';
                   5614:                     }
1.669     raeburn  5615:                 }
1.671     raeburn  5616:             }
                   5617:         }
1.314     www      5618:     }
1.492     albertel 5619: 
1.766     albertel 5620:     if ($priv eq 'bre'
                   5621: 	&& $thisallowed ne 'F' 
                   5622: 	&& $thisallowed ne '2'
                   5623: 	&& &is_portfolio_url($uri)) {
                   5624: 	$thisallowed = &portfolio_access($uri);
                   5625:     }
                   5626:     
1.52      www      5627: # Full access at system, domain or course-wide level? Exit.
1.29      www      5628:     if ($thisallowed=~/F/) {
                   5629: 	return 'F';
                   5630:     }
                   5631: 
1.52      www      5632: # If this is generating or modifying users, exit with special codes
1.29      www      5633: 
1.643     www      5634:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5635: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5636: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5637: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5638: 	    unless ($auname) { return $thisallowed; }
                   5639: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5640: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5641: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5642: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5643: 	}
1.52      www      5644: 	return $thisallowed;
                   5645:     }
                   5646: #
1.103     harris41 5647: # Gathered so far: system, domain and course wide privileges
1.52      www      5648: #
                   5649: # Course: See if uri or referer is an individual resource that is part of 
                   5650: # the course
                   5651: 
1.620     albertel 5652:     if ($env{'request.course.id'}) {
1.232     www      5653: 
1.620     albertel 5654:        $courseprivid=$env{'request.course.id'};
                   5655:        if ($env{'request.course.sec'}) {
                   5656:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5657:        }
                   5658:        $courseprivid=~s/\_/\//;
                   5659:        my $checkreferer=1;
1.232     www      5660:        my ($match,$cond)=&is_on_map($uri);
                   5661:        if ($match) {
                   5662:            $statecond=$cond;
1.620     albertel 5663:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5664:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5665:                $thisallowed.=$1;
                   5666:                $checkreferer=0;
                   5667:            }
1.29      www      5668:        }
1.83      www      5669:        
1.148     www      5670:        if ($checkreferer) {
1.620     albertel 5671: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5672:             unless ($refuri) {
1.800     albertel 5673:                 foreach my $key (keys(%env)) {
                   5674: 		    if ($key=~/^httpref\..*\*/) {
                   5675: 			my $pattern=$key;
1.156     www      5676:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5677:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5678:                         $pattern=~s/\//\\\//g;
1.152     www      5679:                         if ($orguri=~/$pattern/) {
1.800     albertel 5680: 			    $refuri=$env{$key};
1.148     www      5681:                         }
                   5682:                     }
1.191     harris41 5683:                 }
1.148     www      5684:             }
1.232     www      5685: 
1.148     www      5686:          if ($refuri) { 
1.152     www      5687: 	  $refuri=&declutter($refuri);
1.232     www      5688:           my ($match,$cond)=&is_on_map($refuri);
                   5689:             if ($match) {
                   5690:               my $refstatecond=$cond;
1.620     albertel 5691:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5692:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5693:                   $thisallowed.=$1;
1.53      www      5694:                   $uri=$refuri;
                   5695:                   $statecond=$refstatecond;
1.52      www      5696:               }
                   5697:           }
1.148     www      5698:         }
1.29      www      5699:        }
1.52      www      5700:    }
1.29      www      5701: 
1.52      www      5702: #
1.103     harris41 5703: # Gathered now: all privileges that could apply, and condition number
1.52      www      5704: # 
                   5705: #
                   5706: # Full or no access?
                   5707: #
1.29      www      5708: 
1.52      www      5709:     if ($thisallowed=~/F/) {
                   5710: 	return 'F';
                   5711:     }
1.29      www      5712: 
1.52      www      5713:     unless ($thisallowed) {
                   5714:         return '';
                   5715:     }
1.29      www      5716: 
1.52      www      5717: # Restrictions exist, deal with them
                   5718: #
                   5719: #   C:according to course preferences
                   5720: #   R:according to resource settings
                   5721: #   L:unless locked
                   5722: #   X:according to user session state
                   5723: #
                   5724: 
                   5725: # Possibly locked functionality, check all courses
1.54      www      5726: # Locks might take effect only after 10 minutes cache expiration for other
                   5727: # courses, and 2 minutes for current course
1.52      www      5728: 
                   5729:     my $envkey;
                   5730:     if ($thisallowed=~/L/) {
1.1000    raeburn  5731:         foreach $envkey (keys(%env)) {
1.54      www      5732:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5733:                my $courseid=$2;
                   5734:                my $roleid=$1.'.'.$2;
1.92      www      5735:                $courseid=~s/^\///;
1.54      www      5736:                my $expiretime=600;
1.620     albertel 5737:                if ($env{'request.role'} eq $roleid) {
1.54      www      5738: 		  $expiretime=120;
                   5739:                }
                   5740: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5741:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5742:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5743: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5744:                }
1.620     albertel 5745:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5746:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5747: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5748:                        &log($env{'user.domain'},$env{'user.name'},
                   5749:                             $env{'user.home'},
1.57      www      5750:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5751:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5752:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5753: 		       return '';
                   5754:                    }
                   5755:                }
1.620     albertel 5756:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5757:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5758: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5759:                        &log($env{'user.domain'},$env{'user.name'},
                   5760:                             $env{'user.home'},
1.57      www      5761:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5762:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5763:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5764: 		       return '';
                   5765:                    }
                   5766:                }
                   5767: 	   }
1.29      www      5768:        }
1.52      www      5769:     }
                   5770:    
                   5771: #
                   5772: # Rest of the restrictions depend on selected course
                   5773: #
                   5774: 
1.620     albertel 5775:     unless ($env{'request.course.id'}) {
1.766     albertel 5776: 	if ($thisallowed eq 'A') {
                   5777: 	    return 'A';
1.814     raeburn  5778:         } elsif ($thisallowed eq 'B') {
                   5779:             return 'B';
1.766     albertel 5780: 	} else {
                   5781: 	    return '1';
                   5782: 	}
1.52      www      5783:     }
1.29      www      5784: 
1.52      www      5785: #
                   5786: # Now user is definitely in a course
                   5787: #
1.53      www      5788: 
                   5789: 
                   5790: # Course preferences
                   5791: 
                   5792:    if ($thisallowed=~/C/) {
1.620     albertel 5793:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5794:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5795:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5796: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5797: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5798: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5799: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5800: 			$env{'request.course.id'});
                   5801: 	   }
1.237     www      5802:            return '';
                   5803:        }
                   5804: 
1.620     albertel 5805:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5806: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5807: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5808: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5809: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5810: 			$env{'request.course.id'});
                   5811: 	   }
1.54      www      5812:            return '';
                   5813:        }
1.53      www      5814:    }
                   5815: 
                   5816: # Resource preferences
                   5817: 
                   5818:    if ($thisallowed=~/R/) {
1.620     albertel 5819:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5820:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5821: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5822: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5823: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5824: 	   }
                   5825: 	   return '';
1.54      www      5826:        }
1.53      www      5827:    }
1.30      www      5828: 
1.246     www      5829: # Restricted by state or randomout?
1.30      www      5830: 
1.52      www      5831:    if ($thisallowed=~/X/) {
1.620     albertel 5832:       if ($env{'acc.randomout'}) {
1.579     albertel 5833: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5834:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5835:             return ''; 
                   5836:          }
1.247     www      5837:       }
                   5838:       if (&condval($statecond)) {
1.52      www      5839: 	 return '2';
                   5840:       } else {
                   5841:          return '';
                   5842:       }
                   5843:    }
1.30      www      5844: 
1.766     albertel 5845:     if ($thisallowed eq 'A') {
                   5846: 	return 'A';
1.814     raeburn  5847:     } elsif ($thisallowed eq 'B') {
                   5848:         return 'B';
1.766     albertel 5849:     }
1.52      www      5850:    return 'F';
1.232     www      5851: }
                   5852: 
1.710     albertel 5853: sub split_uri_for_cond {
                   5854:     my $uri=&deversion(&declutter(shift));
                   5855:     my @uriparts=split(/\//,$uri);
                   5856:     my $filename=pop(@uriparts);
                   5857:     my $pathname=join('/',@uriparts);
                   5858:     return ($pathname,$filename);
                   5859: }
1.232     www      5860: # --------------------------------------------------- Is a resource on the map?
                   5861: 
                   5862: sub is_on_map {
1.710     albertel 5863:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5864:     #Trying to find the conditional for the file
1.620     albertel 5865:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5866: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5867:     if ($match) {
1.289     bowersj2 5868: 	return (1,$1);
                   5869:     } else {
1.434     www      5870: 	return (0,0);
1.289     bowersj2 5871:     }
1.12      www      5872: }
                   5873: 
1.427     www      5874: # --------------------------------------------------------- Get symb from alias
                   5875: 
                   5876: sub get_symb_from_alias {
                   5877:     my $symb=shift;
                   5878:     my ($map,$resid,$url)=&decode_symb($symb);
                   5879: # Already is a symb
                   5880:     if ($url) { return $symb; }
                   5881: # Must be an alias
                   5882:     my $aliassymb='';
                   5883:     my %bighash;
1.620     albertel 5884:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5885:                             &GDBM_READER(),0640)) {
                   5886:         my $rid=$bighash{'mapalias_'.$symb};
                   5887: 	if ($rid) {
                   5888: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5889: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5890: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5891: 	}
                   5892:         untie %bighash;
                   5893:     }
                   5894:     return $aliassymb;
                   5895: }
                   5896: 
1.12      www      5897: # ----------------------------------------------------------------- Define Role
                   5898: 
                   5899: sub definerole {
                   5900:   if (allowed('mcr','/')) {
                   5901:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5902:     foreach my $role (split(':',$sysrole)) {
                   5903: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5904:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5905:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5906: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5907:                return "refused:s:$crole&$cqual"; 
                   5908:             }
                   5909:         }
1.191     harris41 5910:     }
1.800     albertel 5911:     foreach my $role (split(':',$domrole)) {
                   5912: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5913:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5914:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5915: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5916:                return "refused:d:$crole&$cqual"; 
                   5917:             }
                   5918:         }
1.191     harris41 5919:     }
1.800     albertel 5920:     foreach my $role (split(':',$courole)) {
                   5921: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5922:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5923:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5924: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5925:                return "refused:c:$crole&$cqual"; 
                   5926:             }
                   5927:         }
1.191     harris41 5928:     }
1.620     albertel 5929:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5930:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5931: 	        "rolesdef_$rolename=".
                   5932:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5933:     return reply($command,$env{'user.home'});
1.12      www      5934:   } else {
                   5935:     return 'refused';
                   5936:   }
1.105     harris41 5937: }
                   5938: 
                   5939: # ---------------- Make a metadata query against the network of library servers
                   5940: 
                   5941: sub metadata_query {
1.244     matthew  5942:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5943:     my %rhash;
1.845     albertel 5944:     my %libserv = &all_library();
1.244     matthew  5945:     my @server_list = (defined($server_array) ? @$server_array
                   5946:                                               : keys(%libserv) );
                   5947:     for my $server (@server_list) {
1.118     harris41 5948: 	unless ($custom or $customshow) {
                   5949: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5950: 	    $rhash{$server}=$reply;
                   5951: 	}
                   5952: 	else {
                   5953: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5954: 			     &escape($custom).':'.&escape($customshow),
                   5955: 			     $server);
                   5956: 	    $rhash{$server}=$reply;
                   5957: 	}
1.112     harris41 5958:     }
1.118     harris41 5959:     return \%rhash;
1.240     www      5960: }
                   5961: 
                   5962: # ----------------------------------------- Send log queries and wait for reply
                   5963: 
                   5964: sub log_query {
                   5965:     my ($uname,$udom,$query,%filters)=@_;
                   5966:     my $uhome=&homeserver($uname,$udom);
                   5967:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5968:     my $uhost=&hostname($uhome);
1.800     albertel 5969:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5970:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5971:                        $uhome);
1.479     albertel 5972:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5973:     return get_query_reply($queryid);
                   5974: }
                   5975: 
1.818     raeburn  5976: # -------------------------- Update MySQL table for portfolio file
                   5977: 
                   5978: sub update_portfolio_table {
1.821     raeburn  5979:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5980:     if ($group ne '') {
                   5981:         $file_name =~s /^\Q$group\E//;
                   5982:     }
1.818     raeburn  5983:     my $homeserver = &homeserver($uname,$udom);
                   5984:     my $queryid=
1.821     raeburn  5985:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5986:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5987:     my $reply = &get_query_reply($queryid);
                   5988:     return $reply;
                   5989: }
                   5990: 
1.899     raeburn  5991: # -------------------------- Update MySQL allusers table
                   5992: 
                   5993: sub update_allusers_table {
                   5994:     my ($uname,$udom,$names) = @_;
                   5995:     my $homeserver = &homeserver($uname,$udom);
                   5996:     my $queryid=
                   5997:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5998:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5999:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6000:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6001:                'generation='.&escape($names->{'generation'}).'%%'.
                   6002:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6003:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6004:     return;
1.899     raeburn  6005: }
                   6006: 
1.508     raeburn  6007: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6008: 
                   6009: sub fetch_enrollment_query {
1.511     raeburn  6010:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6011:     my $homeserver;
1.547     raeburn  6012:     my $maxtries = 1;
1.508     raeburn  6013:     if ($context eq 'automated') {
                   6014:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6015:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6016:     } else {
                   6017:         $homeserver = &homeserver($cnum,$dom);
                   6018:     }
1.838     albertel 6019:     my $host=&hostname($homeserver);
1.506     raeburn  6020:     my $cmd = '';
1.1000    raeburn  6021:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6022:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6023:     }
                   6024:     $cmd =~ s/%%$//;
                   6025:     $cmd = &escape($cmd);
                   6026:     my $query = 'fetchenrollment';
1.620     albertel 6027:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6028:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6029:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6030:         return 'error: '.$queryid;
                   6031:     }
1.506     raeburn  6032:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6033:     my $tries = 1;
                   6034:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6035:         $reply = &get_query_reply($queryid);
                   6036:         $tries ++;
                   6037:     }
1.526     raeburn  6038:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6039:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6040:     } else {
1.901     albertel 6041:         my @responses = split(/:/,$reply);
1.515     raeburn  6042:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6043:             foreach my $line (@responses) {
                   6044:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6045:                 $$replyref{$key} = $value;
                   6046:             }
                   6047:         } else {
1.1117    foxr     6048:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6049:             foreach my $line (@responses) {
                   6050:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6051:                 $$replyref{$key} = $value;
                   6052:                 if ($value > 0) {
1.800     albertel 6053:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6054:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6055:                         my $destname = $pathname.'/'.$filename;
                   6056:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6057:                         if ($xml_classlist =~ /^error/) {
                   6058:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6059:                         } else {
1.506     raeburn  6060:                             if ( open(FILE,">$destname") ) {
                   6061:                                 print FILE &unescape($xml_classlist);
                   6062:                                 close(FILE);
1.526     raeburn  6063:                             } else {
                   6064:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6065:                             }
                   6066:                         }
                   6067:                     }
                   6068:                 }
                   6069:             }
                   6070:         }
                   6071:         return 'ok';
                   6072:     }
                   6073:     return 'error';
                   6074: }
                   6075: 
1.242     www      6076: sub get_query_reply {
                   6077:     my $queryid=shift;
1.1117    foxr     6078:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6079:     my $reply='';
                   6080:     for (1..100) {
                   6081: 	sleep 2;
                   6082:         if (-e $replyfile.'.end') {
1.448     albertel 6083: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6084: 		$reply = join('',<$fh>);
                   6085: 		close($fh);
1.240     www      6086: 	   } else { return 'error: reply_file_error'; }
1.242     www      6087:            return &unescape($reply);
                   6088: 	}
1.240     www      6089:     }
1.242     www      6090:     return 'timeout:'.$queryid;
1.240     www      6091: }
                   6092: 
                   6093: sub courselog_query {
1.241     www      6094: #
                   6095: # possible filters:
                   6096: # url: url or symb
                   6097: # username
                   6098: # domain
                   6099: # action: view, submit, grade
                   6100: # start: timestamp
                   6101: # end: timestamp
                   6102: #
1.240     www      6103:     my (%filters)=@_;
1.620     albertel 6104:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6105:     if ($filters{'url'}) {
                   6106: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6107:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6108:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6109:     }
1.620     albertel 6110:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6111:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6112:     return &log_query($cname,$cdom,'courselog',%filters);
                   6113: }
                   6114: 
                   6115: sub userlog_query {
1.858     raeburn  6116: #
                   6117: # possible filters:
                   6118: # action: log check role
                   6119: # start: timestamp
                   6120: # end: timestamp
                   6121: #
1.240     www      6122:     my ($uname,$udom,%filters)=@_;
                   6123:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6124: }
                   6125: 
1.506     raeburn  6126: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6127: 
                   6128: sub auto_run {
1.508     raeburn  6129:     my ($cnum,$cdom) = @_;
1.876     raeburn  6130:     my $response = 0;
                   6131:     my $settings;
                   6132:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6133:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6134:         $settings = $domconfig{'autoenroll'};
                   6135:         if ($settings->{'run'} eq '1') {
                   6136:             $response = 1;
                   6137:         }
                   6138:     } else {
1.934     raeburn  6139:         my $homeserver;
                   6140:         if (&is_course($cdom,$cnum)) {
                   6141:             $homeserver = &homeserver($cnum,$cdom);
                   6142:         } else {
                   6143:             $homeserver = &domain($cdom,'primary');
                   6144:         }
                   6145:         if ($homeserver ne 'no_host') {
                   6146:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6147:         }
1.876     raeburn  6148:     }
1.506     raeburn  6149:     return $response;
                   6150: }
1.776     albertel 6151: 
1.506     raeburn  6152: sub auto_get_sections {
1.508     raeburn  6153:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6154:     my $homeserver;
                   6155:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6156:         $homeserver = &homeserver($cnum,$cdom);
                   6157:     }
                   6158:     if (!defined($homeserver)) { 
                   6159:         if ($cdom =~ /^$match_domain$/) {
                   6160:             $homeserver = &domain($cdom,'primary');
                   6161:         }
                   6162:     }
                   6163:     my @secs;
                   6164:     if (defined($homeserver)) {
                   6165:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6166:         unless ($response eq 'refused') {
                   6167:             @secs = split(/:/,$response);
                   6168:         }
1.506     raeburn  6169:     }
                   6170:     return @secs;
                   6171: }
1.776     albertel 6172: 
1.506     raeburn  6173: sub auto_new_course {
1.1099    raeburn  6174:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6175:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6176:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6177:     return $response;
                   6178: }
1.776     albertel 6179: 
1.506     raeburn  6180: sub auto_validate_courseID {
1.508     raeburn  6181:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6182:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6183:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6184:     return $response;
                   6185: }
1.776     albertel 6186: 
1.1007    raeburn  6187: sub auto_validate_instcode {
1.1020    raeburn  6188:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6189:     my ($homeserver,$response);
                   6190:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6191:         $homeserver = &homeserver($cnum,$cdom);
                   6192:     }
                   6193:     if (!defined($homeserver)) {
                   6194:         if ($cdom =~ /^$match_domain$/) {
                   6195:             $homeserver = &domain($cdom,'primary');
                   6196:         }
                   6197:     }
1.1065    raeburn  6198:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6199:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6200:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6201:     return ($outcome,$description);
1.1007    raeburn  6202: }
                   6203: 
1.506     raeburn  6204: sub auto_create_password {
1.873     raeburn  6205:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6206:     my ($homeserver,$response);
1.506     raeburn  6207:     my $create_passwd = 0;
                   6208:     my $authchk = '';
1.873     raeburn  6209:     if ($udom =~ /^$match_domain$/) {
                   6210:         $homeserver = &domain($udom,'primary');
                   6211:     }
                   6212:     if ($homeserver eq '') {
                   6213:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6214:             $homeserver = &homeserver($cnum,$cdom);
                   6215:         }
                   6216:     }
                   6217:     if ($homeserver eq '') {
                   6218:         $authchk = 'nodomain';
1.506     raeburn  6219:     } else {
1.873     raeburn  6220:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6221:         if ($response eq 'refused') {
                   6222:             $authchk = 'refused';
                   6223:         } else {
1.901     albertel 6224:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6225:         }
1.506     raeburn  6226:     }
                   6227:     return ($authparam,$create_passwd,$authchk);
                   6228: }
                   6229: 
1.706     raeburn  6230: sub auto_photo_permission {
                   6231:     my ($cnum,$cdom,$students) = @_;
                   6232:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6233:     my ($outcome,$perm_reqd,$conditions) = 
                   6234: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6235:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6236: 	return (undef,undef);
                   6237:     }
1.706     raeburn  6238:     return ($outcome,$perm_reqd,$conditions);
                   6239: }
                   6240: 
                   6241: sub auto_checkphotos {
                   6242:     my ($uname,$udom,$pid) = @_;
                   6243:     my $homeserver = &homeserver($uname,$udom);
                   6244:     my ($result,$resulttype);
                   6245:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6246: 				   &escape($uname).':'.&escape($pid),
                   6247: 				   $homeserver));
1.709     albertel 6248:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6249: 	return (undef,undef);
                   6250:     }
1.706     raeburn  6251:     if ($outcome) {
                   6252:         ($result,$resulttype) = split(/:/,$outcome);
                   6253:     } 
                   6254:     return ($result,$resulttype);
                   6255: }
                   6256: 
                   6257: sub auto_photochoice {
                   6258:     my ($cnum,$cdom) = @_;
                   6259:     my $homeserver = &homeserver($cnum,$cdom);
                   6260:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6261: 						       &escape($cdom),
                   6262: 						       $homeserver)));
1.709     albertel 6263:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6264: 	return (undef,undef);
                   6265:     }
1.706     raeburn  6266:     return ($update,$comment);
                   6267: }
                   6268: 
                   6269: sub auto_photoupdate {
                   6270:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6271:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6272:     my $host=&hostname($homeserver);
1.706     raeburn  6273:     my $cmd = '';
                   6274:     my $maxtries = 1;
1.800     albertel 6275:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6276:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6277:     }
                   6278:     $cmd =~ s/%%$//;
                   6279:     $cmd = &escape($cmd);
                   6280:     my $query = 'institutionalphotos';
                   6281:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6282:     unless ($queryid=~/^\Q$host\E\_/) {
                   6283:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6284:         return 'error: '.$queryid;
                   6285:     }
                   6286:     my $reply = &get_query_reply($queryid);
                   6287:     my $tries = 1;
                   6288:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6289:         $reply = &get_query_reply($queryid);
                   6290:         $tries ++;
                   6291:     }
                   6292:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6293:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6294:     } else {
                   6295:         my @responses = split(/:/,$reply);
                   6296:         my $outcome = shift(@responses); 
                   6297:         foreach my $item (@responses) {
                   6298:             my ($key,$value) = split(/=/,$item);
                   6299:             $$photo{$key} = $value;
                   6300:         }
                   6301:         return $outcome;
                   6302:     }
                   6303:     return 'error';
                   6304: }
                   6305: 
1.521     raeburn  6306: sub auto_instcode_format {
1.793     albertel 6307:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6308: 	$cat_order) = @_;
1.521     raeburn  6309:     my $courses = '';
1.772     raeburn  6310:     my @homeservers;
1.521     raeburn  6311:     if ($caller eq 'global') {
1.841     albertel 6312: 	my %servers = &get_servers($codedom,'library');
                   6313: 	foreach my $tryserver (keys(%servers)) {
                   6314: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6315: 		push(@homeservers,$tryserver);
                   6316: 	    }
1.584     raeburn  6317:         }
1.1022    raeburn  6318:     } elsif ($caller eq 'requests') {
                   6319:         if ($codedom =~ /^$match_domain$/) {
                   6320:             my $chome = &domain($codedom,'primary');
                   6321:             unless ($chome eq 'no_host') {
                   6322:                 push(@homeservers,$chome);
                   6323:             }
                   6324:         }
1.521     raeburn  6325:     } else {
1.772     raeburn  6326:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6327:     }
1.793     albertel 6328:     foreach my $code (keys(%{$instcodes})) {
                   6329:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6330:     }
                   6331:     chop($courses);
1.772     raeburn  6332:     my $ok_response = 0;
                   6333:     my $response;
                   6334:     while (@homeservers > 0 && $ok_response == 0) {
                   6335:         my $server = shift(@homeservers); 
                   6336:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6337:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6338:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6339: 		split(/:/,$response);
1.772     raeburn  6340:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6341:             push(@{$codetitles},&str2array($codetitles_str));
                   6342:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6343:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6344:             $ok_response = 1;
                   6345:         }
                   6346:     }
                   6347:     if ($ok_response) {
1.521     raeburn  6348:         return 'ok';
1.772     raeburn  6349:     } else {
                   6350:         return $response;
1.521     raeburn  6351:     }
                   6352: }
                   6353: 
1.792     raeburn  6354: sub auto_instcode_defaults {
                   6355:     my ($domain,$returnhash,$code_order) = @_;
                   6356:     my @homeservers;
1.841     albertel 6357: 
                   6358:     my %servers = &get_servers($domain,'library');
                   6359:     foreach my $tryserver (keys(%servers)) {
                   6360: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6361: 	    push(@homeservers,$tryserver);
                   6362: 	}
1.792     raeburn  6363:     }
1.841     albertel 6364: 
1.792     raeburn  6365:     my $response;
1.841     albertel 6366:     foreach my $server (@homeservers) {
1.792     raeburn  6367:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6368:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6369: 	
                   6370: 	foreach my $pair (split(/\&/,$response)) {
                   6371: 	    my ($name,$value)=split(/\=/,$pair);
                   6372: 	    if ($name eq 'code_order') {
                   6373: 		@{$code_order} = split(/\&/,&unescape($value));
                   6374: 	    } else {
                   6375: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6376: 	    }
                   6377: 	}
                   6378: 	return 'ok';
1.792     raeburn  6379:     }
1.841     albertel 6380: 
                   6381:     return $response;
1.1003    raeburn  6382: }
                   6383: 
                   6384: sub auto_possible_instcodes {
1.1007    raeburn  6385:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6386:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6387:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6388:         return;
                   6389:     }
1.1003    raeburn  6390:     my (@homeservers,$uhome);
                   6391:     if (defined(&domain($domain,'primary'))) {
                   6392:         $uhome=&domain($domain,'primary');
                   6393:         push(@homeservers,&domain($domain,'primary'));
                   6394:     } else {
                   6395:         my %servers = &get_servers($domain,'library');
                   6396:         foreach my $tryserver (keys(%servers)) {
                   6397:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6398:                 push(@homeservers,$tryserver);
                   6399:             }
                   6400:         }
                   6401:     }
                   6402:     my $response;
                   6403:     foreach my $server (@homeservers) {
                   6404:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6405:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6406:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6407:             split(':',$response);
                   6408:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6409:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6410:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6411:             my ($name,$value)=split('=',$item);
                   6412:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6413:         }
                   6414:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6415:             my ($name,$value)=split('=',$item);
                   6416:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6417:         }
                   6418:         return 'ok';
                   6419:     }
                   6420:     return $response;
                   6421: }
1.792     raeburn  6422: 
1.1010    raeburn  6423: sub auto_courserequest_checks {
                   6424:     my ($dom) = @_;
1.1020    raeburn  6425:     my ($homeserver,%validations);
                   6426:     if ($dom =~ /^$match_domain$/) {
                   6427:         $homeserver = &domain($dom,'primary');
                   6428:     }
                   6429:     unless ($homeserver eq 'no_host') {
                   6430:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6431:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6432:             my @items = split(/&/,$response);
                   6433:             foreach my $item (@items) {
                   6434:                 my ($key,$value) = split('=',$item);
                   6435:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6436:             }
                   6437:         }
                   6438:     }
1.1010    raeburn  6439:     return %validations; 
                   6440: }
                   6441: 
1.1020    raeburn  6442: sub auto_courserequest_validation {
                   6443:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6444:     my ($homeserver,$response);
                   6445:     if ($dom =~ /^$match_domain$/) {
                   6446:         $homeserver = &domain($dom,'primary');
                   6447:     }
                   6448:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6449:           
1.1020    raeburn  6450:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6451:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6452:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6453:                                     $homeserver));
                   6454:     }
                   6455:     return $response;
                   6456: }
                   6457: 
1.777     albertel 6458: sub auto_validate_class_sec {
1.918     raeburn  6459:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6460:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6461:     my $ownerlist;
                   6462:     if (ref($owners) eq 'ARRAY') {
                   6463:         $ownerlist = join(',',@{$owners});
                   6464:     } else {
                   6465:         $ownerlist = $owners;
                   6466:     }
1.773     raeburn  6467:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6468:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6469:     return $response;
                   6470: }
                   6471: 
1.679     raeburn  6472: # ------------------------------------------------------- Course Group routines
                   6473: 
                   6474: sub get_coursegroups {
1.809     raeburn  6475:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6476:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6477: }
                   6478: 
1.679     raeburn  6479: sub modify_coursegroup {
                   6480:     my ($cdom,$cnum,$groupsettings) = @_;
                   6481:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6482: }
                   6483: 
1.809     raeburn  6484: sub toggle_coursegroup_status {
                   6485:     my ($cdom,$cnum,$group,$action) = @_;
                   6486:     my ($from_namespace,$to_namespace);
                   6487:     if ($action eq 'delete') {
                   6488:         $from_namespace = 'coursegroups';
                   6489:         $to_namespace = 'deleted_groups';
                   6490:     } else {
                   6491:         $from_namespace = 'deleted_groups';
                   6492:         $to_namespace = 'coursegroups';
                   6493:     }
                   6494:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6495:     if (my $tmp = &error(%curr_group)) {
                   6496:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6497:         return ('read error',$tmp);
                   6498:     } else {
                   6499:         my %savedsettings = %curr_group; 
1.809     raeburn  6500:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6501:         my $deloutcome;
                   6502:         if ($result eq 'ok') {
1.809     raeburn  6503:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6504:         } else {
                   6505:             return ('write error',$result);
                   6506:         }
                   6507:         if ($deloutcome eq 'ok') {
                   6508:             return 'ok';
                   6509:         } else {
                   6510:             return ('delete error',$deloutcome);
                   6511:         }
                   6512:     }
                   6513: }
                   6514: 
1.679     raeburn  6515: sub modify_group_roles {
1.957     raeburn  6516:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6517:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6518:     my $role = 'gr/'.&escape($userprivs);
                   6519:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6520:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6521:     if ($result eq 'ok') {
                   6522:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6523:     }
1.679     raeburn  6524:     return $result;
                   6525: }
                   6526: 
                   6527: sub modify_coursegroup_membership {
                   6528:     my ($cdom,$cnum,$membership) = @_;
                   6529:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6530:     return $result;
                   6531: }
                   6532: 
1.682     raeburn  6533: sub get_active_groups {
                   6534:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6535:     my $now = time;
                   6536:     my %groups = ();
                   6537:     foreach my $key (keys(%env)) {
1.811     albertel 6538:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6539:             my ($start,$end) = split(/\./,$env{$key});
                   6540:             if (($end!=0) && ($end<$now)) { next; }
                   6541:             if (($start!=0) && ($start>$now)) { next; }
                   6542:             if ($1 eq $cdom && $2 eq $cnum) {
                   6543:                 $groups{$3} = $env{$key} ;
                   6544:             }
                   6545:         }
                   6546:     }
                   6547:     return %groups;
                   6548: }
                   6549: 
1.683     raeburn  6550: sub get_group_membership {
                   6551:     my ($cdom,$cnum,$group) = @_;
                   6552:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6553: }
                   6554: 
                   6555: sub get_users_groups {
                   6556:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6557:     my @usersgroups;
1.683     raeburn  6558:     my $cachetime=1800;
                   6559: 
                   6560:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6561:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6562:     if (defined($cached)) {
1.734     albertel 6563:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6564:     } else {  
                   6565:         $grouplist = '';
1.816     raeburn  6566:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6567:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6568:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6569:         my $access_end = $env{'course.'.$courseid.
                   6570:                               '.default_enrollment_end_date'};
                   6571:         my $now = time;
                   6572:         foreach my $key (keys(%roleshash)) {
                   6573:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6574:                 my $group = $1;
                   6575:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6576:                     my $start = $2;
                   6577:                     my $end = $1;
                   6578:                     if ($start == -1) { next; } # deleted from group
                   6579:                     if (($start!=0) && ($start>$now)) { next; }
                   6580:                     if (($end!=0) && ($end<$now)) {
                   6581:                         if ($access_end && $access_end < $now) {
                   6582:                             if ($access_end - $end < 86400) {
                   6583:                                 push(@usersgroups,$group);
1.733     raeburn  6584:                             }
                   6585:                         }
1.817     raeburn  6586:                         next;
1.733     raeburn  6587:                     }
1.817     raeburn  6588:                     push(@usersgroups,$group);
1.683     raeburn  6589:                 }
                   6590:             }
                   6591:         }
1.817     raeburn  6592:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6593:         $grouplist = join(':',@usersgroups);
                   6594:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6595:     }
1.733     raeburn  6596:     return @usersgroups;
1.683     raeburn  6597: }
                   6598: 
                   6599: sub devalidate_getgroups_cache {
                   6600:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6601:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6602: 
1.683     raeburn  6603:     my $hashid="$udom:$uname:$courseid";
                   6604:     &devalidate_cache_new('getgroups',$hashid);
                   6605: }
                   6606: 
1.12      www      6607: # ------------------------------------------------------------------ Plain Text
                   6608: 
                   6609: sub plaintext {
1.988     raeburn  6610:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6611:     if ($short =~ m{^cr/}) {
1.758     albertel 6612: 	return (split('/',$short))[-1];
                   6613:     }
1.742     raeburn  6614:     if (!defined($cid)) {
                   6615:         $cid = $env{'request.course.id'};
                   6616:     }
                   6617:     my %rolenames = (
1.1008    raeburn  6618:                       Course    => 'std',
                   6619:                       Community => 'alt1',
1.742     raeburn  6620:                     );
1.1037    raeburn  6621:     if ($cid ne '') {
                   6622:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6623:             unless ($forcedefault) {
                   6624:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6625:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6626:                 return &Apache::lonlocal::mt($roletext);
                   6627:             }
                   6628:         }
                   6629:     }
                   6630:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6631:         (defined($rolenames{$type})) && 
                   6632:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6633:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6634:     } elsif ($cid ne '') {
                   6635:         my $crstype = $env{'course.'.$cid.'.type'};
                   6636:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6637:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6638:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6639:         }
1.742     raeburn  6640:     }
1.1037    raeburn  6641:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6642: }
                   6643: 
                   6644: # ----------------------------------------------------------------- Assign Role
                   6645: 
                   6646: sub assignrole {
1.957     raeburn  6647:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6648:         $context)=@_;
1.21      www      6649:     my $mrole;
                   6650:     if ($role =~ /^cr\//) {
1.393     www      6651:         my $cwosec=$url;
1.811     albertel 6652:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6653: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6654:            my $refused = 1;
                   6655:            if ($context eq 'requestcourses') {
                   6656:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6657:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6658:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6659:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6660:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6661:                            if ($crsenv{'internal.courseowner'} eq
                   6662:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6663:                                $refused = '';
                   6664:                            }
                   6665:                        }
                   6666:                    }
                   6667:                }
                   6668:            }
                   6669:            if ($refused) {
                   6670:                &logthis('Refused custom assignrole: '.
                   6671:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6672:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6673:                return 'refused';
                   6674:            }
1.104     www      6675:         }
1.21      www      6676:         $mrole='cr';
1.678     raeburn  6677:     } elsif ($role =~ /^gr\//) {
                   6678:         my $cwogrp=$url;
1.811     albertel 6679:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6680:         unless (&allowed('mdg',$cwogrp)) {
                   6681:             &logthis('Refused group assignrole: '.
                   6682:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6683:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6684:             return 'refused';
                   6685:         }
                   6686:         $mrole='gr';
1.21      www      6687:     } else {
1.82      www      6688:         my $cwosec=$url;
1.811     albertel 6689:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6690:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6691:             my $refused;
                   6692:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6693:                 if (!(&allowed('c'.$role,$url))) {
                   6694:                     $refused = 1;
                   6695:                 }
                   6696:             } else {
                   6697:                 $refused = 1;
                   6698:             }
1.947     raeburn  6699:             if ($refused) {
1.1045    raeburn  6700:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6701:                 if (!$selfenroll && $context eq 'course') {
                   6702:                     my %crsenv;
                   6703:                     if ($role eq 'cc' || $role eq 'co') {
                   6704:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6705:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6706:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6707:                                 if ($crsenv{'internal.courseowner'} eq 
                   6708:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6709:                                     $refused = '';
                   6710:                                 }
                   6711:                             }
                   6712:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6713:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6714:                                 if ($crsenv{'internal.courseowner'} eq 
                   6715:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6716:                                     $refused = '';
                   6717:                                 }
                   6718:                             }
                   6719:                         }
                   6720:                     }
                   6721:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6722:                     $refused = '';
1.1017    raeburn  6723:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6724:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6725:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6726:                         my $wrongcc;
                   6727:                         if ($cnum =~ /^$match_community$/) {
                   6728:                             $wrongcc = 1 if ($role eq 'cc');
                   6729:                         } else {
                   6730:                             $wrongcc = 1 if ($role eq 'co');
                   6731:                         }
                   6732:                         unless ($wrongcc) {
                   6733:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6734:                             if ($crsenv{'internal.courseowner'} eq 
                   6735:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6736:                                 $refused = '';
                   6737:                             }
1.1017    raeburn  6738:                         }
                   6739:                     }
                   6740:                 }
                   6741:                 if ($refused) {
1.947     raeburn  6742:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6743:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6744: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6745:                     return 'refused';
                   6746:                 }
1.932     raeburn  6747:             }
1.104     www      6748:         }
1.21      www      6749:         $mrole=$role;
                   6750:     }
1.620     albertel 6751:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6752:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6753:     if ($end) { $command.='_'.$end; }
1.21      www      6754:     if ($start) {
                   6755: 	if ($end) { 
1.81      www      6756:            $command.='_'.$start; 
1.21      www      6757:         } else {
1.81      www      6758:            $command.='_0_'.$start;
1.21      www      6759:         }
                   6760:     }
1.739     raeburn  6761:     my $origstart = $start;
                   6762:     my $origend = $end;
1.957     raeburn  6763:     my $delflag;
1.357     www      6764: # actually delete
                   6765:     if ($deleteflag) {
1.373     www      6766: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6767: # modify command to delete the role
1.620     albertel 6768:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6769:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6770: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6771: # set start and finish to negative values for userrolelog
                   6772:            $start=-1;
                   6773:            $end=-1;
1.957     raeburn  6774:            $delflag = 1;
1.357     www      6775:         }
                   6776:     }
                   6777: # send command
1.349     www      6778:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6779: # log new user role if status is ok
1.349     www      6780:     if ($answer eq 'ok') {
1.663     raeburn  6781: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6782: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6783:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6784:         unless ($role =~ /^gr/) {
                   6785:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6786:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6787:         }
1.1053    raeburn  6788:         if ($role eq 'cc') {
                   6789:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6790:         }
1.349     www      6791:     }
                   6792:     return $answer;
1.169     harris41 6793: }
                   6794: 
1.1053    raeburn  6795: sub autoupdate_coowners {
                   6796:     my ($url,$end,$start,$uname,$udom) = @_;
                   6797:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6798:     if (($cdom ne '') && ($cnum ne '')) {
                   6799:         my $now = time;
                   6800:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6801:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6802:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6803:             my $instcode = $coursehash{'internal.coursecode'};
                   6804:             if ($instcode ne '') {
1.1056    raeburn  6805:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6806:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6807:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6808:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6809:                         if ($result eq 'valid') {
                   6810:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6811:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6812:                                     push(@newcoowners,$coowner);
                   6813:                                 }
                   6814:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6815:                                     push(@newcoowners,$uname.':'.$udom);
                   6816:                                 }
                   6817:                                 @newcoowners = sort(@newcoowners);
                   6818:                             } else {
                   6819:                                 push(@newcoowners,$uname.':'.$udom);
                   6820:                             }
                   6821:                         } else {
                   6822:                             if ($coursehash{'internal.co-owners'}) {
                   6823:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6824:                                     unless ($coowner eq $uname.':'.$udom) {
                   6825:                                         push(@newcoowners,$coowner);
                   6826:                                     }
                   6827:                                 }
                   6828:                                 unless (@newcoowners > 0) {
                   6829:                                     $delcoowners = 1;
                   6830:                                     $coowners = '';
                   6831:                                 }
                   6832:                             }
                   6833:                         }
                   6834:                         if (@newcoowners || $delcoowners) {
                   6835:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6836:                                             $delcoowners,@newcoowners);
                   6837:                         }
                   6838:                     }
                   6839:                 }
                   6840:             }
                   6841:         }
                   6842:     }
                   6843: }
                   6844: 
                   6845: sub store_coowners {
                   6846:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6847:     my $cid = $cdom.'_'.$cnum;
                   6848:     my ($coowners,$delresult,$putresult);
                   6849:     if (@newcoowners) {
                   6850:         $coowners = join(',',@newcoowners);
                   6851:         my %coownershash = (
                   6852:                             'internal.co-owners' => $coowners,
                   6853:                            );
                   6854:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6855:         if ($putresult eq 'ok') {
                   6856:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6857:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6858:             }
                   6859:         }
                   6860:     }
                   6861:     if ($delcoowners) {
                   6862:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6863:         if ($delresult eq 'ok') {
                   6864:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6865:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6866:             }
                   6867:         }
                   6868:     }
                   6869:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6870:         my %crsinfo =
                   6871:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6872:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6873:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6874:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6875:         }
                   6876:     }
                   6877: }
                   6878: 
1.169     harris41 6879: # -------------------------------------------------- Modify user authentication
1.197     www      6880: # Overrides without validation
                   6881: 
1.169     harris41 6882: sub modifyuserauth {
                   6883:     my ($udom,$uname,$umode,$upass)=@_;
                   6884:     my $uhome=&homeserver($uname,$udom);
1.197     www      6885:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6886:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6887:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6888:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6889:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6890: 		     &escape($upass),$uhome);
1.620     albertel 6891:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6892:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6893:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6894:     &log($udom,,$uname,$uhome,
1.620     albertel 6895:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6896:                                      $env{'user.name'}.', '.$umode.
1.197     www      6897:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6898:     unless ($reply eq 'ok') {
1.197     www      6899:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6900: 	return 'error: '.$reply;
                   6901:     }   
1.170     harris41 6902:     return 'ok';
1.80      www      6903: }
                   6904: 
1.81      www      6905: # --------------------------------------------------------------- Modify a user
1.80      www      6906: 
1.81      www      6907: sub modifyuser {
1.206     matthew  6908:     my ($udom,    $uname, $uid,
                   6909:         $umode,   $upass, $first,
                   6910:         $middle,  $last,  $gene,
1.1058    raeburn  6911:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6912:     $udom= &LONCAPA::clean_domain($udom);
                   6913:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6914:     my $showcandelete = 'none';
                   6915:     if (ref($candelete) eq 'ARRAY') {
                   6916:         if (@{$candelete} > 0) {
                   6917:             $showcandelete = join(', ',@{$candelete});
                   6918:         }
                   6919:     }
1.81      www      6920:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6921:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6922: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6923:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6924:                                      ' desiredhome not specified'). 
1.620     albertel 6925:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6926:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6927:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6928:     my $newuser;
                   6929:     if ($uhome eq 'no_host') {
                   6930:         $newuser = 1;
                   6931:     }
1.80      www      6932: # ----------------------------------------------------------------- Create User
1.406     albertel 6933:     if (($uhome eq 'no_host') && 
                   6934: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6935:         my $unhome='';
1.844     albertel 6936:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6937:             $unhome = $desiredhome;
1.620     albertel 6938: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6939: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6940:         } else { # load balancing routine for determining $unhome
1.81      www      6941:             my $loadm=10000000;
1.841     albertel 6942: 	    my %servers = &get_servers($udom,'library');
                   6943: 	    foreach my $tryserver (keys(%servers)) {
                   6944: 		my $answer=reply('load',$tryserver);
                   6945: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6946: 		    $loadm=$answer;
                   6947: 		    $unhome=$tryserver;
                   6948: 		}
1.80      www      6949: 	    }
                   6950:         }
                   6951:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6952: 	    return 'error: unable to find a home server for '.$uname.
                   6953:                    ' in domain '.$udom;
1.80      www      6954:         }
                   6955:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6956:                          &escape($upass),$unhome);
                   6957: 	unless ($reply eq 'ok') {
                   6958:             return 'error: '.$reply;
                   6959:         }   
1.230     stredwic 6960:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6961:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6962: 	    return 'error: unable verify users home machine.';
1.80      www      6963:         }
1.209     matthew  6964:     }   # End of creation of new user
1.80      www      6965: # ---------------------------------------------------------------------- Add ID
                   6966:     if ($uid) {
                   6967:        $uid=~tr/A-Z/a-z/;
                   6968:        my %uidhash=&idrget($udom,$uname);
1.196     www      6969:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6970:          && (!$forceid)) {
1.80      www      6971: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6972: 	      return 'error: user id "'.$uid.'" does not match '.
                   6973:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6974:           }
                   6975:        } else {
                   6976: 	  &idput($udom,($uname => $uid));
                   6977:        }
                   6978:     }
                   6979: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6980:     my @tmp=&get('environment',
1.899     raeburn  6981: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6982:                     'permanentemail','inststatus'],
1.134     albertel 6983: 		   $udom,$uname);
1.1075    raeburn  6984:     my (%names,%oldnames);
1.313     matthew  6985:     if ($tmp[0] =~ m/^error:.*/) { 
                   6986:         %names=(); 
                   6987:     } else {
                   6988:         %names = @tmp;
1.1075    raeburn  6989:         %oldnames = %names;
1.313     matthew  6990:     }
1.388     www      6991: #
1.1058    raeburn  6992: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6993: # of users did not contain them), do not overwrite existing values
                   6994: # unless field is in $candelete array ref.  
                   6995: #
                   6996: 
                   6997:     my @fields = ('firstname','middlename','lastname','generation',
                   6998:                   'permanentemail','id');
                   6999:     my %newvalues;
                   7000:     if (ref($candelete) eq 'ARRAY') {
                   7001:         foreach my $field (@fields) {
                   7002:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7003:                 if ($field eq 'firstname') {
                   7004:                     $names{$field} = $first;
                   7005:                 } elsif ($field eq 'middlename') {
                   7006:                     $names{$field} = $middle;
                   7007:                 } elsif ($field eq 'lastname') {
                   7008:                     $names{$field} = $last;
                   7009:                 } elsif ($field eq 'generation') { 
                   7010:                     $names{$field} = $gene;
                   7011:                 } elsif ($field eq 'permanentemail') {
                   7012:                     $names{$field} = $email;
                   7013:                 } elsif ($field eq 'id') {
                   7014:                     $names{$field}  = $uid;
                   7015:                 }
                   7016:             }
                   7017:         }
                   7018:     }
1.388     www      7019:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7020:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7021:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7022:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7023:     if ($email) {
                   7024:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7025:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7026:     }
1.899     raeburn  7027:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7028:     if (defined($inststatus)) {
                   7029:         $names{'inststatus'} = '';
                   7030:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7031:         if (ref($usertypes) eq 'HASH') {
                   7032:             my @okstatuses; 
                   7033:             foreach my $item (split(/:/,$inststatus)) {
                   7034:                 if (defined($usertypes->{$item})) {
                   7035:                     push(@okstatuses,$item);  
                   7036:                 }
                   7037:             }
                   7038:             if (@okstatuses) {
                   7039:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7040:             }
                   7041:         }
                   7042:     }
1.1075    raeburn  7043:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7044:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7045:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7046:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7047:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7048:     } else {
                   7049:         $logmsg .= ' during self creation';
                   7050:     }
1.1075    raeburn  7051:     my $changed;
                   7052:     if ($newuser) {
                   7053:         $changed = 1;
                   7054:     } else {
                   7055:         foreach my $field (@fields) {
                   7056:             if ($names{$field} ne $oldnames{$field}) {
                   7057:                 $changed = 1;
                   7058:                 last;
                   7059:             }
                   7060:         }
                   7061:     }
                   7062:     unless ($changed) {
                   7063:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7064:         &logthis($logmsg);
                   7065:         return 'ok';
                   7066:     }
                   7067:     my $reply = &put('environment', \%names, $udom,$uname);
                   7068:     if ($reply ne 'ok') { 
                   7069:         return 'error: '.$reply;
                   7070:     }
1.1087    raeburn  7071:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7072:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7073:     }
1.1075    raeburn  7074:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7075:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7076:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7077:     &logthis($logmsg);
1.134     albertel 7078:     return 'ok';
1.80      www      7079: }
                   7080: 
1.81      www      7081: # -------------------------------------------------------------- Modify student
1.80      www      7082: 
1.81      www      7083: sub modifystudent {
                   7084:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7085:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7086:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7087:     if (!$cid) {
1.620     albertel 7088: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7089: 	    return 'not_in_class';
                   7090: 	}
1.80      www      7091:     }
                   7092: # --------------------------------------------------------------- Make the user
1.81      www      7093:     my $reply=&modifyuser
1.209     matthew  7094: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7095:          $desiredhome,$email,$inststatus);
1.80      www      7096:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7097:     # This will cause &modify_student_enrollment to get the uid from the
                   7098:     # students environment
                   7099:     $uid = undef if (!$forceid);
1.455     albertel 7100:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7101: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7102:     return $reply;
                   7103: }
                   7104: 
                   7105: sub modify_student_enrollment {
1.957     raeburn  7106:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7107:     my ($cdom,$cnum,$chome);
                   7108:     if (!$cid) {
1.620     albertel 7109: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7110: 	    return 'not_in_class';
                   7111: 	}
1.620     albertel 7112: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7113: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7114:     } else {
                   7115: 	($cdom,$cnum)=split(/_/,$cid);
                   7116:     }
1.620     albertel 7117:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7118:     if (!$chome) {
1.457     raeburn  7119: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7120:     }
1.455     albertel 7121:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7122:     # Make sure the user exists
1.81      www      7123:     my $uhome=&homeserver($uname,$udom);
                   7124:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7125: 	return 'error: no such user';
                   7126:     }
1.297     matthew  7127:     # Get student data if we were not given enough information
                   7128:     if (!defined($first)  || $first  eq '' || 
                   7129:         !defined($last)   || $last   eq '' || 
                   7130:         !defined($uid)    || $uid    eq '' || 
                   7131:         !defined($middle) || $middle eq '' || 
                   7132:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7133:         # They did not supply us with enough data to enroll the student, so
                   7134:         # we need to pick up more information.
1.297     matthew  7135:         my %tmp = &get('environment',
1.294     matthew  7136:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7137:                        ,$udom,$uname);
                   7138: 
1.800     albertel 7139:         #foreach my $key (keys(%tmp)) {
                   7140:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7141:         #}
1.294     matthew  7142:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7143:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7144:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7145:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7146:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7147:     }
1.556     albertel 7148:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7149:     my $reply=cput('classlist',
                   7150: 		   {"$uname:$udom" => 
1.515     raeburn  7151: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7152: 		   $cdom,$cnum);
1.81      www      7153:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7154: 	return 'error: '.$reply;
1.652     albertel 7155:     } else {
                   7156: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7157:     }
1.297     matthew  7158:     # Add student role to user
1.83      www      7159:     my $uurl='/'.$cid;
1.81      www      7160:     $uurl=~s/\_/\//g;
                   7161:     if ($usec) {
                   7162: 	$uurl.='/'.$usec;
                   7163:     }
1.957     raeburn  7164:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7165: }
                   7166: 
1.556     albertel 7167: sub format_name {
                   7168:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7169:     my $name;
                   7170:     if ($first ne 'lastname') {
                   7171: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7172:     } else {
                   7173: 	if ($lastname=~/\S/) {
                   7174: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7175: 	    $name=~s/\s+,/,/;
                   7176: 	} else {
                   7177: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7178: 	}
                   7179:     }
                   7180:     $name=~s/^\s+//;
                   7181:     $name=~s/\s+$//;
                   7182:     $name=~s/\s+/ /g;
                   7183:     return $name;
                   7184: }
                   7185: 
1.84      www      7186: # ------------------------------------------------- Write to course preferences
                   7187: 
                   7188: sub writecoursepref {
                   7189:     my ($courseid,%prefs)=@_;
                   7190:     $courseid=~s/^\///;
                   7191:     $courseid=~s/\_/\//g;
                   7192:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7193:     my $chome=homeserver($cnum,$cdomain);
                   7194:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7195: 	return 'error: no such course';
                   7196:     }
                   7197:     my $cstring='';
1.800     albertel 7198:     foreach my $pref (keys(%prefs)) {
                   7199: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7200:     }
1.84      www      7201:     $cstring=~s/\&$//;
                   7202:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7203: }
                   7204: 
                   7205: # ---------------------------------------------------------- Make/modify course
                   7206: 
                   7207: sub createcourse {
1.741     raeburn  7208:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7209:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7210:     $url=&declutter($url);
                   7211:     my $cid='';
1.1028    raeburn  7212:     if ($context eq 'requestcourses') {
                   7213:         my $can_create = 0;
                   7214:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7215:         if ($udom eq $ownerdom) {
                   7216:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7217:                                   $context)) {
                   7218:                 $can_create = 1;
                   7219:             }
                   7220:         } else {
                   7221:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7222:                                            $category);
                   7223:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7224:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7225:                 if (@curr > 0) {
                   7226:                     my @options = qw(approval validate autolimit);
                   7227:                     my $optregex = join('|',@options);
                   7228:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7229:                         $can_create = 1;
                   7230:                     }
                   7231:                 }
                   7232:             }
                   7233:         }
                   7234:         if ($can_create) {
                   7235:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7236:                 unless (&allowed('ccc',$udom)) {
                   7237:                     return 'refused'; 
                   7238:                 }
1.1017    raeburn  7239:             }
                   7240:         } else {
                   7241:             return 'refused';
                   7242:         }
1.1028    raeburn  7243:     } elsif (!&allowed('ccc',$udom)) {
                   7244:         return 'refused';
1.84      www      7245:     }
1.1011    raeburn  7246: # --------------------------------------------------------------- Get Unique ID
                   7247:     my $uname;
                   7248:     if ($cnum =~ /^$match_courseid$/) {
                   7249:         my $chome=&homeserver($cnum,$udom,'true');
                   7250:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7251:             $uname = $cnum;
                   7252:         } else {
1.1038    raeburn  7253:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7254:         }
                   7255:     } else {
1.1038    raeburn  7256:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7257:     }
                   7258:     return $uname if ($uname =~ /^error/);
                   7259: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7260:     if (!defined($course_server)) {
                   7261:         if (defined(&domain($udom,'primary'))) {
                   7262:             $course_server = &domain($udom,'primary');
                   7263:         } else {
                   7264:             $course_server = $env{'user.home'}; 
                   7265:         }
                   7266:     }
                   7267:     my %host_servers =
                   7268:         &Apache::lonnet::get_servers($udom,'library');
                   7269:     unless ($host_servers{$course_server}) {
                   7270:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7271:     }
1.84      www      7272: # ------------------------------------------------------------- Make the course
                   7273:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7274:                       $course_server);
1.84      www      7275:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7276:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7277:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7278: 	return 'error: no such course';
                   7279:     }
1.271     www      7280: # ----------------------------------------------------------------- Course made
1.516     raeburn  7281: # log existence
1.1029    raeburn  7282:     my $now = time;
1.918     raeburn  7283:     my $newcourse = {
                   7284:                     $udom.'_'.$uname => {
1.921     raeburn  7285:                                      description => $description,
                   7286:                                      inst_code   => $inst_code,
                   7287:                                      owner       => $course_owner,
                   7288:                                      type        => $crstype,
1.1029    raeburn  7289:                                      creator     => $env{'user.name'}.':'.
                   7290:                                                     $env{'user.domain'},
                   7291:                                      created     => $now,
                   7292:                                      context     => $context,
1.918     raeburn  7293:                                                 },
                   7294:                     };
1.921     raeburn  7295:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7296: # set toplevel url
1.271     www      7297:     my $topurl=$url;
                   7298:     unless ($nonstandard) {
                   7299: # ------------------------------------------ For standard courses, make top url
                   7300:         my $mapurl=&clutter($url);
1.278     www      7301:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7302:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7303: <map>
                   7304: <resource id="1" type="start"></resource>
                   7305: <resource id="2" src="$mapurl"></resource>
                   7306: <resource id="3" type="finish"></resource>
                   7307: <link index="1" from="1" to="2"></link>
                   7308: <link index="2" from="2" to="3"></link>
                   7309: </map>
                   7310: ENDINITMAP
                   7311:         $topurl=&declutter(
1.638     albertel 7312:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7313:                           );
                   7314:     }
                   7315: # ----------------------------------------------------------- Write preferences
1.84      www      7316:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7317:                      ('description'              => $description,
                   7318:                       'url'                      => $topurl,
                   7319:                       'internal.creator'         => $env{'user.name'}.':'.
                   7320:                                                     $env{'user.domain'},
                   7321:                       'internal.created'         => $now,
                   7322:                       'internal.creationcontext' => $context)
                   7323:                     );
1.84      www      7324:     return '/'.$udom.'/'.$uname;
                   7325: }
                   7326: 
1.1011    raeburn  7327: # ------------------------------------------------------------------- Create ID
                   7328: sub generate_coursenum {
1.1038    raeburn  7329:     my ($udom,$crstype) = @_;
1.1011    raeburn  7330:     my $domdesc = &domain($udom);
                   7331:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7332:     my $first;
                   7333:     if ($crstype eq 'Community') {
                   7334:         $first = '0';
                   7335:     } else {
                   7336:         $first = int(1+rand(9)); 
                   7337:     } 
                   7338:     my $uname=$first.
1.1011    raeburn  7339:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7340:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7341:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7342: # ----------------------------------------------- Make sure that does not exist
                   7343:     my $uhome=&homeserver($uname,$udom,'true');
                   7344:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7345:         if ($crstype eq 'Community') {
                   7346:             $first = '0';
                   7347:         } else {
                   7348:             $first = int(1+rand(9));
                   7349:         }
                   7350:         $uname=$first.
1.1011    raeburn  7351:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7352:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7353:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7354:         $uhome=&homeserver($uname,$udom,'true');
                   7355:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7356:             return 'error: unable to generate unique course-ID';
                   7357:         }
                   7358:     }
                   7359:     return $uname;
                   7360: }
                   7361: 
1.813     albertel 7362: sub is_course {
                   7363:     my ($cdom,$cnum) = @_;
                   7364:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7365: 				undef,'.');
1.813     albertel 7366:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7367:         return 1;
                   7368:     }
                   7369:     return 0;
                   7370: }
                   7371: 
1.1015    raeburn  7372: sub store_userdata {
                   7373:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7374:     my $result;
1.1016    raeburn  7375:     if ($datakey ne '') {
1.1013    raeburn  7376:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7377:             if ($udom eq '' || $uname eq '') {
                   7378:                 $udom = $env{'user.domain'};
                   7379:                 $uname = $env{'user.name'};
                   7380:             }
                   7381:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7382:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7383:                 $result = 'error: no_host';
                   7384:             } else {
                   7385:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7386:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7387: 
                   7388:                 my $namevalue='';
                   7389:                 foreach my $key (keys(%{$storehash})) {
                   7390:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7391:                 }
                   7392:                 $namevalue=~s/\&$//;
1.1105    raeburn  7393:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7394:                                   $namevalue,$uhome);
1.1013    raeburn  7395:             }
                   7396:         } else {
                   7397:             $result = 'error: data to store was not a hash reference'; 
                   7398:         }
                   7399:     } else {
                   7400:         $result= 'error: invalid requestkey'; 
                   7401:     }
                   7402:     return $result;
                   7403: }
                   7404: 
1.21      www      7405: # ---------------------------------------------------------- Assign Custom Role
                   7406: 
                   7407: sub assigncustomrole {
1.957     raeburn  7408:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7409:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7410:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7411: }
                   7412: 
                   7413: # ----------------------------------------------------------------- Revoke Role
                   7414: 
                   7415: sub revokerole {
1.957     raeburn  7416:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7417:     my $now=time;
1.965     raeburn  7418:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7419: }
                   7420: 
                   7421: # ---------------------------------------------------------- Revoke Custom Role
                   7422: 
                   7423: sub revokecustomrole {
1.957     raeburn  7424:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7425:     my $now=time;
1.357     www      7426:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7427:            $deleteflag,$selfenroll,$context);
1.17      www      7428: }
                   7429: 
1.533     banghart 7430: # ------------------------------------------------------------ Disk usage
1.535     albertel 7431: sub diskusage {
1.955     raeburn  7432:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7433:     $directorypath =~ s/\/$//;
                   7434:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7435:                        .&escape($getpropath).':'.&escape($uname).':'
                   7436:                        .&escape($udom),homeserver($uname,$udom));
                   7437:     if ($listing eq 'unknown_cmd') {
                   7438:         if ($getpropath) {
                   7439:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7440:         }
                   7441:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7442:     }
1.514     albertel 7443:     return $listing;
1.512     banghart 7444: }
                   7445: 
1.566     banghart 7446: sub is_locked {
1.1096    raeburn  7447:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7448:     my @check;
                   7449:     my $is_locked;
1.1093    raeburn  7450:     push (@check,$file_name);
1.613     albertel 7451:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7452: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7453:     my ($tmp)=keys(%locked);
                   7454:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7455:     
1.566     banghart 7456:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7457:         $is_locked = 'false';
                   7458:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7459:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7460:                $is_locked = 'true';
1.1096    raeburn  7461:                if (ref($which) eq 'ARRAY') {
                   7462:                    push(@{$which},$entry);
                   7463:                } else {
                   7464:                    last;
                   7465:                }
1.745     raeburn  7466:            }
                   7467:        }
1.566     banghart 7468:     } else {
                   7469:         $is_locked = 'false';
                   7470:     }
1.1093    raeburn  7471:     return $is_locked;
1.566     banghart 7472: }
                   7473: 
1.759     albertel 7474: sub declutter_portfile {
                   7475:     my ($file) = @_;
1.833     albertel 7476:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7477:     return $file;
                   7478: }
                   7479: 
1.559     banghart 7480: # ------------------------------------------------------------- Mark as Read Only
                   7481: 
                   7482: sub mark_as_readonly {
                   7483:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7484:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7485:     my ($tmp)=keys(%current_permissions);
                   7486:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7487:     foreach my $file (@{$files}) {
1.759     albertel 7488: 	$file = &declutter_portfile($file);
1.561     banghart 7489:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7490:     }
1.613     albertel 7491:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7492:     return;
                   7493: }
                   7494: 
1.572     banghart 7495: # ------------------------------------------------------------Save Selected Files
                   7496: 
                   7497: sub save_selected_files {
                   7498:     my ($user, $path, @files) = @_;
                   7499:     my $filename = $user."savedfiles";
1.573     banghart 7500:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7501:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7502:     foreach my $file (@files) {
1.620     albertel 7503:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7504:     }
                   7505:     foreach my $file (@other_files) {
1.574     banghart 7506:         print (OUT $file."\n");
1.572     banghart 7507:     }
1.574     banghart 7508:     close (OUT);
1.572     banghart 7509:     return 'ok';
                   7510: }
                   7511: 
1.574     banghart 7512: sub clear_selected_files {
                   7513:     my ($user) = @_;
                   7514:     my $filename = $user."savedfiles";
1.1117    foxr     7515:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7516:     print (OUT undef);
                   7517:     close (OUT);
                   7518:     return ("ok");    
                   7519: }
                   7520: 
1.572     banghart 7521: sub files_in_path {
                   7522:     my ($user, $path) = @_;
                   7523:     my $filename = $user."savedfiles";
                   7524:     my %return_files;
1.1117    foxr     7525:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7526:     while (my $line_in = <IN>) {
1.574     banghart 7527:         chomp ($line_in);
                   7528:         my @paths_and_file = split (m!/!, $line_in);
                   7529:         my $file_part = pop (@paths_and_file);
                   7530:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7531:         $path_part.='/';
                   7532:         my $path_and_file = $path_part.$file_part;
                   7533:         if ($path_part eq $path) {
                   7534:             $return_files{$file_part}= 'selected';
                   7535:         }
                   7536:     }
1.574     banghart 7537:     close (IN);
                   7538:     return (\%return_files);
1.572     banghart 7539: }
                   7540: 
                   7541: # called in portfolio select mode, to show files selected NOT in current directory
                   7542: sub files_not_in_path {
                   7543:     my ($user, $path) = @_;
                   7544:     my $filename = $user."savedfiles";
                   7545:     my @return_files;
                   7546:     my $path_part;
1.1117    foxr     7547:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7548:     while (my $line = <IN>) {
1.572     banghart 7549:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7550:         my @paths_and_file = split(m|/|, $line);
                   7551:         my $file_part = pop(@paths_and_file);
                   7552:         chomp($file_part);
                   7553:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7554:         $path_part .= '/';
                   7555:         my $path_and_file = $path_part.$file_part;
                   7556:         if ($path_part ne $path) {
1.800     albertel 7557:             push(@return_files, ($path_and_file));
1.572     banghart 7558:         }
                   7559:     }
1.800     albertel 7560:     close(OUT);
1.574     banghart 7561:     return (@return_files);
1.572     banghart 7562: }
                   7563: 
1.745     raeburn  7564: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7565: 
1.745     raeburn  7566: sub get_portfile_permissions {
                   7567:     my ($domain,$user) = @_;
1.613     albertel 7568:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7569:     my ($tmp)=keys(%current_permissions);
                   7570:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7571:     return \%current_permissions;
                   7572: }
                   7573: 
                   7574: #---------------------------------------------Get portfolio file access controls
                   7575: 
1.749     raeburn  7576: sub get_access_controls {
1.745     raeburn  7577:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7578:     my %access;
                   7579:     my $real_file = $file;
                   7580:     $file =~ s/\.meta$//;
1.745     raeburn  7581:     if (defined($file)) {
1.749     raeburn  7582:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7583:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7584:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7585:             }
                   7586:         }
1.745     raeburn  7587:     } else {
1.749     raeburn  7588:         foreach my $key (keys(%{$current_permissions})) {
                   7589:             if ($key =~ /\0accesscontrol$/) {
                   7590:                 if (defined($group)) {
                   7591:                     if ($key !~ m-^\Q$group\E/-) {
                   7592:                         next;
                   7593:                     }
                   7594:                 }
                   7595:                 my ($fullpath) = split(/\0/,$key);
                   7596:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7597:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7598:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7599:                     }
                   7600:                 }
                   7601:             }
                   7602:         }
                   7603:     }
                   7604:     return %access;
                   7605: }
                   7606: 
                   7607: sub modify_access_controls {
                   7608:     my ($file_name,$changes,$domain,$user)=@_;
                   7609:     my ($outcome,$deloutcome);
                   7610:     my %store_permissions;
                   7611:     my %new_values;
                   7612:     my %new_control;
                   7613:     my %translation;
                   7614:     my @deletions = ();
                   7615:     my $now = time;
                   7616:     if (exists($$changes{'activate'})) {
                   7617:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7618:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7619:             my $numnew = scalar(@newitems);
                   7620:             for (my $i=0; $i<$numnew; $i++) {
                   7621:                 my $newkey = $newitems[$i];
                   7622:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7623:                 if ($newkey =~ /^\d+:/) { 
                   7624:                     $newkey =~ s/^(\d+)/$newid/;
                   7625:                     $translation{$1} = $newid;
                   7626:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7627:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7628:                     $translation{$1} = $newid;
                   7629:                 }
1.749     raeburn  7630:                 $new_values{$file_name."\0".$newkey} = 
                   7631:                                           $$changes{'activate'}{$newitems[$i]};
                   7632:                 $new_control{$newkey} = $now;
                   7633:             }
                   7634:         }
                   7635:     }
                   7636:     my %todelete;
                   7637:     my %changed_items;
                   7638:     foreach my $action ('delete','update') {
                   7639:         if (exists($$changes{$action})) {
                   7640:             if (ref($$changes{$action}) eq 'HASH') {
                   7641:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7642:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7643:                     if ($action eq 'delete') { 
                   7644:                         $todelete{$itemnum} = 1;
                   7645:                     } else {
                   7646:                         $changed_items{$itemnum} = $key;
                   7647:                     }
                   7648:                 }
1.745     raeburn  7649:             }
                   7650:         }
1.749     raeburn  7651:     }
                   7652:     # get lock on access controls for file.
                   7653:     my $lockhash = {
                   7654:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7655:                                                        ':'.$env{'user.domain'},
                   7656:                    }; 
                   7657:     my $tries = 0;
                   7658:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7659:    
                   7660:     while (($gotlock ne 'ok') && $tries <3) {
                   7661:         $tries ++;
                   7662:         sleep 1;
                   7663:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7664:     }
                   7665:     if ($gotlock eq 'ok') {
                   7666:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7667:         my ($tmp)=keys(%curr_permissions);
                   7668:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7669:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7670:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7671:             if (ref($curr_controls) eq 'HASH') {
                   7672:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7673:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7674:                     if (defined($todelete{$itemnum})) {
                   7675:                         push(@deletions,$file_name."\0".$control_item);
                   7676:                     } else {
                   7677:                         if (defined($changed_items{$itemnum})) {
                   7678:                             $new_control{$changed_items{$itemnum}} = $now;
                   7679:                             push(@deletions,$file_name."\0".$control_item);
                   7680:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7681:                         } else {
                   7682:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7683:                         }
                   7684:                     }
1.745     raeburn  7685:                 }
                   7686:             }
                   7687:         }
1.970     raeburn  7688:         my ($group);
                   7689:         if (&is_course($domain,$user)) {
                   7690:             ($group,my $file) = split(/\//,$file_name,2);
                   7691:         }
1.749     raeburn  7692:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7693:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7694:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7695:         #  remove lock
                   7696:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7697:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7698:         my $sqlresult =
1.970     raeburn  7699:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7700:                                     $group);
1.749     raeburn  7701:     } else {
                   7702:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7703:     }
1.749     raeburn  7704:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7705: }
                   7706: 
1.827     raeburn  7707: sub make_public_indefinitely {
                   7708:     my ($requrl) = @_;
                   7709:     my $now = time;
                   7710:     my $action = 'activate';
                   7711:     my $aclnum = 0;
                   7712:     if (&is_portfolio_url($requrl)) {
                   7713:         my (undef,$udom,$unum,$file_name,$group) =
                   7714:             &parse_portfolio_url($requrl);
                   7715:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7716:         my %access_controls = &get_access_controls($current_perms,
                   7717:                                                    $group,$file_name);
                   7718:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7719:             my ($num,$scope,$end,$start) = 
                   7720:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7721:             if ($scope eq 'public') {
                   7722:                 if ($start <= $now && $end == 0) {
                   7723:                     $action = 'none';
                   7724:                 } else {
                   7725:                     $action = 'update';
                   7726:                     $aclnum = $num;
                   7727:                 }
                   7728:                 last;
                   7729:             }
                   7730:         }
                   7731:         if ($action eq 'none') {
                   7732:              return 'ok';
                   7733:         } else {
                   7734:             my %changes;
                   7735:             my $newend = 0;
                   7736:             my $newstart = $now;
                   7737:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7738:             $changes{$action}{$newkey} = {
                   7739:                 type => 'public',
                   7740:                 time => {
                   7741:                     start => $newstart,
                   7742:                     end   => $newend,
                   7743:                 },
                   7744:             };
                   7745:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7746:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7747:             return $outcome;
                   7748:         }
                   7749:     } else {
                   7750:         return 'invalid';
                   7751:     }
                   7752: }
                   7753: 
1.745     raeburn  7754: #------------------------------------------------------Get Marked as Read Only
                   7755: 
                   7756: sub get_marked_as_readonly {
                   7757:     my ($domain,$user,$what,$group) = @_;
                   7758:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7759:     my @readonly_files;
1.629     banghart 7760:     my $cmp1=$what;
                   7761:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7762:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7763:         if (defined($group)) {
                   7764:             if ($file_name !~ m-^\Q$group\E/-) {
                   7765:                 next;
                   7766:             }
                   7767:         }
1.561     banghart 7768:         if (ref($value) eq "ARRAY"){
                   7769:             foreach my $stored_what (@{$value}) {
1.629     banghart 7770:                 my $cmp2=$stored_what;
1.759     albertel 7771:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7772:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7773:                 }
1.629     banghart 7774:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7775:                     push(@readonly_files, $file_name);
1.745     raeburn  7776:                     last;
1.563     banghart 7777:                 } elsif (!defined($what)) {
                   7778:                     push(@readonly_files, $file_name);
1.745     raeburn  7779:                     last;
1.561     banghart 7780:                 }
                   7781:             }
1.745     raeburn  7782:         }
1.561     banghart 7783:     }
                   7784:     return @readonly_files;
                   7785: }
1.577     banghart 7786: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7787: 
1.577     banghart 7788: sub get_marked_as_readonly_hash {
1.745     raeburn  7789:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7790:     my %readonly_files;
1.745     raeburn  7791:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7792:         if (defined($group)) {
                   7793:             if ($file_name !~ m-^\Q$group\E/-) {
                   7794:                 next;
                   7795:             }
                   7796:         }
1.577     banghart 7797:         if (ref($value) eq "ARRAY"){
                   7798:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7799:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7800:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7801:                         if ($lock_descriptor eq 'graded') {
                   7802:                             $readonly_files{$file_name} = 'graded';
                   7803:                         } elsif ($lock_descriptor eq 'handback') {
                   7804:                             $readonly_files{$file_name} = 'handback';
                   7805:                         } else {
                   7806:                             if (!exists($readonly_files{$file_name})) {
                   7807:                                 $readonly_files{$file_name} = 'locked';
                   7808:                             }
                   7809:                         }
1.745     raeburn  7810:                     }
1.750     banghart 7811:                 } 
1.577     banghart 7812:             }
                   7813:         } 
                   7814:     }
                   7815:     return %readonly_files;
                   7816: }
1.559     banghart 7817: # ------------------------------------------------------------ Unmark as Read Only
                   7818: 
                   7819: sub unmark_as_readonly {
1.629     banghart 7820:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7821:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7822:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7823:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7824:     my $symb_crs = $what;
                   7825:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7826:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7827:     my ($tmp)=keys(%current_permissions);
                   7828:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7829:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7830:     foreach my $file (@readonly_files) {
1.759     albertel 7831: 	my $clean_file = &declutter_portfile($file);
                   7832: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7833: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7834:         my @new_locks;
                   7835:         my @del_keys;
                   7836:         if (ref($current_locks) eq "ARRAY"){
                   7837:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7838:                 my $compare=$locker;
1.749     raeburn  7839:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7840:                     $compare=join('',@{$locker});
1.746     raeburn  7841:                     if ($compare ne $symb_crs) {
                   7842:                         push(@new_locks, $locker);
                   7843:                     }
1.563     banghart 7844:                 }
                   7845:             }
1.650     albertel 7846:             if (scalar(@new_locks) > 0) {
1.563     banghart 7847:                 $current_permissions{$file} = \@new_locks;
                   7848:             } else {
                   7849:                 push(@del_keys, $file);
1.613     albertel 7850:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7851:                 delete($current_permissions{$file});
1.563     banghart 7852:             }
                   7853:         }
1.561     banghart 7854:     }
1.613     albertel 7855:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7856:     return;
                   7857: }
1.512     banghart 7858: 
1.17      www      7859: # ------------------------------------------------------------ Directory lister
                   7860: 
                   7861: sub dirlist {
1.955     raeburn  7862:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7863:     $uri=~s/^\///;
                   7864:     $uri=~s/\/$//;
1.253     stredwic 7865:     my ($udom, $uname);
1.955     raeburn  7866:     if ($getuserdir) {
1.253     stredwic 7867:         $udom = $userdomain;
                   7868:         $uname = $username;
1.955     raeburn  7869:     } else {
                   7870:         (undef,$udom,$uname)=split(/\//,$uri);
                   7871:         if(defined($userdomain)) {
                   7872:             $udom = $userdomain;
                   7873:         }
                   7874:         if(defined($username)) {
                   7875:             $uname = $username;
                   7876:         }
1.253     stredwic 7877:     }
1.955     raeburn  7878:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7879: 
1.955     raeburn  7880:     $dirRoot = $perlvar{'lonDocRoot'};
                   7881:     if (defined($getpropath)) {
                   7882:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7883:         $dirRoot =~ s/\/$//;
1.955     raeburn  7884:     } elsif (defined($getuserdir)) {
                   7885:         my $subdir=$uname.'__';
                   7886:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7887:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7888:                    ."/$udom/$subdir/$uname";
                   7889:     } elsif (defined($alternateRoot)) {
                   7890:         $dirRoot = $alternateRoot;
1.751     banghart 7891:     }
1.253     stredwic 7892: 
                   7893:     if($udom) {
                   7894:         if($uname) {
1.955     raeburn  7895:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7896:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7897:                               .':'.&escape($uname).':'.&escape($udom),
                   7898:                               &homeserver($uname,$udom));
                   7899:             if ($listing eq 'unknown_cmd') {
                   7900:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7901:                                   &homeserver($uname,$udom));
                   7902:             } else {
                   7903:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7904:             }
1.605     matthew  7905:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7906:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7907: 				  &homeserver($uname,$udom));
1.605     matthew  7908:                 @listing_results = split(/:/,$listing);
                   7909:             } else {
                   7910:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7911:             }
                   7912:             return @listing_results;
1.955     raeburn  7913:         } elsif(!$alternateRoot) {
1.800     albertel 7914:             my %allusers;
1.841     albertel 7915: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7916:  	    foreach my $tryserver (keys(%servers)) {
                   7917:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7918:                                   &escape($udom),$tryserver);
                   7919:                 if ($listing eq 'unknown_cmd') {
                   7920: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7921: 				      $udom, $tryserver);
                   7922:                 } else {
                   7923:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7924:                 }
1.841     albertel 7925: 		if ($listing eq 'unknown_cmd') {
                   7926: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7927: 				      $udom, $tryserver);
                   7928: 		    @listing_results = split(/:/,$listing);
                   7929: 		} else {
                   7930: 		    @listing_results =
                   7931: 			map { &unescape($_); } split(/:/,$listing);
                   7932: 		}
                   7933: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7934: 		    $listing_results[0] ne 'empty'       &&
                   7935: 		    $listing_results[0] ne 'con_lost') {
                   7936: 		    foreach my $line (@listing_results) {
                   7937: 			my ($entry) = split(/&/,$line,2);
                   7938: 			$allusers{$entry} = 1;
                   7939: 		    }
                   7940: 		}
1.253     stredwic 7941:             }
                   7942:             my $alluserstr='';
1.800     albertel 7943:             foreach my $user (sort(keys(%allusers))) {
                   7944:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7945:             }
                   7946:             $alluserstr=~s/:$//;
                   7947:             return split(/:/,$alluserstr);
                   7948:         } else {
1.800     albertel 7949:             return ('missing user name');
1.253     stredwic 7950:         }
1.955     raeburn  7951:     } elsif(!defined($getpropath)) {
1.841     albertel 7952:         my @all_domains = sort(&all_domains());
1.955     raeburn  7953:         foreach my $domain (@all_domains) {
                   7954:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7955:         }
                   7956:         return @all_domains;
                   7957:     } else {
1.800     albertel 7958:         return ('missing domain');
1.275     stredwic 7959:     }
                   7960: }
                   7961: 
                   7962: # --------------------------------------------- GetFileTimestamp
                   7963: # This function utilizes dirlist and returns the date stamp for
                   7964: # when it was last modified.  It will also return an error of -1
                   7965: # if an error occurs
                   7966: 
                   7967: sub GetFileTimestamp {
1.955     raeburn  7968:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7969:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7970:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7971:     my ($fileStat) = 
                   7972:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7973:                                  undef,$getuserdir);
1.275     stredwic 7974:     my @stats = split('&', $fileStat);
                   7975:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7976:         # @stats contains first the filename, then the stat output
                   7977:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7978:     } else {
                   7979:         return -1;
1.253     stredwic 7980:     }
1.26      www      7981: }
                   7982: 
1.712     albertel 7983: sub stat_file {
                   7984:     my ($uri) = @_;
1.787     albertel 7985:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7986: 
1.955     raeburn  7987:     my ($udom,$uname,$file);
1.712     albertel 7988:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7989: 	($udom,$uname,$file) =
1.811     albertel 7990: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7991: 	$file = 'userfiles/'.$file;
                   7992:     }
                   7993:     if ($uri =~ m-^/res/-) {
                   7994: 	($udom,$uname) = 
1.807     albertel 7995: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7996: 	$file = $uri;
                   7997:     }
                   7998: 
                   7999:     if (!$udom || !$uname || !$file) {
                   8000: 	# unable to handle the uri
                   8001: 	return ();
                   8002:     }
1.956     raeburn  8003:     my $getpropath;
                   8004:     if ($file =~ /^userfiles\//) {
                   8005:         $getpropath = 1;
                   8006:     }
1.955     raeburn  8007:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8008:     my @stats = split('&', $result);
1.721     banghart 8009:     
1.712     albertel 8010:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8011: 	shift(@stats); #filename is first
                   8012: 	return @stats;
                   8013:     }
                   8014:     return ();
                   8015: }
                   8016: 
1.26      www      8017: # -------------------------------------------------------- Value of a Condition
                   8018: 
1.713     albertel 8019: # gets the value of a specific preevaluated condition
                   8020: #    stored in the string  $env{user.state.<cid>}
                   8021: # or looks up a condition reference in the bighash and if if hasn't
                   8022: # already been evaluated recurses into docondval to get the value of
                   8023: # the condition, then memoizing it to 
                   8024: #   $env{user.state.<cid>.<condition>}
1.40      www      8025: sub directcondval {
                   8026:     my $number=shift;
1.620     albertel 8027:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8028: 	&Apache::lonuserstate::evalstate();
                   8029:     }
1.713     albertel 8030:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8031: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8032:     } elsif ($number =~ /^_/) {
                   8033: 	my $sub_condition;
                   8034: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8035: 		&GDBM_READER(),0640)) {
                   8036: 	    $sub_condition=$bighash{'conditions'.$number};
                   8037: 	    untie(%bighash);
                   8038: 	}
                   8039: 	my $value = &docondval($sub_condition);
1.949     raeburn  8040: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8041: 	return $value;
                   8042:     }
1.620     albertel 8043:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8044:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8045:     } else {
                   8046:        return 2;
                   8047:     }
                   8048: }
                   8049: 
1.713     albertel 8050: # get the collection of conditions for this resource
1.26      www      8051: sub condval {
                   8052:     my $condidx=shift;
1.54      www      8053:     my $allpathcond='';
1.713     albertel 8054:     foreach my $cond (split(/\|/,$condidx)) {
                   8055: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8056: 	    $allpathcond.=
                   8057: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8058: 	}
1.191     harris41 8059:     }
1.54      www      8060:     $allpathcond=~s/\|$//;
1.713     albertel 8061:     return &docondval($allpathcond);
                   8062: }
                   8063: 
                   8064: #evaluates an expression of conditions
                   8065: sub docondval {
                   8066:     my ($allpathcond) = @_;
                   8067:     my $result=0;
                   8068:     if ($env{'request.course.id'}
                   8069: 	&& defined($allpathcond)) {
                   8070: 	my $operand='|';
                   8071: 	my @stack;
                   8072: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8073: 	    if ($chunk eq '(') {
                   8074: 		push @stack,($operand,$result);
                   8075: 	    } elsif ($chunk eq ')') {
                   8076: 		my $before=pop @stack;
                   8077: 		if (pop @stack eq '&') {
                   8078: 		    $result=$result>$before?$before:$result;
                   8079: 		} else {
                   8080: 		    $result=$result>$before?$result:$before;
                   8081: 		}
                   8082: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8083: 		$operand=$chunk;
                   8084: 	    } else {
                   8085: 		my $new=directcondval($chunk);
                   8086: 		if ($operand eq '&') {
                   8087: 		    $result=$result>$new?$new:$result;
                   8088: 		} else {
                   8089: 		    $result=$result>$new?$result:$new;
                   8090: 		}
                   8091: 	    }
                   8092: 	}
1.26      www      8093:     }
                   8094:     return $result;
1.421     albertel 8095: }
                   8096: 
                   8097: # ---------------------------------------------------- Devalidate courseresdata
                   8098: 
                   8099: sub devalidatecourseresdata {
                   8100:     my ($coursenum,$coursedomain)=@_;
                   8101:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8102:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8103: }
                   8104: 
1.763     www      8105: 
1.200     www      8106: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8107: #
                   8108: #  Parameters:
                   8109: #      $coursenum    - Number of the course.
                   8110: #      $coursedomain - Domain at which the course was created.
                   8111: #  Returns:
                   8112: #     A hash of the course parameters along (I think) with timestamps
                   8113: #     and version info.
1.877     foxr     8114: 
1.624     albertel 8115: sub get_courseresdata {
                   8116:     my ($coursenum,$coursedomain)=@_;
1.200     www      8117:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8118:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8119:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8120:     my %dumpreply;
1.417     albertel 8121:     unless (defined($cached)) {
1.624     albertel 8122: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8123: 	$result=\%dumpreply;
1.251     albertel 8124: 	my ($tmp) = keys(%dumpreply);
                   8125: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8126: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8127: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8128: 	    return $tmp;
1.416     albertel 8129: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8130: 	    $result=undef;
1.599     albertel 8131: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8132: 	}
                   8133:     }
1.624     albertel 8134:     return $result;
                   8135: }
                   8136: 
1.633     albertel 8137: sub devalidateuserresdata {
                   8138:     my ($uname,$udom)=@_;
                   8139:     my $hashid="$udom:$uname";
                   8140:     &devalidate_cache_new('userres',$hashid);
                   8141: }
                   8142: 
1.624     albertel 8143: sub get_userresdata {
                   8144:     my ($uname,$udom)=@_;
                   8145:     #most student don\'t have any data set, check if there is some data
                   8146:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8147: 
                   8148:     my $hashid="$udom:$uname";
                   8149:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8150:     if (!defined($cached)) {
                   8151: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8152: 	$result=\%resourcedata;
                   8153: 	&do_cache_new('userres',$hashid,$result,600);
                   8154:     }
                   8155:     my ($tmp)=keys(%$result);
                   8156:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8157: 	return $result;
                   8158:     }
                   8159:     #error 2 occurs when the .db doesn't exist
                   8160:     if ($tmp!~/error: 2 /) {
1.672     albertel 8161: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8162: 		 " Trying to get resource data for ".
                   8163: 		 $uname." at ".$udom.": ".
                   8164: 		 $tmp."</font>");
                   8165:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8166: 	#&EXT_cache_set($udom,$uname);
                   8167: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8168: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8169:     }
                   8170:     return $tmp;
                   8171: }
1.879     foxr     8172: #----------------------------------------------- resdata - return resource data
                   8173: #  Purpose:
                   8174: #    Return resource data for either users or for a course.
                   8175: #  Parameters:
                   8176: #     $name      - Course/user name.
                   8177: #     $domain    - Name of the domain the user/course is registered on.
                   8178: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8179: #     @which     - Array of names of resources desired.
                   8180: #  Returns:
                   8181: #     The value of the first reasource in @which that is found in the
                   8182: #     resource hash.
                   8183: #  Exceptional Conditions:
                   8184: #     If the $type passed in is not valid (not the string 'course' or 
                   8185: #     'user', an undefined  reference is returned.
                   8186: #     If none of the resources are found, an undef is returned
1.624     albertel 8187: sub resdata {
                   8188:     my ($name,$domain,$type,@which)=@_;
                   8189:     my $result;
                   8190:     if ($type eq 'course') {
                   8191: 	$result=&get_courseresdata($name,$domain);
                   8192:     } elsif ($type eq 'user') {
                   8193: 	$result=&get_userresdata($name,$domain);
                   8194:     }
                   8195:     if (!ref($result)) { return $result; }    
1.251     albertel 8196:     foreach my $item (@which) {
1.927     albertel 8197: 	if (defined($result->{$item->[0]})) {
                   8198: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8199: 	}
1.250     albertel 8200:     }
1.291     albertel 8201:     return undef;
1.200     www      8202: }
                   8203: 
1.379     matthew  8204: #
                   8205: # EXT resource caching routines
                   8206: #
                   8207: 
                   8208: sub clear_EXT_cache_status {
1.383     albertel 8209:     &delenv('cache.EXT.');
1.379     matthew  8210: }
                   8211: 
                   8212: sub EXT_cache_status {
                   8213:     my ($target_domain,$target_user) = @_;
1.383     albertel 8214:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8215:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8216:         # We know already the user has no data
                   8217:         return 1;
                   8218:     } else {
                   8219:         return 0;
                   8220:     }
                   8221: }
                   8222: 
                   8223: sub EXT_cache_set {
                   8224:     my ($target_domain,$target_user) = @_;
1.383     albertel 8225:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8226:     #&appenv({$cachename => time});
1.379     matthew  8227: }
                   8228: 
1.28      www      8229: # --------------------------------------------------------- Value of a Variable
1.58      www      8230: sub EXT {
1.715     albertel 8231: 
1.395     albertel 8232:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8233:     unless ($varname) { return ''; }
1.218     albertel 8234:     #get real user name/domain, courseid and symb
                   8235:     my $courseid;
1.359     albertel 8236:     my $publicuser;
1.427     www      8237:     if ($symbparm) {
                   8238: 	$symbparm=&get_symb_from_alias($symbparm);
                   8239:     }
1.218     albertel 8240:     if (!($uname && $udom)) {
1.790     albertel 8241:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8242:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8243:     } else {
1.620     albertel 8244: 	$courseid=$env{'request.course.id'};
1.218     albertel 8245:     }
1.48      www      8246:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8247:     my $rest;
1.320     albertel 8248:     if (defined($therest[0])) {
1.48      www      8249:        $rest=join('.',@therest);
                   8250:     } else {
                   8251:        $rest='';
                   8252:     }
1.320     albertel 8253: 
1.57      www      8254:     my $qualifierrest=$qualifier;
                   8255:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8256:     my $spacequalifierrest=$space;
                   8257:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8258:     if ($realm eq 'user') {
1.48      www      8259: # --------------------------------------------------------------- user.resource
                   8260: 	if ($space eq 'resource') {
1.651     albertel 8261: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8262: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8263: 		 &&
1.744     albertel 8264: 		 ($symbparm eq &symbread()) ) {	
                   8265: 		# if we are in the middle of processing the resource the
                   8266: 		# get the value we are planning on committing
                   8267:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8268:                     return $Apache::lonhomework::results{$qualifierrest};
                   8269:                 } else {
                   8270:                     return $Apache::lonhomework::history{$qualifierrest};
                   8271:                 }
1.335     albertel 8272: 	    } else {
1.359     albertel 8273: 		my %restored;
1.620     albertel 8274: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8275: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8276: 		} else {
                   8277: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8278: 		}
1.335     albertel 8279: 		return $restored{$qualifierrest};
                   8280: 	    }
1.48      www      8281: # ----------------------------------------------------------------- user.access
                   8282:         } elsif ($space eq 'access') {
1.218     albertel 8283: 	    # FIXME - not supporting calls for a specific user
1.48      www      8284:             return &allowed($qualifier,$rest);
                   8285: # ------------------------------------------ user.preferences, user.environment
                   8286:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8287: 	    if (($uname eq $env{'user.name'}) &&
                   8288: 		($udom eq $env{'user.domain'})) {
                   8289: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8290: 	    } else {
1.359     albertel 8291: 		my %returnhash;
                   8292: 		if (!$publicuser) {
                   8293: 		    %returnhash=&userenvironment($udom,$uname,
                   8294: 						 $qualifierrest);
                   8295: 		}
1.218     albertel 8296: 		return $returnhash{$qualifierrest};
                   8297: 	    }
1.48      www      8298: # ----------------------------------------------------------------- user.course
                   8299:         } elsif ($space eq 'course') {
1.218     albertel 8300: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8301:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8302: # ------------------------------------------------------------------- user.role
                   8303:         } elsif ($space eq 'role') {
1.218     albertel 8304: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8305:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8306:             if ($qualifier eq 'value') {
                   8307: 		return $role;
                   8308:             } elsif ($qualifier eq 'extent') {
                   8309:                 return $where;
                   8310:             }
                   8311: # ----------------------------------------------------------------- user.domain
                   8312:         } elsif ($space eq 'domain') {
1.218     albertel 8313:             return $udom;
1.48      www      8314: # ------------------------------------------------------------------- user.name
                   8315:         } elsif ($space eq 'name') {
1.218     albertel 8316:             return $uname;
1.48      www      8317: # ---------------------------------------------------- Any other user namespace
1.29      www      8318:         } else {
1.359     albertel 8319: 	    my %reply;
                   8320: 	    if (!$publicuser) {
                   8321: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8322: 	    }
                   8323: 	    return $reply{$qualifierrest};
1.48      www      8324:         }
1.236     www      8325:     } elsif ($realm eq 'query') {
                   8326: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8327:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8328: 						[$spacequalifierrest]);
1.620     albertel 8329: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8330:    } elsif ($realm eq 'request') {
1.48      www      8331: # ------------------------------------------------------------- request.browser
                   8332:         if ($space eq 'browser') {
1.430     www      8333: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8334: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8335: 		    return 1;
                   8336: 		} else {
                   8337: 		    return 0;
                   8338: 		}
                   8339: 	    } else {
1.620     albertel 8340: 		return $env{'browser.'.$qualifier};
1.430     www      8341: 	    }
1.57      www      8342: # ------------------------------------------------------------ request.filename
                   8343:         } else {
1.620     albertel 8344:             return $env{'request.'.$spacequalifierrest};
1.29      www      8345:         }
1.28      www      8346:     } elsif ($realm eq 'course') {
1.48      www      8347: # ---------------------------------------------------------- course.description
1.620     albertel 8348:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8349:     } elsif ($realm eq 'resource') {
1.165     www      8350: 
1.620     albertel 8351: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8352: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8353: 	}
1.693     albertel 8354: 
                   8355: 	if ($space eq 'title') {
                   8356: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8357: 	    return &gettitle($symbparm);
                   8358: 	}
                   8359: 	
                   8360: 	if ($space eq 'map') {
                   8361: 	    my ($map) = &decode_symb($symbparm);
                   8362: 	    return &symbread($map);
                   8363: 	}
1.905     albertel 8364: 	if ($space eq 'filename') {
                   8365: 	    if ($symbparm) {
                   8366: 		return &clutter((&decode_symb($symbparm))[2]);
                   8367: 	    }
                   8368: 	    return &hreflocation('',$env{'request.filename'});
                   8369: 	}
1.693     albertel 8370: 
                   8371: 	my ($section, $group, @groups);
1.593     albertel 8372: 	my ($courselevelm,$courselevel);
1.539     albertel 8373: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8374: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8375: 
1.218     albertel 8376: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8377: 
1.60      www      8378: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8379: 	    my $symbp=$symbparm;
1.735     albertel 8380: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8381: 
                   8382: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8383: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8384: 
1.620     albertel 8385: 	    if (($env{'user.name'} eq $uname) &&
                   8386: 		($env{'user.domain'} eq $udom)) {
                   8387: 		$section=$env{'request.course.sec'};
1.733     raeburn  8388:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8389:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8390: 	    } else {
1.539     albertel 8391: 		if (! defined($usection)) {
1.551     albertel 8392: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8393: 		} else {
                   8394: 		    $section = $usection;
                   8395: 		}
1.733     raeburn  8396:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8397: 	    }
                   8398: 
                   8399: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8400: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8401: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8402: 
1.593     albertel 8403: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8404: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8405: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8406: 
1.60      www      8407: # ----------------------------------------------------------- first, check user
1.624     albertel 8408: 
                   8409: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8410: 				       ([$courselevelr,'resource'],
                   8411: 					[$courselevelm,'map'     ],
                   8412: 					[$courselevel, 'course'  ]));
1.931     albertel 8413: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8414: 
1.594     albertel 8415: # ------------------------------------------------ second, check some of course
1.684     raeburn  8416:             my $coursereply;
1.691     raeburn  8417:             if (@groups > 0) {
                   8418:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8419:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8420:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8421:             }
1.96      www      8422: 
1.684     raeburn  8423: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8424: 				  $env{'course.'.$courseid.'.domain'},
                   8425: 				  'course',
                   8426: 				  ([$seclevelr,   'resource'],
                   8427: 				   [$seclevelm,   'map'     ],
                   8428: 				   [$seclevel,    'course'  ],
                   8429: 				   [$courselevelr,'resource']));
                   8430: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8431: 
1.60      www      8432: # ------------------------------------------------------ third, check map parms
1.218     albertel 8433: 	    my %parmhash=();
                   8434: 	    my $thisparm='';
                   8435: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8436: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8437: 		    &GDBM_READER(),0640)) {
1.218     albertel 8438: 		$thisparm=$parmhash{$symbparm};
                   8439: 		untie(%parmhash);
                   8440: 	    }
1.927     albertel 8441: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8442: 	}
1.594     albertel 8443: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8444: 
1.218     albertel 8445: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8446: 	my $filename;
                   8447: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8448: 	if ($symbparm) {
1.409     www      8449: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8450: 	} else {
1.620     albertel 8451: 	    $filename=$env{'request.filename'};
1.282     albertel 8452: 	}
                   8453: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8454: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8455: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8456: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8457: 
1.927     albertel 8458: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8459: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8460: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8461: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8462: 				     $env{'course.'.$courseid.'.domain'},
                   8463: 				     'course',
1.927     albertel 8464: 				     ([$courselevelm,'map'   ],
                   8465: 				      [$courselevel, 'course']));
                   8466: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8467: 	}
1.145     www      8468: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8469: 	unless ($space eq '0') {
1.336     albertel 8470: 	    my @parts=split(/_/,$space);
                   8471: 	    my $id=pop(@parts);
                   8472: 	    my $part=join('_',@parts);
                   8473: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8474: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8475: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8476: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8477: 	}
1.395     albertel 8478: 	if ($recurse) { return undef; }
                   8479: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8480: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8481: # ---------------------------------------------------- Any other user namespace
                   8482:     } elsif ($realm eq 'environment') {
                   8483: # ----------------------------------------------------------------- environment
1.620     albertel 8484: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8485: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8486: 	} else {
1.770     albertel 8487: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8488: 		return '';
                   8489: 	    }
1.219     albertel 8490: 	    my %returnhash=&userenvironment($udom,$uname,
                   8491: 					    $spacequalifierrest);
                   8492: 	    return $returnhash{$spacequalifierrest};
                   8493: 	}
1.28      www      8494:     } elsif ($realm eq 'system') {
1.48      www      8495: # ----------------------------------------------------------------- system.time
                   8496: 	if ($space eq 'time') {
                   8497: 	    return time;
                   8498:         }
1.696     albertel 8499:     } elsif ($realm eq 'server') {
                   8500: # ----------------------------------------------------------------- system.time
                   8501: 	if ($space eq 'name') {
                   8502: 	    return $ENV{'SERVER_NAME'};
                   8503:         }
1.28      www      8504:     }
1.48      www      8505:     return '';
1.61      www      8506: }
                   8507: 
1.927     albertel 8508: sub get_reply {
                   8509:     my ($reply_value) = @_;
1.940     raeburn  8510:     if (ref($reply_value) eq 'ARRAY') {
                   8511:         if (wantarray) {
                   8512: 	    return @$reply_value;
                   8513:         }
                   8514:         return $reply_value->[0];
                   8515:     } else {
                   8516:         return $reply_value;
1.927     albertel 8517:     }
                   8518: }
                   8519: 
1.691     raeburn  8520: sub check_group_parms {
                   8521:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8522:     my @groupitems = ();
                   8523:     my $resultitem;
1.927     albertel 8524:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8525:     foreach my $group (@{$groups}) {
                   8526:         foreach my $level (@levels) {
1.927     albertel 8527:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8528:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8529:         }
                   8530:     }
                   8531:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8532:                             $env{'course.'.$courseid.'.domain'},
                   8533:                                      'course',@groupitems);
                   8534:     return $coursereply;
                   8535: }
                   8536: 
                   8537: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8538:     my ($courseid,@groups) = @_;
                   8539:     @groups = sort(@groups);
1.691     raeburn  8540:     return @groups;
                   8541: }
                   8542: 
1.395     albertel 8543: sub packages_tab_default {
                   8544:     my ($uri,$varname)=@_;
                   8545:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8546: 
                   8547:     my (@extension,@specifics,$do_default);
                   8548:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8549: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8550: 	if ($pack_type eq 'default') {
                   8551: 	    $do_default=1;
                   8552: 	} elsif ($pack_type eq 'extension') {
                   8553: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8554: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8555: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8556: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8557: 	}
                   8558:     }
                   8559:     # first look for a package that matches the requested part id
                   8560:     foreach my $package (@specifics) {
                   8561: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8562: 	next if ($pack_part ne $part);
                   8563: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8564: 	    return $packagetab{"$pack_type&$name&default"};
                   8565: 	}
                   8566:     }
                   8567:     # look for any possible matching non extension_ package
                   8568:     foreach my $package (@specifics) {
                   8569: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8570: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8571: 	    return $packagetab{"$pack_type&$name&default"};
                   8572: 	}
1.585     albertel 8573: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8574: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8575: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8576: 	}
                   8577:     }
1.738     albertel 8578:     # look for any posible extension_ match
                   8579:     foreach my $package (@extension) {
                   8580: 	my ($package,$pack_type)=@{$package};
                   8581: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8582: 	    return $packagetab{"$pack_type&$name&default"};
                   8583: 	}
                   8584: 	if (defined($packagetab{$package."&$name&default"})) {
                   8585: 	    return $packagetab{$package."&$name&default"};
                   8586: 	}
                   8587:     }
                   8588:     # look for a global default setting
                   8589:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8590: 	return $packagetab{"default&$name&default"};
                   8591:     }
1.395     albertel 8592:     return undef;
                   8593: }
                   8594: 
1.334     albertel 8595: sub add_prefix_and_part {
                   8596:     my ($prefix,$part)=@_;
                   8597:     my $keyroot;
                   8598:     if (defined($prefix) && $prefix !~ /^__/) {
                   8599: 	# prefix that has a part already
                   8600: 	$keyroot=$prefix;
                   8601:     } elsif (defined($prefix)) {
                   8602: 	# prefix that is missing a part
                   8603: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8604:     } else {
                   8605: 	# no prefix at all
                   8606: 	if (defined($part)) { $keyroot='_'.$part; }
                   8607:     }
                   8608:     return $keyroot;
                   8609: }
                   8610: 
1.71      www      8611: # ---------------------------------------------------------------- Get metadata
                   8612: 
1.599     albertel 8613: my %metaentry;
1.1070    www      8614: my %importedpartids;
1.71      www      8615: sub metadata {
1.176     www      8616:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8617:     $uri=&declutter($uri);
1.288     albertel 8618:     # if it is a non metadata possible uri return quickly
1.529     albertel 8619:     if (($uri eq '') || 
                   8620: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8621: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8622:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8623: 	return undef;
                   8624:     }
                   8625:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8626: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8627: 	return undef;
1.288     albertel 8628:     }
1.73      www      8629:     my $filename=$uri;
                   8630:     $uri=~s/\.meta$//;
1.172     www      8631: #
                   8632: # Is the metadata already cached?
1.177     www      8633: # Look at timestamp of caching
1.172     www      8634: # Everything is cached by the main uri, libraries are never directly cached
                   8635: #
1.428     albertel 8636:     if (!defined($liburi)) {
1.599     albertel 8637: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8638: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8639:     }
                   8640:     {
1.1069    www      8641: # Imported parts would go here
1.1070    www      8642:         my %importedids=();
                   8643:         my @origfileimportpartids=();
1.1069    www      8644:         my $importedparts=0;
1.172     www      8645: #
                   8646: # Is this a recursive call for a library?
                   8647: #
1.599     albertel 8648: #	if (! exists($metacache{$uri})) {
                   8649: #	    $metacache{$uri}={};
                   8650: #	}
1.924     albertel 8651: 	my $cachetime = 60*60;
1.171     www      8652:         if ($liburi) {
                   8653: 	    $liburi=&declutter($liburi);
                   8654:             $filename=$liburi;
1.401     bowersj2 8655:         } else {
1.599     albertel 8656: 	    &devalidate_cache_new('meta',$uri);
                   8657: 	    undef(%metaentry);
1.401     bowersj2 8658: 	}
1.140     www      8659:         my %metathesekeys=();
1.73      www      8660:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8661: 	my $metastring;
1.924     albertel 8662: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8663: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8664: 	    $metastring = 
1.929     albertel 8665: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8666: 					  ('grade_target' => 'meta'));
                   8667: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8668: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8669:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8670: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8671: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8672: 	    $metastring=&getfile($file);
1.489     albertel 8673: 	}
1.208     albertel 8674:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8675:         my $token;
1.140     www      8676:         undef %metathesekeys;
1.71      www      8677:         while ($token=$parser->get_token) {
1.339     albertel 8678: 	    if ($token->[0] eq 'S') {
                   8679: 		if (defined($token->[2]->{'package'})) {
1.172     www      8680: #
                   8681: # This is a package - get package info
                   8682: #
1.339     albertel 8683: 		    my $package=$token->[2]->{'package'};
                   8684: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8685: 		    if (defined($token->[2]->{'id'})) { 
                   8686: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8687: 		    }
1.599     albertel 8688: 		    if ($metaentry{':packages'}) {
                   8689: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8690: 		    } else {
1.599     albertel 8691: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8692: 		    }
1.736     albertel 8693: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8694: 			my $part=$keyroot;
                   8695: 			$part=~s/^\_//;
1.736     albertel 8696: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8697: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8698: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8699: 			    # ignore package.tab specified default values
                   8700:                             # here &package_tab_default() will fetch those
                   8701: 			    if ($subp eq 'default') { next; }
1.736     albertel 8702: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8703: 			    my $unikey;
                   8704: 			    if ($pack =~ /_0$/) {
                   8705: 				$unikey='parameter_0_'.$name;
                   8706: 				$part=0;
                   8707: 			    } else {
                   8708: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8709: 			    }
1.339     albertel 8710: 			    if ($subp eq 'display') {
                   8711: 				$value.=' [Part: '.$part.']';
                   8712: 			    }
1.599     albertel 8713: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8714: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8715: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8716: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8717: 			    }
1.599     albertel 8718: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8719: 				$metaentry{':'.$unikey}=
                   8720: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8721: 			    }
1.339     albertel 8722: 			}
                   8723: 		    }
                   8724: 		} else {
1.172     www      8725: #
                   8726: # This is not a package - some other kind of start tag
1.339     albertel 8727: #
                   8728: 		    my $entry=$token->[1];
1.1068    www      8729: 		    my $unikey='';
1.175     www      8730: 
1.339     albertel 8731: 		    if ($entry eq 'import') {
1.175     www      8732: #
                   8733: # Importing a library here
1.339     albertel 8734: #
1.1067    www      8735:                         my $location=$parser->get_text('/import');
                   8736:                         my $dir=$filename;
                   8737:                         $dir=~s|[^/]*$||;
                   8738:                         $location=&filelocation($dir,$location);
1.1069    www      8739:                        
1.1068    www      8740:                         my $importmode=$token->[2]->{'importmode'};
                   8741:                         if ($importmode eq 'problem') {
1.1069    www      8742: # Import as problem/response
1.1068    www      8743:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8744:                         } elsif ($importmode eq 'part') {
                   8745: # Import as part(s)
1.1069    www      8746:                            $importedparts=1;
                   8747: # We need to get the original file and the imported file to get the part order correct
                   8748: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8749: # Load and inspect original file
1.1070    www      8750:                            if ($#origfileimportpartids<0) {
                   8751:                               undef(%importedpartids);
                   8752:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8753:                               my $origfile=&getfile($origfilelocation);
                   8754:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8755:                            }
                   8756: 
1.1069    www      8757: # Load and inspect imported file
                   8758:                            my $impfile=&getfile($location);
                   8759:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8760:                            if ($#impfilepartids>=0) {
                   8761: # This problem had parts
1.1070    www      8762:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8763:                            } else {
                   8764: # Importing by turning a single problem into a problem part
                   8765: # It gets the import-tags ID as part-ID
                   8766:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8767:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8768:                            }
1.1068    www      8769:                         } else {
                   8770: # Normal import
                   8771:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8772:                            if (defined($token->[2]->{'id'})) {
                   8773:                               $unikey.='_'.$token->[2]->{'id'};
                   8774:                            }
1.1067    www      8775:                         }
                   8776: 
1.339     albertel 8777: 			if ($depthcount<20) {
1.736     albertel 8778: 			    my $metadata = 
                   8779: 				&metadata($uri,'keys', $location,$unikey,
                   8780: 					  $depthcount+1);
                   8781: 			    foreach my $meta (split(',',$metadata)) {
                   8782: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8783: 				$metathesekeys{$meta}=1;
1.339     albertel 8784: 			    }
1.1068    www      8785: 			
                   8786:                         }
1.1067    www      8787: 		    } else {
                   8788: #
                   8789: # Not importing, some other kind of non-package, non-library start tag
                   8790: # 
                   8791:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8792:                         if (defined($token->[2]->{'id'})) {
                   8793:                             $unikey.='_'.$token->[2]->{'id'};
                   8794:                         }
1.339     albertel 8795: 			if (defined($token->[2]->{'name'})) { 
                   8796: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8797: 			}
                   8798: 			$metathesekeys{$unikey}=1;
1.736     albertel 8799: 			foreach my $param (@{$token->[3]}) {
                   8800: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8801: 				$token->[2]->{$param};
1.339     albertel 8802: 			}
                   8803: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8804: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8805: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8806: 		 # only ws inside the tag, and not in default, so use default
                   8807: 		 # as value
1.599     albertel 8808: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8809: 			} elsif ( $internaltext =~ /\S/ ) {
                   8810: 		  # something interesting inside the tag
                   8811: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8812: 			} else {
1.908     albertel 8813: 		  # no interesting values, don't set a default
1.339     albertel 8814: 			}
1.172     www      8815: # end of not-a-package not-a-library import
1.339     albertel 8816: 		    }
1.172     www      8817: # end of not-a-package start tag
1.339     albertel 8818: 		}
1.172     www      8819: # the next is the end of "start tag"
1.339     albertel 8820: 	    }
                   8821: 	}
1.483     albertel 8822: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8823: 	$extension = lc($extension);
                   8824: 	if ($extension eq 'htm') { $extension='html'; }
                   8825: 
1.737     albertel 8826: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8827: 	    #no specific packages #how's our extension
                   8828: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8829: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8830: 					 \%metathesekeys);
                   8831: 	}
1.883     albertel 8832: 
                   8833: 	if (!exists($metaentry{':packages'})
                   8834: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8835: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8836: 		#no specific packages well let's get default then
                   8837: 		if ($key!~/^default&/) { next; }
1.488     albertel 8838: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8839: 					     \%metathesekeys);
                   8840: 	    }
                   8841: 	}
1.338     www      8842: # are there custom rights to evaluate
1.599     albertel 8843: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8844: 
1.338     www      8845:     #
                   8846:     # Importing a rights file here
1.339     albertel 8847:     #
                   8848: 	    unless ($depthcount) {
1.599     albertel 8849: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8850: 		my $dir=$filename;
                   8851: 		$dir=~s|[^/]*$||;
                   8852: 		$location=&filelocation($dir,$location);
1.736     albertel 8853: 		my $rights_metadata =
                   8854: 		    &metadata($uri,'keys',$location,'_rights',
                   8855: 			      $depthcount+1);
                   8856: 		foreach my $rights (split(',',$rights_metadata)) {
                   8857: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8858: 		    $metathesekeys{$rights}=1;
1.339     albertel 8859: 		}
                   8860: 	    }
                   8861: 	}
1.737     albertel 8862: 	# uniqifiy package listing
                   8863: 	my %seen;
                   8864: 	my @uniq_packages =
                   8865: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8866: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8867: 
1.1070    www      8868:         if ($importedparts) {
                   8869: # We had imported parts and need to rebuild partorder
                   8870:            $metaentry{':partorder'}='';
                   8871:            $metathesekeys{'partorder'}=1;
                   8872:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8873:                if ($origfileimportpartids[$index] eq 'part') {
                   8874: # original part, part of the problem
                   8875:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8876:                } else {
                   8877: # we have imported parts at this position
                   8878:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8879:                }
                   8880:            }
                   8881:            $metaentry{':partorder'}=~s/^\,//;
                   8882:         }
                   8883: 
1.737     albertel 8884: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8885: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8886: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8887: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8888: # this is the end of "was not already recently cached
1.71      www      8889:     }
1.599     albertel 8890:     return $metaentry{':'.$what};
1.261     albertel 8891: }
                   8892: 
1.488     albertel 8893: sub metadata_create_package_def {
1.483     albertel 8894:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8895:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8896:     if ($subp eq 'default') { next; }
                   8897:     
1.599     albertel 8898:     if (defined($metaentry{':packages'})) {
                   8899: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8900:     } else {
1.599     albertel 8901: 	$metaentry{':packages'}=$package;
1.483     albertel 8902:     }
                   8903:     my $value=$packagetab{$key};
                   8904:     my $unikey;
                   8905:     $unikey='parameter_0_'.$name;
1.599     albertel 8906:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8907:     $$metathesekeys{$unikey}=1;
1.599     albertel 8908:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8909: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8910:     }
1.599     albertel 8911:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8912: 	$metaentry{':'.$unikey}=
                   8913: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8914:     }
                   8915: }
                   8916: 
1.261     albertel 8917: sub metadata_generate_part0 {
                   8918:     my ($metadata,$metacache,$uri) = @_;
                   8919:     my %allnames;
1.737     albertel 8920:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8921: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8922: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8923: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8924: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8925: 	    $allnames{$name}=$part;
                   8926: 	  }
                   8927: 	}
                   8928:     }
                   8929:     foreach my $name (keys(%allnames)) {
                   8930:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8931:       my $key=":parameter_0_$name";
1.261     albertel 8932:       $$metacache{"$key.part"}='0';
                   8933:       $$metacache{"$key.name"}=$name;
1.428     albertel 8934:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8935: 					   $allnames{$name}.'_'.$name.
                   8936: 					   '.type'};
1.428     albertel 8937:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8938: 			     '.display'};
1.644     www      8939:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8940:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8941:       $$metacache{"$key.display"}=$olddis;
                   8942:     }
1.71      www      8943: }
                   8944: 
1.764     albertel 8945: # ------------------------------------------------------ Devalidate title cache
                   8946: 
                   8947: sub devalidate_title_cache {
                   8948:     my ($url)=@_;
                   8949:     if (!$env{'request.course.id'}) { return; }
                   8950:     my $symb=&symbread($url);
                   8951:     if (!$symb) { return; }
                   8952:     my $key=$env{'request.course.id'}."\0".$symb;
                   8953:     &devalidate_cache_new('title',$key);
                   8954: }
                   8955: 
1.1014    droeschl 8956: # ------------------------------------------------- Get the title of a course
                   8957: 
                   8958: sub current_course_title {
                   8959:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8960: }
1.301     www      8961: # ------------------------------------------------- Get the title of a resource
                   8962: 
                   8963: sub gettitle {
                   8964:     my $urlsymb=shift;
                   8965:     my $symb=&symbread($urlsymb);
1.534     albertel 8966:     if ($symb) {
1.620     albertel 8967: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8968: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8969: 	if (defined($cached)) { 
                   8970: 	    return $result;
                   8971: 	}
1.534     albertel 8972: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8973: 	my $title='';
1.907     albertel 8974: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8975: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8976: 	} else {
                   8977: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8978: 		    &GDBM_READER(),0640)) {
                   8979: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8980: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8981: 		untie(%bighash);
                   8982: 	    }
1.534     albertel 8983: 	}
                   8984: 	$title=~s/\&colon\;/\:/gs;
                   8985: 	if ($title) {
1.599     albertel 8986: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8987: 	}
                   8988: 	$urlsymb=$url;
                   8989:     }
                   8990:     my $title=&metadata($urlsymb,'title');
                   8991:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8992:     return $title;
1.301     www      8993: }
1.613     albertel 8994: 
1.614     albertel 8995: sub get_slot {
                   8996:     my ($which,$cnum,$cdom)=@_;
                   8997:     if (!$cnum || !$cdom) {
1.790     albertel 8998: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8999: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9000: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9001:     }
1.703     albertel 9002:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9003:     my %slotinfo;
                   9004:     if (exists($remembered{$key})) {
                   9005: 	$slotinfo{$which} = $remembered{$key};
                   9006:     } else {
                   9007: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9008: 	&Apache::lonhomework::showhash(%slotinfo);
                   9009: 	my ($tmp)=keys(%slotinfo);
                   9010: 	if ($tmp=~/^error:/) { return (); }
                   9011: 	$remembered{$key} = $slotinfo{$which};
                   9012:     }
1.616     albertel 9013:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9014: 	return %{$slotinfo{$which}};
                   9015:     }
                   9016:     return $slotinfo{$which};
1.614     albertel 9017: }
1.31      www      9018: # ------------------------------------------------- Update symbolic store links
                   9019: 
                   9020: sub symblist {
                   9021:     my ($mapname,%newhash)=@_;
1.438     www      9022:     $mapname=&deversion(&declutter($mapname));
1.31      www      9023:     my %hash;
1.620     albertel 9024:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9025:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9026:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9027: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9028: 		next if ($url eq 'last_known'
                   9029: 			 && $env{'form.no_update_last_known'});
                   9030: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9031: 						    $newhash{$url}->[1],
                   9032: 						    $newhash{$url}->[0]);
1.191     harris41 9033:             }
1.31      www      9034:             if (untie(%hash)) {
                   9035: 		return 'ok';
                   9036:             }
                   9037:         }
                   9038:     }
                   9039:     return 'error';
1.212     www      9040: }
                   9041: 
                   9042: # --------------------------------------------------------------- Verify a symb
                   9043: 
                   9044: sub symbverify {
1.510     www      9045:     my ($symb,$thisurl)=@_;
                   9046:     my $thisfn=$thisurl;
1.439     www      9047:     $thisfn=&declutter($thisfn);
1.215     www      9048: # direct jump to resource in page or to a sequence - will construct own symbs
                   9049:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9050: # check URL part
1.409     www      9051:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9052: 
1.431     www      9053:     unless ($url eq $thisfn) { return 0; }
1.213     www      9054: 
1.216     www      9055:     $symb=&symbclean($symb);
1.510     www      9056:     $thisurl=&deversion($thisurl);
1.439     www      9057:     $thisfn=&deversion($thisfn);
1.213     www      9058: 
                   9059:     my %bighash;
                   9060:     my $okay=0;
1.431     www      9061: 
1.620     albertel 9062:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9063:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9064:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9065:             $thisurl =~ s/\?.+$//;
                   9066:         }
1.510     www      9067:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9068:         unless ($ids) {
                   9069:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9070:             $ids=$bighash{$idkey};
1.216     www      9071:         }
                   9072:         if ($ids) {
                   9073: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9074: 	    foreach my $id (split(/\,/,$ids)) {
                   9075: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9076:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9077:                    $symb =~ s/\?.+$//;
                   9078:                }
1.216     www      9079:                if (
                   9080:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9081:    eq $symb) { 
1.620     albertel 9082: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9083: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9084:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9085: 		       $okay=1; 
                   9086: 		   }
                   9087: 	       }
1.216     www      9088: 	   }
                   9089:         }
1.213     www      9090: 	untie(%bighash);
                   9091:     }
                   9092:     return $okay;
1.31      www      9093: }
                   9094: 
1.210     www      9095: # --------------------------------------------------------------- Clean-up symb
                   9096: 
                   9097: sub symbclean {
                   9098:     my $symb=shift;
1.568     albertel 9099:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9100: # remove version from map
                   9101:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9102: 
1.210     www      9103: # remove version from URL
                   9104:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9105: 
1.507     www      9106: # remove wrapper
                   9107: 
1.510     www      9108:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9109:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9110:     return $symb;
1.409     www      9111: }
                   9112: 
                   9113: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9114: 
                   9115: sub encode_symb {
                   9116:     my ($map,$resid,$url)=@_;
                   9117:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9118: }
1.409     www      9119: 
                   9120: sub decode_symb {
1.568     albertel 9121:     my $symb=shift;
                   9122:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9123:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9124:     return (&fixversion($map),$resid,&fixversion($url));
                   9125: }
                   9126: 
                   9127: sub fixversion {
                   9128:     my $fn=shift;
1.609     banghart 9129:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9130:     my %bighash;
                   9131:     my $uri=&clutter($fn);
1.620     albertel 9132:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9133: # is this cached?
1.599     albertel 9134:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9135:     if (defined($cached)) { return $result; }
                   9136: # unfortunately not cached, or expired
1.620     albertel 9137:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9138: 	    &GDBM_READER(),0640)) {
                   9139:  	if ($bighash{'version_'.$uri}) {
                   9140:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9141:  	    unless (($version eq 'mostrecent') || 
                   9142: 		    ($version==&getversion($uri))) {
1.440     www      9143:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9144:  	    }
                   9145:  	}
                   9146:  	untie %bighash;
1.413     www      9147:     }
1.599     albertel 9148:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9149: }
                   9150: 
                   9151: sub deversion {
                   9152:     my $url=shift;
                   9153:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9154:     return $url;
1.210     www      9155: }
                   9156: 
1.31      www      9157: # ------------------------------------------------------ Return symb list entry
                   9158: 
                   9159: sub symbread {
1.249     www      9160:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9161:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9162:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9163: # no filename provided? try from environment
1.44      www      9164:     unless ($thisfn) {
1.620     albertel 9165:         if ($env{'request.symb'}) {
                   9166: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9167: 	}
1.620     albertel 9168: 	$thisfn=$env{'request.filename'};
1.44      www      9169:     }
1.569     albertel 9170:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9171: # is that filename actually a symb? Verify, clean, and return
                   9172:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9173: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9174: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9175: 	}
1.242     www      9176:     }
1.44      www      9177:     $thisfn=declutter($thisfn);
1.31      www      9178:     my %hash;
1.37      www      9179:     my %bighash;
                   9180:     my $syval='';
1.620     albertel 9181:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9182:         my $targetfn = $thisfn;
1.609     banghart 9183:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9184:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9185:         }
1.687     albertel 9186: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9187: 	    $targetfn=$1;
                   9188: 	}
1.620     albertel 9189:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9190:                       &GDBM_READER(),0640)) {
1.481     raeburn  9191: 	    $syval=$hash{$targetfn};
1.37      www      9192:             untie(%hash);
                   9193:         }
                   9194: # ---------------------------------------------------------- There was an entry
                   9195:         if ($syval) {
1.601     albertel 9196: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9197: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9198: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9199: 		    #return $env{$cache_str}='';
1.601     albertel 9200: 		#}    
                   9201: 		#$syval.=$1;
                   9202: 	    #}
1.37      www      9203:         } else {
                   9204: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9205:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9206:                             &GDBM_READER(),0640)) {
1.37      www      9207: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9208:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9209:               unless ($ids) { 
                   9210:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9211:               }
                   9212:               unless ($ids) {
                   9213: # alias?
                   9214: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9215:               }
1.37      www      9216:               if ($ids) {
                   9217: # ------------------------------------------------------------------- Has ID(s)
                   9218:                  my @possibilities=split(/\,/,$ids);
1.39      www      9219:                  if ($#possibilities==0) {
                   9220: # ----------------------------------------------- There is only one possibility
1.37      www      9221: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9222: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9223: 						    $resid,$thisfn);
1.249     www      9224:                  } elsif (!$donotrecurse) {
1.39      www      9225: # ------------------------------------------ There is more than one possibility
                   9226:                      my $realpossible=0;
1.800     albertel 9227:                      foreach my $id (@possibilities) {
                   9228: 			 my $file=$bighash{'src_'.$id};
1.39      www      9229:                          if (&allowed('bre',$file)) {
1.800     albertel 9230:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9231:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9232: 				$realpossible++;
1.626     albertel 9233:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9234: 						    $resid,$thisfn);
1.39      www      9235:                             }
                   9236: 			 }
1.191     harris41 9237:                      }
1.39      www      9238: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9239:                  } else {
                   9240:                      $syval='';
1.37      www      9241:                  }
                   9242: 	      }
                   9243:               untie(%bighash)
1.481     raeburn  9244:            }
1.31      www      9245:         }
1.62      www      9246:         if ($syval) {
1.620     albertel 9247: 	    return $env{$cache_str}=$syval;
1.62      www      9248:         }
1.31      www      9249:     }
1.949     raeburn  9250:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9251:     return $env{$cache_str}='';
1.31      www      9252: }
                   9253: 
                   9254: # ---------------------------------------------------------- Return random seed
                   9255: 
1.32      www      9256: sub numval {
                   9257:     my $txt=shift;
                   9258:     $txt=~tr/A-J/0-9/;
                   9259:     $txt=~tr/a-j/0-9/;
                   9260:     $txt=~tr/K-T/0-9/;
                   9261:     $txt=~tr/k-t/0-9/;
                   9262:     $txt=~tr/U-Z/0-5/;
                   9263:     $txt=~tr/u-z/0-5/;
                   9264:     $txt=~s/\D//g;
1.564     albertel 9265:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9266:     return int($txt);
1.368     albertel 9267: }
                   9268: 
1.484     albertel 9269: sub numval2 {
                   9270:     my $txt=shift;
                   9271:     $txt=~tr/A-J/0-9/;
                   9272:     $txt=~tr/a-j/0-9/;
                   9273:     $txt=~tr/K-T/0-9/;
                   9274:     $txt=~tr/k-t/0-9/;
                   9275:     $txt=~tr/U-Z/0-5/;
                   9276:     $txt=~tr/u-z/0-5/;
                   9277:     $txt=~s/\D//g;
                   9278:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9279:     my $total;
                   9280:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9281:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9282:     return int($total);
                   9283: }
                   9284: 
1.575     albertel 9285: sub numval3 {
                   9286:     use integer;
                   9287:     my $txt=shift;
                   9288:     $txt=~tr/A-J/0-9/;
                   9289:     $txt=~tr/a-j/0-9/;
                   9290:     $txt=~tr/K-T/0-9/;
                   9291:     $txt=~tr/k-t/0-9/;
                   9292:     $txt=~tr/U-Z/0-5/;
                   9293:     $txt=~tr/u-z/0-5/;
                   9294:     $txt=~s/\D//g;
                   9295:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9296:     my $total;
                   9297:     foreach my $val (@txts) { $total+=$val; }
                   9298:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9299:     return $total;
                   9300: }
                   9301: 
1.675     albertel 9302: sub digest {
                   9303:     my ($data)=@_;
                   9304:     my $digest=&Digest::MD5::md5($data);
                   9305:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9306:     my ($e,$f);
                   9307:     {
                   9308:         use integer;
                   9309:         $e=($a+$b);
                   9310:         $f=($c+$d);
                   9311:         if ($_64bit) {
                   9312:             $e=(($e<<32)>>32);
                   9313:             $f=(($f<<32)>>32);
                   9314:         }
                   9315:     }
                   9316:     if (wantarray) {
                   9317: 	return ($e,$f);
                   9318:     } else {
                   9319: 	my $g;
                   9320: 	{
                   9321: 	    use integer;
                   9322: 	    $g=($e+$f);
                   9323: 	    if ($_64bit) {
                   9324: 		$g=(($g<<32)>>32);
                   9325: 	    }
                   9326: 	}
                   9327: 	return $g;
                   9328:     }
                   9329: }
                   9330: 
1.368     albertel 9331: sub latest_rnd_algorithm_id {
1.675     albertel 9332:     return '64bit5';
1.366     albertel 9333: }
1.32      www      9334: 
1.503     albertel 9335: sub get_rand_alg {
                   9336:     my ($courseid)=@_;
1.790     albertel 9337:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9338:     if ($courseid) {
1.620     albertel 9339: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9340:     }
                   9341:     return &latest_rnd_algorithm_id();
                   9342: }
                   9343: 
1.562     albertel 9344: sub validCODE {
                   9345:     my ($CODE)=@_;
                   9346:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9347:     return 0;
                   9348: }
                   9349: 
1.491     albertel 9350: sub getCODE {
1.620     albertel 9351:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9352:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9353: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9354: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9355: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9356:     }
                   9357:     return undef;
                   9358: }
                   9359: 
1.31      www      9360: sub rndseed {
1.155     albertel 9361:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9362:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9363:     if (!defined($symb)) {
1.366     albertel 9364: 	unless ($symb=$wsymb) { return time; }
                   9365:     }
                   9366:     if (!$courseid) { $courseid=$wcourseid; }
                   9367:     if (!$domain) { $domain=$wdomain; }
                   9368:     if (!$username) { $username=$wusername }
1.503     albertel 9369:     my $which=&get_rand_alg();
1.1110    www      9370: 
1.491     albertel 9371:     if (defined(&getCODE())) {
1.675     albertel 9372: 	if ($which eq '64bit5') {
                   9373: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9374: 	} elsif ($which eq '64bit4') {
1.575     albertel 9375: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9376: 	} else {
                   9377: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9378: 	}
1.675     albertel 9379:     } elsif ($which eq '64bit5') {
                   9380: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9381:     } elsif ($which eq '64bit4') {
                   9382: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9383:     } elsif ($which eq '64bit3') {
                   9384: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9385:     } elsif ($which eq '64bit2') {
                   9386: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9387:     } elsif ($which eq '64bit') {
                   9388: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9389:     }
                   9390:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9391: }
                   9392: 
                   9393: sub rndseed_32bit {
                   9394:     my ($symb,$courseid,$domain,$username)=@_;
                   9395:     {
                   9396: 	use integer;
                   9397: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9398: 	my $symbseed=numval($symb) << 22;
                   9399: 	my $namechck=unpack("%32C*",$username) << 17;
                   9400: 	my $nameseed=numval($username) << 12;
                   9401: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9402: 	my $courseseed=unpack("%32C*",$courseid);
                   9403: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9404: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9405: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9406: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9407: 	return $num;
                   9408:     }
                   9409: }
                   9410: 
                   9411: sub rndseed_64bit {
                   9412:     my ($symb,$courseid,$domain,$username)=@_;
                   9413:     {
                   9414: 	use integer;
                   9415: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9416: 	my $symbseed=numval($symb) << 10;
                   9417: 	my $namechck=unpack("%32S*",$username);
                   9418: 	
                   9419: 	my $nameseed=numval($username) << 21;
                   9420: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9421: 	my $courseseed=unpack("%32S*",$courseid);
                   9422: 	
                   9423: 	my $num1=$symbchck+$symbseed+$namechck;
                   9424: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9425: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9426: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9427: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9428: 	return "$num1,$num2";
1.155     albertel 9429:     }
1.366     albertel 9430: }
                   9431: 
1.443     albertel 9432: sub rndseed_64bit2 {
                   9433:     my ($symb,$courseid,$domain,$username)=@_;
                   9434:     {
                   9435: 	use integer;
                   9436: 	# strings need to be an even # of cahracters long, it it is odd the
                   9437:         # last characters gets thrown away
                   9438: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9439: 	my $symbseed=numval($symb) << 10;
                   9440: 	my $namechck=unpack("%32S*",$username.' ');
                   9441: 	
                   9442: 	my $nameseed=numval($username) << 21;
1.501     albertel 9443: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9444: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9445: 	
                   9446: 	my $num1=$symbchck+$symbseed+$namechck;
                   9447: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9448: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9449: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9450: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9451: 	return "$num1,$num2";
                   9452:     }
                   9453: }
                   9454: 
                   9455: sub rndseed_64bit3 {
                   9456:     my ($symb,$courseid,$domain,$username)=@_;
                   9457:     {
                   9458: 	use integer;
                   9459: 	# strings need to be an even # of cahracters long, it it is odd the
                   9460:         # last characters gets thrown away
                   9461: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9462: 	my $symbseed=numval2($symb) << 10;
                   9463: 	my $namechck=unpack("%32S*",$username.' ');
                   9464: 	
                   9465: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9466: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9467: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9468: 	
                   9469: 	my $num1=$symbchck+$symbseed+$namechck;
                   9470: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9471: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9472: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9473: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9474: 	
1.503     albertel 9475: 	return "$num1:$num2";
1.443     albertel 9476:     }
                   9477: }
                   9478: 
1.575     albertel 9479: sub rndseed_64bit4 {
                   9480:     my ($symb,$courseid,$domain,$username)=@_;
                   9481:     {
                   9482: 	use integer;
                   9483: 	# strings need to be an even # of cahracters long, it it is odd the
                   9484:         # last characters gets thrown away
                   9485: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9486: 	my $symbseed=numval3($symb) << 10;
                   9487: 	my $namechck=unpack("%32S*",$username.' ');
                   9488: 	
                   9489: 	my $nameseed=numval3($username) << 21;
                   9490: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9491: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9492: 	
                   9493: 	my $num1=$symbchck+$symbseed+$namechck;
                   9494: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9495: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9496: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9497: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9498: 	
1.575     albertel 9499: 	return "$num1:$num2";
                   9500:     }
                   9501: }
                   9502: 
1.675     albertel 9503: sub rndseed_64bit5 {
                   9504:     my ($symb,$courseid,$domain,$username)=@_;
                   9505:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9506:     return "$num1:$num2";
                   9507: }
                   9508: 
1.366     albertel 9509: sub rndseed_CODE_64bit {
                   9510:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9511:     {
1.366     albertel 9512: 	use integer;
1.443     albertel 9513: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9514: 	my $symbseed=numval2($symb);
1.491     albertel 9515: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9516: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9517: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9518: 	my $num1=$symbseed+$CODEchck;
                   9519: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9520: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9521: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9522: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9523: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9524: 	return "$num1:$num2";
1.366     albertel 9525:     }
                   9526: }
                   9527: 
1.575     albertel 9528: sub rndseed_CODE_64bit4 {
                   9529:     my ($symb,$courseid,$domain,$username)=@_;
                   9530:     {
                   9531: 	use integer;
                   9532: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9533: 	my $symbseed=numval3($symb);
                   9534: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9535: 	my $CODEseed=numval3(&getCODE());
                   9536: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9537: 	my $num1=$symbseed+$CODEchck;
                   9538: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9539: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9540: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9541: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9542: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9543: 	return "$num1:$num2";
                   9544:     }
                   9545: }
                   9546: 
1.675     albertel 9547: sub rndseed_CODE_64bit5 {
                   9548:     my ($symb,$courseid,$domain,$username)=@_;
                   9549:     my $code = &getCODE();
                   9550:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9551:     return "$num1:$num2";
                   9552: }
                   9553: 
1.366     albertel 9554: sub setup_random_from_rndseed {
                   9555:     my ($rndseed)=@_;
1.503     albertel 9556:     if ($rndseed =~/([,:])/) {
                   9557: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9558: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9559:     } else {
                   9560: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9561:     }
1.36      albertel 9562: }
                   9563: 
1.474     albertel 9564: sub latest_receipt_algorithm_id {
1.835     albertel 9565:     return 'receipt3';
1.474     albertel 9566: }
                   9567: 
1.480     www      9568: sub recunique {
                   9569:     my $fucourseid=shift;
                   9570:     my $unique;
1.835     albertel 9571:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9572: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9573: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9574:     } else {
                   9575: 	$unique=$perlvar{'lonReceipt'};
                   9576:     }
                   9577:     return unpack("%32C*",$unique);
                   9578: }
                   9579: 
                   9580: sub recprefix {
                   9581:     my $fucourseid=shift;
                   9582:     my $prefix;
1.835     albertel 9583:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9584: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9585: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9586:     } else {
                   9587: 	$prefix=$perlvar{'lonHostID'};
                   9588:     }
                   9589:     return unpack("%32C*",$prefix);
                   9590: }
                   9591: 
1.76      www      9592: sub ireceipt {
1.474     albertel 9593:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9594: 
                   9595:     my $return =&recprefix($fucourseid).'-';
                   9596: 
                   9597:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9598: 	$env{'request.state'} eq 'construct') {
                   9599: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9600: 	return $return;
                   9601:     }
                   9602: 
1.76      www      9603:     my $cuname=unpack("%32C*",$funame);
                   9604:     my $cudom=unpack("%32C*",$fudom);
                   9605:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9606:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9607:     my $cunique=&recunique($fucourseid);
1.474     albertel 9608:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9609:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9610: 
1.790     albertel 9611: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9612: 			       
                   9613: 	$return.= ($cunique%$cuname+
                   9614: 		   $cunique%$cudom+
                   9615: 		   $cusymb%$cuname+
                   9616: 		   $cusymb%$cudom+
                   9617: 		   $cucourseid%$cuname+
                   9618: 		   $cucourseid%$cudom+
                   9619: 		   $cpart%$cuname+
                   9620: 		   $cpart%$cudom);
                   9621:     } else {
                   9622: 	$return.= ($cunique%$cuname+
                   9623: 		   $cunique%$cudom+
                   9624: 		   $cusymb%$cuname+
                   9625: 		   $cusymb%$cudom+
                   9626: 		   $cucourseid%$cuname+
                   9627: 		   $cucourseid%$cudom);
                   9628:     }
                   9629:     return $return;
1.76      www      9630: }
                   9631: 
                   9632: sub receipt {
1.474     albertel 9633:     my ($part)=@_;
1.790     albertel 9634:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9635:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9636: }
1.260     ng       9637: 
1.790     albertel 9638: sub whichuser {
                   9639:     my ($passedsymb)=@_;
                   9640:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9641:     if (defined($env{'form.grade_symb'})) {
                   9642: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9643: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9644: 	if (!$allowed &&
                   9645: 	    exists($env{'request.course.sec'}) &&
                   9646: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9647: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9648: 			      '/'.$env{'request.course.sec'});
                   9649: 	}
                   9650: 	if ($allowed) {
                   9651: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9652: 	    $courseid=$tmp_courseid;
                   9653: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9654: 	    ($name)=&get_env_multiple('form.grade_username');
                   9655: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9656: 	}
                   9657:     }
                   9658:     if (!$passedsymb) {
                   9659: 	$symb=&symbread();
                   9660:     } else {
                   9661: 	$symb=$passedsymb;
                   9662:     }
                   9663:     $courseid=$env{'request.course.id'};
                   9664:     $domain=$env{'user.domain'};
                   9665:     $name=$env{'user.name'};
                   9666:     if ($name eq 'public' && $domain eq 'public') {
                   9667: 	if (!defined($env{'form.username'})) {
                   9668: 	    $env{'form.username'}.=time.rand(10000000);
                   9669: 	}
                   9670: 	$name.=$env{'form.username'};
                   9671:     }
                   9672:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9673: 
                   9674: }
                   9675: 
1.36      albertel 9676: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9677: # returns either the contents of the file or 
                   9678: # -1 if the file doesn't exist
1.481     raeburn  9679: #
                   9680: # if the target is a file that was uploaded via DOCS, 
                   9681: # a check will be made to see if a current copy exists on the local server,
                   9682: # if it does this will be served, otherwise a copy will be retrieved from
                   9683: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9684: # the local server.   
1.472     albertel 9685: 
1.36      albertel 9686: sub getfile {
1.538     albertel 9687:     my ($file) = @_;
1.609     banghart 9688:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9689:     &repcopy($file);
                   9690:     return &readfile($file);
                   9691: }
                   9692: 
                   9693: sub repcopy_userfile {
                   9694:     my ($file)=@_;
1.609     banghart 9695:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9696:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9697:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9698: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9699:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9700:     if (-e "$file") {
1.828     www      9701: # we already have a local copy, check it out
1.538     albertel 9702: 	my @fileinfo = stat($file);
1.828     www      9703: 	my $rtncode;
                   9704: 	my $info;
1.538     albertel 9705: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9706: 	if ($lwpresp ne 'ok') {
1.828     www      9707: # there is no such file anymore, even though we had a local copy
1.482     albertel 9708: 	    if ($rtncode eq '404') {
1.538     albertel 9709: 		unlink($file);
1.482     albertel 9710: 	    }
                   9711: 	    return -1;
                   9712: 	}
                   9713: 	if ($info < $fileinfo[9]) {
1.828     www      9714: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9715: 	    return 'ok';
1.828     www      9716: 	} else {
                   9717: # the file is outdated, get rid of it
                   9718: 	    unlink($file);
1.482     albertel 9719: 	}
1.828     www      9720:     }
                   9721: # one way or the other, at this point, we don't have the file
                   9722: # construct the correct path for the file
                   9723:     my @parts = ($cdom,$cnum); 
                   9724:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9725: 	push @parts, split(/\//,$1);
                   9726:     }
                   9727:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9728:     foreach my $part (@parts) {
                   9729: 	$path .= '/'.$part;
                   9730: 	if (!-e $path) {
                   9731: 	    mkdir($path,0770);
1.482     albertel 9732: 	}
                   9733:     }
1.828     www      9734: # now the path exists for sure
                   9735: # get a user agent
                   9736:     my $ua=new LWP::UserAgent;
                   9737:     my $transferfile=$file.'.in.transfer';
                   9738: # FIXME: this should flock
                   9739:     if (-e $transferfile) { return 'ok'; }
                   9740:     my $request;
                   9741:     $uri=~s/^\///;
1.980     raeburn  9742:     my $homeserver = &homeserver($cnum,$cdom);
                   9743:     my $protocol = $protocol{$homeserver};
                   9744:     $protocol = 'http' if ($protocol ne 'https');
                   9745:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9746:     my $response=$ua->request($request,$transferfile);
                   9747: # did it work?
                   9748:     if ($response->is_error()) {
                   9749: 	unlink($transferfile);
                   9750: 	&logthis("Userfile repcopy failed for $uri");
                   9751: 	return -1;
                   9752:     }
                   9753: # worked, rename the transfer file
                   9754:     rename($transferfile,$file);
1.607     raeburn  9755:     return 'ok';
1.481     raeburn  9756: }
                   9757: 
1.517     albertel 9758: sub tokenwrapper {
                   9759:     my $uri=shift;
1.980     raeburn  9760:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9761:     $uri=~s|^/||;
1.620     albertel 9762:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9763:     my $token=$1;
1.552     albertel 9764:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9765:     if ($udom && $uname && $file) {
                   9766: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9767:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9768:         my $homeserver = &homeserver($uname,$udom);
                   9769:         my $protocol = $protocol{$homeserver};
                   9770:         $protocol = 'http' if ($protocol ne 'https');
                   9771:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9772:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9773:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9774:     } else {
                   9775:         return '/adm/notfound.html';
                   9776:     }
                   9777: }
                   9778: 
1.828     www      9779: # call with reqtype HEAD: get last modification time
                   9780: # call with reqtype GET: get the file contents
                   9781: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9782: #
1.481     raeburn  9783: sub getuploaded {
                   9784:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9785:     $uri=~s/^\///;
1.980     raeburn  9786:     my $homeserver = &homeserver($cnum,$cdom);
                   9787:     my $protocol = $protocol{$homeserver};
                   9788:     $protocol = 'http' if ($protocol ne 'https');
                   9789:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9790:     my $ua=new LWP::UserAgent;
                   9791:     my $request=new HTTP::Request($reqtype,$uri);
                   9792:     my $response=$ua->request($request);
                   9793:     $$rtncode = $response->code;
1.482     albertel 9794:     if (! $response->is_success()) {
                   9795: 	return 'failed';
                   9796:     }      
                   9797:     if ($reqtype eq 'HEAD') {
1.486     www      9798: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9799:     } elsif ($reqtype eq 'GET') {
                   9800: 	$$info = $response->content;
1.472     albertel 9801:     }
1.482     albertel 9802:     return 'ok';
1.36      albertel 9803: }
                   9804: 
1.481     raeburn  9805: sub readfile {
                   9806:     my $file = shift;
                   9807:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9808:     my $fh;
                   9809:     open($fh,"<$file");
                   9810:     my $a='';
1.800     albertel 9811:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9812:     return $a;
                   9813: }
                   9814: 
1.36      albertel 9815: sub filelocation {
1.590     banghart 9816:     my ($dir,$file) = @_;
                   9817:     my $location;
                   9818:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9819: 
                   9820:     if ($file =~ m-^/adm/-) {
                   9821: 	$file=~s-^/adm/wrapper/-/-;
                   9822: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9823:     }
1.882     albertel 9824: 
1.590     banghart 9825:     if ($file=~m:^/~:) { # is a contruction space reference
                   9826:         $location = $file;
                   9827:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9828:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9829: 	# is a correct contruction space reference
                   9830:         $location = $file;
1.956     raeburn  9831:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9832:         $location = $file;
1.609     banghart 9833:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9834:         my ($udom,$uname,$filename)=
1.811     albertel 9835:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9836:         my $home=&homeserver($uname,$udom);
                   9837:         my $is_me=0;
                   9838:         my @ids=&current_machine_ids();
                   9839:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9840:         if ($is_me) {
1.1117    foxr     9841:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9842:         } else {
                   9843:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9844:   	      $udom.'/'.$uname.'/'.$filename;
                   9845:         }
1.882     albertel 9846:     } elsif ($file =~ m-^/adm/-) {
                   9847: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9848:     } else {
                   9849:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9850:         $file=~s:^/res/:/:;
                   9851:         if ( !( $file =~ m:^/:) ) {
                   9852:             $location = $dir. '/'.$file;
                   9853:         } else {
                   9854:             $location = '/home/httpd/html/res'.$file;
                   9855:         }
1.59      albertel 9856:     }
1.590     banghart 9857:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9858:     while ($location=~m{/\.\./}) {
                   9859: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9860: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9861: 	} else {
                   9862: 	    $location=~ s{/\.\./}{/}g;
                   9863: 	}
                   9864:     } #remove dir/..
1.590     banghart 9865:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9866:     return $location;
1.46      www      9867: }
1.36      albertel 9868: 
1.46      www      9869: sub hreflocation {
                   9870:     my ($dir,$file)=@_;
1.980     raeburn  9871:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9872: 	$file=filelocation($dir,$file);
1.700     albertel 9873:     } elsif ($file=~m-^/adm/-) {
                   9874: 	$file=~s-^/adm/wrapper/-/-;
                   9875: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9876:     }
                   9877:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9878: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9879:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9880: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9881:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9882: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9883: 	    -/uploaded/$1/$2/-x;
1.46      www      9884:     }
1.913     albertel 9885:     if ($file=~ m{^/userfiles/}) {
                   9886: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9887:     }
1.462     albertel 9888:     return $file;
1.465     albertel 9889: }
                   9890: 
                   9891: sub current_machine_domains {
1.853     albertel 9892:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9893: }
                   9894: 
                   9895: sub machine_domains {
                   9896:     my ($hostname) = @_;
1.465     albertel 9897:     my @domains;
1.838     albertel 9898:     my %hostname = &all_hostnames();
1.465     albertel 9899:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9900: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9901: 	if ($hostname eq $name) {
1.844     albertel 9902: 	    push(@domains,&host_domain($id));
1.465     albertel 9903: 	}
                   9904:     }
                   9905:     return @domains;
                   9906: }
                   9907: 
                   9908: sub current_machine_ids {
1.853     albertel 9909:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9910: }
                   9911: 
                   9912: sub machine_ids {
                   9913:     my ($hostname) = @_;
                   9914:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9915:     my @ids;
1.888     albertel 9916:     my %name_to_host = &all_names();
1.889     albertel 9917:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9918: 	return @{ $name_to_host{$hostname} };
                   9919:     }
                   9920:     return;
1.31      www      9921: }
                   9922: 
1.824     raeburn  9923: sub additional_machine_domains {
                   9924:     my @domains;
                   9925:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9926:     while( my $line = <$fh>) {
                   9927:         $line =~ s/\s//g;
                   9928:         push(@domains,$line);
                   9929:     }
                   9930:     return @domains;
                   9931: }
                   9932: 
                   9933: sub default_login_domain {
                   9934:     my $domain = $perlvar{'lonDefDomain'};
                   9935:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9936:     foreach my $posdom (&current_machine_domains(),
                   9937:                         &additional_machine_domains()) {
                   9938:         if (lc($posdom) eq lc($testdomain)) {
                   9939:             $domain=$posdom;
                   9940:             last;
                   9941:         }
                   9942:     }
                   9943:     return $domain;
                   9944: }
                   9945: 
1.31      www      9946: # ------------------------------------------------------------- Declutters URLs
                   9947: 
                   9948: sub declutter {
                   9949:     my $thisfn=shift;
1.569     albertel 9950:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9951:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9952:     $thisfn=~s/^\///;
1.697     albertel 9953:     $thisfn=~s|^adm/wrapper/||;
                   9954:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9955:     $thisfn=~s/^res\///;
1.1032    raeburn  9956:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9957:         $thisfn=~s/\?.+$//;
                   9958:     }
1.268     www      9959:     return $thisfn;
                   9960: }
                   9961: 
                   9962: # ------------------------------------------------------------- Clutter up URLs
                   9963: 
                   9964: sub clutter {
                   9965:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9966:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9967: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9968:        $thisfn='/res'.$thisfn; 
                   9969:     }
1.1031    raeburn  9970:     if ($thisfn !~m|^/adm|) {
                   9971: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9972: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9973: 	} else {
                   9974: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9975: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9976: 	    if ($embstyle eq 'ssi'
                   9977: 		|| ($embstyle eq 'hdn')
                   9978: 		|| ($embstyle eq 'rat')
                   9979: 		|| ($embstyle eq 'prv')
                   9980: 		|| ($embstyle eq 'ign')) {
                   9981: 		#do nothing with these
                   9982: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9983: 		|| ($embstyle eq 'emb')
                   9984: 		|| ($embstyle eq 'wrp')) {
                   9985: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9986: 	    } elsif ($embstyle eq 'unk'
                   9987: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9988: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9989: 	    } else {
1.718     www      9990: #		&logthis("Got a blank emb style");
1.695     albertel 9991: 	    }
1.694     albertel 9992: 	}
                   9993:     }
1.31      www      9994:     return $thisfn;
1.12      www      9995: }
                   9996: 
1.787     albertel 9997: sub clutter_with_no_wrapper {
                   9998:     my $uri = &clutter(shift);
                   9999:     if ($uri =~ m-^/adm/-) {
                   10000: 	$uri =~ s-^/adm/wrapper/-/-;
                   10001: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10002:     }
                   10003:     return $uri;
                   10004: }
                   10005: 
1.557     albertel 10006: sub freeze_escape {
                   10007:     my ($value)=@_;
                   10008:     if (ref($value)) {
                   10009: 	$value=&nfreeze($value);
                   10010: 	return '__FROZEN__'.&escape($value);
                   10011:     }
                   10012:     return &escape($value);
                   10013: }
                   10014: 
1.11      www      10015: 
1.557     albertel 10016: sub thaw_unescape {
                   10017:     my ($value)=@_;
                   10018:     if ($value =~ /^__FROZEN__/) {
                   10019: 	substr($value,0,10,undef);
                   10020: 	$value=&unescape($value);
                   10021: 	return &thaw($value);
                   10022:     }
                   10023:     return &unescape($value);
                   10024: }
                   10025: 
1.436     albertel 10026: sub correct_line_ends {
                   10027:     my ($result)=@_;
                   10028:     $$result =~s/\r\n/\n/mg;
                   10029:     $$result =~s/\r/\n/mg;
1.415     albertel 10030: }
1.1       albertel 10031: # ================================================================ Main Program
                   10032: 
1.184     www      10033: sub goodbye {
1.204     albertel 10034:    &logthis("Starting Shut down");
1.443     albertel 10035: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10036:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10037: #converted
1.599     albertel 10038: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10039:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10040: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10041: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10042: #1.1 only
1.870     albertel 10043: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10044: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10045: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10046: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10047:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10048:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10049:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10050:    &flushcourselogs();
                   10051:    &logthis("Shutting down");
                   10052: }
                   10053: 
1.852     albertel 10054: sub get_dns {
1.869     albertel 10055:     my ($url,$func,$ignore_cache) = @_;
                   10056:     if (!$ignore_cache) {
                   10057: 	my ($content,$cached)=
                   10058: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10059: 	if ($cached) {
                   10060: 	    &$func($content);
                   10061: 	    return;
                   10062: 	}
                   10063:     }
                   10064: 
                   10065:     my %alldns;
1.852     albertel 10066:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10067:     foreach my $dns (<$config>) {
                   10068: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10069:         my $line = $1;
                   10070:         my ($host,$protocol) = split(/:/,$line);
                   10071:         if ($protocol ne 'https') {
                   10072:             $protocol = 'http';
                   10073:         }
                   10074: 	$alldns{$host} = $protocol;
1.869     albertel 10075:     }
                   10076:     while (%alldns) {
                   10077: 	my ($dns) = keys(%alldns);
1.852     albertel 10078: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10079: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10080: 	my $response=$ua->request($request);
1.979     raeburn  10081:         delete($alldns{$dns});
1.852     albertel 10082: 	next if ($response->is_error());
                   10083: 	my @content = split("\n",$response->content);
1.869     albertel 10084: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10085: 	&$func(\@content);
1.869     albertel 10086: 	return;
1.852     albertel 10087:     }
                   10088:     close($config);
1.871     albertel 10089:     my $which = (split('/',$url))[3];
                   10090:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10091:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10092:     my @content = <$config>;
                   10093:     &$func(\@content);
                   10094:     return;
1.852     albertel 10095: }
1.327     albertel 10096: # ------------------------------------------------------------ Read domain file
                   10097: {
1.852     albertel 10098:     my $loaded;
1.846     albertel 10099:     my %domain;
                   10100: 
1.852     albertel 10101:     sub parse_domain_tab {
                   10102: 	my ($lines) = @_;
                   10103: 	foreach my $line (@$lines) {
                   10104: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10105: 
1.846     albertel 10106: 	    chomp($line);
1.852     albertel 10107: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10108: 	    my %this_domain;
                   10109: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10110: 			       'lang_def', 'city', 'longi', 'lati',
                   10111: 			       'primary') {
                   10112: 		$this_domain{$field} = shift(@elements);
                   10113: 	    }
                   10114: 	    $domain{$name} = \%this_domain;
1.852     albertel 10115: 	}
                   10116:     }
1.864     albertel 10117: 
                   10118:     sub reset_domain_info {
                   10119: 	undef($loaded);
                   10120: 	undef(%domain);
                   10121:     }
                   10122: 
1.852     albertel 10123:     sub load_domain_tab {
1.869     albertel 10124: 	my ($ignore_cache) = @_;
                   10125: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10126: 	my $fh;
                   10127: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10128: 	    my @lines = <$fh>;
                   10129: 	    &parse_domain_tab(\@lines);
1.448     albertel 10130: 	}
1.852     albertel 10131: 	close($fh);
                   10132: 	$loaded = 1;
1.327     albertel 10133:     }
1.846     albertel 10134: 
                   10135:     sub domain {
1.852     albertel 10136: 	&load_domain_tab() if (!$loaded);
                   10137: 
1.846     albertel 10138: 	my ($name,$what) = @_;
                   10139: 	return if ( !exists($domain{$name}) );
                   10140: 
                   10141: 	if (!$what) {
                   10142: 	    return $domain{$name}{'description'};
                   10143: 	}
                   10144: 	return $domain{$name}{$what};
                   10145:     }
1.974     raeburn  10146: 
                   10147:     sub domain_info {
                   10148:         &load_domain_tab() if (!$loaded);
                   10149:         return %domain;
                   10150:     }
                   10151: 
1.327     albertel 10152: }
                   10153: 
                   10154: 
1.1       albertel 10155: # ------------------------------------------------------------- Read hosts file
                   10156: {
1.838     albertel 10157:     my %hostname;
1.844     albertel 10158:     my %hostdom;
1.845     albertel 10159:     my %libserv;
1.852     albertel 10160:     my $loaded;
1.888     albertel 10161:     my %name_to_host;
1.1074    raeburn  10162:     my %internetdom;
1.1107    raeburn  10163:     my %LC_dns_serv;
1.852     albertel 10164: 
                   10165:     sub parse_hosts_tab {
                   10166: 	my ($file) = @_;
                   10167: 	foreach my $configline (@$file) {
                   10168: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10169:             chomp($configline);
                   10170: 	    if ($configline =~ /^\^/) {
                   10171:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10172:                     $LC_dns_serv{$1} = 1;
                   10173:                 }
                   10174:                 next;
                   10175:             }
1.1074    raeburn  10176: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10177: 	    $name=~s/\s//g;
                   10178: 	    if ($id && $domain && $role && $name) {
                   10179: 		$hostname{$id}=$name;
1.888     albertel 10180: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10181: 		$hostdom{$id}=$domain;
                   10182: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10183:                 if (defined($protocol)) {
                   10184:                     if ($protocol eq 'https') {
                   10185:                         $protocol{$id} = $protocol;
                   10186:                     } else {
                   10187:                         $protocol{$id} = 'http'; 
                   10188:                     }
1.968     raeburn  10189:                 } else {
1.969     raeburn  10190:                     $protocol{$id} = 'http';
1.968     raeburn  10191:                 }
1.1074    raeburn  10192:                 if (defined($intdom)) {
                   10193:                     $internetdom{$id} = $intdom;
                   10194:                 }
1.852     albertel 10195: 	    }
                   10196: 	}
                   10197:     }
1.864     albertel 10198:     
                   10199:     sub reset_hosts_info {
1.897     albertel 10200: 	&purge_remembered();
1.864     albertel 10201: 	&reset_domain_info();
                   10202: 	&reset_hosts_ip_info();
1.892     albertel 10203: 	undef(%name_to_host);
1.864     albertel 10204: 	undef(%hostname);
                   10205: 	undef(%hostdom);
                   10206: 	undef(%libserv);
                   10207: 	undef($loaded);
                   10208:     }
1.1       albertel 10209: 
1.852     albertel 10210:     sub load_hosts_tab {
1.869     albertel 10211: 	my ($ignore_cache) = @_;
                   10212: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10213: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10214: 	my @config = <$config>;
                   10215: 	&parse_hosts_tab(\@config);
                   10216: 	close($config);
                   10217: 	$loaded=1;
1.1       albertel 10218:     }
1.852     albertel 10219: 
1.838     albertel 10220:     sub hostname {
1.852     albertel 10221: 	&load_hosts_tab() if (!$loaded);
                   10222: 
1.838     albertel 10223: 	my ($lonid) = @_;
                   10224: 	return $hostname{$lonid};
                   10225:     }
1.845     albertel 10226: 
1.838     albertel 10227:     sub all_hostnames {
1.852     albertel 10228: 	&load_hosts_tab() if (!$loaded);
                   10229: 
1.838     albertel 10230: 	return %hostname;
                   10231:     }
1.845     albertel 10232: 
1.888     albertel 10233:     sub all_names {
                   10234: 	&load_hosts_tab() if (!$loaded);
                   10235: 
                   10236: 	return %name_to_host;
                   10237:     }
                   10238: 
1.974     raeburn  10239:     sub all_host_domain {
                   10240:         &load_hosts_tab() if (!$loaded);
                   10241:         return %hostdom;
                   10242:     }
                   10243: 
1.845     albertel 10244:     sub is_library {
1.852     albertel 10245: 	&load_hosts_tab() if (!$loaded);
                   10246: 
1.845     albertel 10247: 	return exists($libserv{$_[0]});
                   10248:     }
                   10249: 
                   10250:     sub all_library {
1.852     albertel 10251: 	&load_hosts_tab() if (!$loaded);
                   10252: 
1.845     albertel 10253: 	return %libserv;
                   10254:     }
                   10255: 
1.1062    droeschl 10256:     sub unique_library {
                   10257: 	#2x reverse removes all hostnames that appear more than once
                   10258:         my %unique = reverse &all_library();
                   10259:         return reverse %unique;
                   10260:     }
                   10261: 
1.841     albertel 10262:     sub get_servers {
1.852     albertel 10263: 	&load_hosts_tab() if (!$loaded);
                   10264: 
1.841     albertel 10265: 	my ($domain,$type) = @_;
                   10266: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10267: 	                                          : %hostname;
                   10268: 	my %result;
1.842     albertel 10269: 	if (ref($domain) eq 'ARRAY') {
                   10270: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10271: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10272: 		    $result{$host} = $hostname;
                   10273: 		}
                   10274: 	    }
                   10275: 	} else {
                   10276: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10277: 		if ($hostdom{$host} eq $domain) {
                   10278: 		    $result{$host} = $hostname;
                   10279: 		}
1.841     albertel 10280: 	    }
                   10281: 	}
                   10282: 	return %result;
                   10283:     }
1.845     albertel 10284: 
1.1062    droeschl 10285:     sub get_unique_servers {
                   10286:         my %unique = reverse &get_servers(@_);
                   10287: 	return reverse %unique;
                   10288:     }
                   10289: 
1.844     albertel 10290:     sub host_domain {
1.852     albertel 10291: 	&load_hosts_tab() if (!$loaded);
                   10292: 
1.844     albertel 10293: 	my ($lonid) = @_;
                   10294: 	return $hostdom{$lonid};
                   10295:     }
                   10296: 
1.841     albertel 10297:     sub all_domains {
1.852     albertel 10298: 	&load_hosts_tab() if (!$loaded);
                   10299: 
1.841     albertel 10300: 	my %seen;
                   10301: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10302: 	return @uniq;
                   10303:     }
1.1074    raeburn  10304: 
                   10305:     sub internet_dom {
                   10306:         &load_hosts_tab() if (!$loaded);
                   10307: 
                   10308:         my ($lonid) = @_;
                   10309:         return $internetdom{$lonid};
                   10310:     }
1.1107    raeburn  10311: 
                   10312:     sub is_LC_dns {
                   10313:         &load_hosts_tab() if (!$loaded);
                   10314: 
                   10315:         my ($hostname) = @_;
                   10316:         return exists($LC_dns_serv{$hostname});
                   10317:     }
                   10318: 
1.1       albertel 10319: }
                   10320: 
1.847     albertel 10321: { 
                   10322:     my %iphost;
1.856     albertel 10323:     my %name_to_ip;
                   10324:     my %lonid_to_ip;
1.869     albertel 10325: 
1.847     albertel 10326:     sub get_hosts_from_ip {
                   10327: 	my ($ip) = @_;
                   10328: 	my %iphosts = &get_iphost();
                   10329: 	if (ref($iphosts{$ip})) {
                   10330: 	    return @{$iphosts{$ip}};
                   10331: 	}
                   10332: 	return;
1.839     albertel 10333:     }
1.864     albertel 10334:     
                   10335:     sub reset_hosts_ip_info {
                   10336: 	undef(%iphost);
                   10337: 	undef(%name_to_ip);
                   10338: 	undef(%lonid_to_ip);
                   10339:     }
1.856     albertel 10340: 
                   10341:     sub get_host_ip {
                   10342: 	my ($lonid) = @_;
                   10343: 	if (exists($lonid_to_ip{$lonid})) {
                   10344: 	    return $lonid_to_ip{$lonid};
                   10345: 	}
                   10346: 	my $name=&hostname($lonid);
                   10347:    	my $ip = gethostbyname($name);
                   10348: 	return if (!$ip || length($ip) ne 4);
                   10349: 	$ip=inet_ntoa($ip);
                   10350: 	$name_to_ip{$name}   = $ip;
                   10351: 	$lonid_to_ip{$lonid} = $ip;
                   10352: 	return $ip;
                   10353:     }
1.847     albertel 10354:     
                   10355:     sub get_iphost {
1.869     albertel 10356: 	my ($ignore_cache) = @_;
1.894     albertel 10357: 
1.869     albertel 10358: 	if (!$ignore_cache) {
                   10359: 	    if (%iphost) {
                   10360: 		return %iphost;
                   10361: 	    }
                   10362: 	    my ($ip_info,$cached)=
                   10363: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10364: 	    if ($cached) {
                   10365: 		%iphost      = %{$ip_info->[0]};
                   10366: 		%name_to_ip  = %{$ip_info->[1]};
                   10367: 		%lonid_to_ip = %{$ip_info->[2]};
                   10368: 		return %iphost;
                   10369: 	    }
                   10370: 	}
1.894     albertel 10371: 
                   10372: 	# get yesterday's info for fallback
                   10373: 	my %old_name_to_ip;
                   10374: 	my ($ip_info,$cached)=
                   10375: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10376: 	if ($cached) {
                   10377: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10378: 	}
                   10379: 
1.888     albertel 10380: 	my %name_to_host = &all_names();
                   10381: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10382: 	    my $ip;
                   10383: 	    if (!exists($name_to_ip{$name})) {
                   10384: 		$ip = gethostbyname($name);
                   10385: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10386: 		    if (defined($old_name_to_ip{$name})) {
                   10387: 			$ip = $old_name_to_ip{$name};
                   10388: 			&logthis("Can't find $name defaulting to old $ip");
                   10389: 		    } else {
                   10390: 			&logthis("Name $name no IP found");
                   10391: 			next;
                   10392: 		    }
                   10393: 		} else {
                   10394: 		    $ip=inet_ntoa($ip);
1.847     albertel 10395: 		}
                   10396: 		$name_to_ip{$name} = $ip;
                   10397: 	    } else {
                   10398: 		$ip = $name_to_ip{$name};
1.653     albertel 10399: 	    }
1.888     albertel 10400: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10401: 		$lonid_to_ip{$id} = $ip;
                   10402: 	    }
                   10403: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10404: 	}
1.869     albertel 10405: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10406: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10407: 				      48*60*60);
1.869     albertel 10408: 
1.847     albertel 10409: 	return %iphost;
1.598     albertel 10410:     }
                   10411: 
1.992     raeburn  10412:     #
                   10413:     #  Given a DNS returns the loncapa host name for that DNS 
                   10414:     # 
                   10415:     sub host_from_dns {
                   10416:         my ($dns) = @_;
                   10417:         my @hosts;
                   10418:         my $ip;
                   10419: 
1.993     raeburn  10420:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10421:             $ip = $name_to_ip{$dns};
                   10422:         }
                   10423:         if (!$ip) {
                   10424:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10425:             if (length($ip) == 4) { 
                   10426: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10427:             }
                   10428:         }
                   10429:         if ($ip) {
                   10430: 	    @hosts = get_hosts_from_ip($ip);
                   10431: 	    return $hosts[0];
                   10432:         }
                   10433:         return undef;
1.986     foxr     10434:     }
1.992     raeburn  10435: 
1.1074    raeburn  10436:     sub get_internet_names {
                   10437:         my ($lonid) = @_;
                   10438:         return if ($lonid eq '');
                   10439:         my ($idnref,$cached)=
                   10440:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10441:         if ($cached) {
                   10442:             return $idnref;
                   10443:         }
                   10444:         my $ip = &get_host_ip($lonid);
                   10445:         my @hosts = &get_hosts_from_ip($ip);
                   10446:         my %iphost = &get_iphost();
                   10447:         my (@idns,%seen);
                   10448:         foreach my $id (@hosts) {
                   10449:             my $dom = &host_domain($id);
                   10450:             my $prim_id = &domain($dom,'primary');
                   10451:             my $prim_ip = &get_host_ip($prim_id);
                   10452:             next if ($seen{$prim_ip});
                   10453:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10454:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10455:                     my $intdom = &internet_dom($id);
                   10456:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10457:                         push(@idns,$intdom);
                   10458:                     }
                   10459:                 }
                   10460:             }
                   10461:             $seen{$prim_ip} = 1;
                   10462:         }
                   10463:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10464:     }
                   10465: 
1.986     foxr     10466: }
                   10467: 
1.1079    raeburn  10468: sub all_loncaparevs {
                   10469:     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);
                   10470: }
                   10471: 
1.862     albertel 10472: BEGIN {
                   10473: 
                   10474: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10475:     unless ($readit) {
                   10476: {
                   10477:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10478:     %perlvar = (%perlvar,%{$configvars});
                   10479: }
                   10480: 
                   10481: 
1.1       albertel 10482: # ------------------------------------------------------ Read spare server file
                   10483: {
1.448     albertel 10484:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10485: 
                   10486:     while (my $configline=<$config>) {
                   10487:        chomp($configline);
1.284     matthew  10488:        if ($configline) {
1.784     albertel 10489: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10490: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10491: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10492:        }
                   10493:     }
1.448     albertel 10494:     close($config);
1.1       albertel 10495: }
1.11      www      10496: # ------------------------------------------------------------ Read permissions
                   10497: {
1.448     albertel 10498:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10499: 
                   10500:     while (my $configline=<$config>) {
1.448     albertel 10501: 	chomp($configline);
                   10502: 	if ($configline) {
                   10503: 	    my ($role,$perm)=split(/ /,$configline);
                   10504: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10505: 	}
1.11      www      10506:     }
1.448     albertel 10507:     close($config);
1.11      www      10508: }
                   10509: 
                   10510: # -------------------------------------------- Read plain texts for permissions
                   10511: {
1.448     albertel 10512:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10513: 
                   10514:     while (my $configline=<$config>) {
1.448     albertel 10515: 	chomp($configline);
                   10516: 	if ($configline) {
1.742     raeburn  10517: 	    my ($short,@plain)=split(/:/,$configline);
                   10518:             %{$prp{$short}} = ();
                   10519: 	    if (@plain > 0) {
                   10520:                 $prp{$short}{'std'} = $plain[0];
                   10521:                 for (my $i=1; $i<@plain; $i++) {
                   10522:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10523:                 }
                   10524:             }
1.448     albertel 10525: 	}
1.135     www      10526:     }
1.448     albertel 10527:     close($config);
1.135     www      10528: }
                   10529: 
                   10530: # ---------------------------------------------------------- Read package table
                   10531: {
1.448     albertel 10532:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10533: 
                   10534:     while (my $configline=<$config>) {
1.483     albertel 10535: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10536: 	chomp($configline);
                   10537: 	my ($short,$plain)=split(/:/,$configline);
                   10538: 	my ($pack,$name)=split(/\&/,$short);
                   10539: 	if ($plain ne '') {
                   10540: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10541: 	    $packagetab{$short}=$plain; 
                   10542: 	}
1.11      www      10543:     }
1.448     albertel 10544:     close($config);
1.329     matthew  10545: }
                   10546: 
1.1073    raeburn  10547: # ---------------------------------------------------------- Read loncaparev table
                   10548: {
                   10549:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10550:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10551:             while (my $configline=<$config>) {
                   10552:                 chomp($configline);
                   10553:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10554:                 $loncaparevs{$hostid}=$loncaparev;
                   10555:             }
                   10556:             close($config);
                   10557:         }
                   10558:     }
                   10559: }
                   10560: 
1.1074    raeburn  10561: # ---------------------------------------------------------- Read serverhostID table
                   10562: {
                   10563:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10564:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10565:             while (my $configline=<$config>) {
                   10566:                 chomp($configline);
                   10567:                 my ($name,$id)=split(/:/,$configline);
                   10568:                 $serverhomeIDs{$name}=$id;
                   10569:             }
                   10570:             close($config);
                   10571:         }
                   10572:     }
                   10573: }
                   10574: 
1.1079    raeburn  10575: {
                   10576:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10577:     if (-e $file) {
                   10578:         my $parser = HTML::LCParser->new($file);
                   10579:         while (my $token = $parser->get_token()) {
                   10580:             if ($token->[0] eq 'S') {
                   10581:                 my $item = $token->[1];
                   10582:                 my $name = $token->[2]{'name'};
                   10583:                 my $value = $token->[2]{'value'};
                   10584:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10585:                     my $release = $parser->get_text();
                   10586:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10587:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10588:                 }
                   10589:             }
                   10590:         }
                   10591:     }
1.1073    raeburn  10592: }
                   10593: 
1.329     matthew  10594: # ------------- set up temporary directory
                   10595: {
1.1117    foxr     10596:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10597: 
1.11      www      10598: }
                   10599: 
1.794     albertel 10600: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10601: 				'compress_threshold'=> 20_000,
                   10602:  			        });
1.185     www      10603: 
1.281     www      10604: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10605: $dumpcount=0;
1.958     www      10606: $locknum=0;
1.22      www      10607: 
1.163     harris41 10608: &logtouch();
1.672     albertel 10609: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10610: $readit=1;
1.564     albertel 10611:     {
                   10612: 	use integer;
                   10613: 	my $test=(2**32)+1;
1.568     albertel 10614: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10615: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10616:     }
1.195     www      10617: }
1.1       albertel 10618: }
1.179     www      10619: 
1.1       albertel 10620: 1;
1.191     harris41 10621: __END__
                   10622: 
1.243     albertel 10623: =pod
                   10624: 
1.191     harris41 10625: =head1 NAME
                   10626: 
1.243     albertel 10627: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10628: 
                   10629: =head1 SYNOPSIS
                   10630: 
1.243     albertel 10631: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10632: 
                   10633:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10634: 
1.243     albertel 10635: Common parameters:
                   10636: 
                   10637: =over 4
                   10638: 
                   10639: =item *
                   10640: 
                   10641: $uname : an internal username (if $cname expecting a course Id specifically)
                   10642: 
                   10643: =item *
                   10644: 
                   10645: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10646: 
                   10647: =item *
                   10648: 
                   10649: $symb : a resource instance identifier
                   10650: 
                   10651: =item *
                   10652: 
                   10653: $namespace : the name of a .db file that contains the data needed or
                   10654: being set.
                   10655: 
                   10656: =back
                   10657: 
1.394     bowersj2 10658: =head1 OVERVIEW
1.191     harris41 10659: 
1.394     bowersj2 10660: lonnet provides subroutines which interact with the
                   10661: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10662: about classes, users, and resources.
1.243     albertel 10663: 
                   10664: For many of these objects you can also use this to store data about
                   10665: them or modify them in various ways.
1.191     harris41 10666: 
1.394     bowersj2 10667: =head2 Symbs
1.191     harris41 10668: 
1.394     bowersj2 10669: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10670: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10671: map, the resource number of the resource in the map, and the URL of
                   10672: the resource itself. The latter is somewhat redundant, but might help
                   10673: if maps change.
                   10674: 
                   10675: An example is
                   10676: 
                   10677:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10678: 
                   10679: The respective map entry is
                   10680: 
                   10681:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10682:   title="Problem 2">
                   10683:  </resource>
                   10684: 
                   10685: Symbs are used by the random number generator, as well as to store and
                   10686: restore data specific to a certain instance of for example a problem.
                   10687: 
                   10688: =head2 Storing And Retrieving Data
                   10689: 
                   10690: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10691: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10692: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10693: is is the non-critical message twin of cstore. These functions are for
                   10694: handlers to store a perl hash to a user's permanent data space in an
                   10695: easy manner, and to retrieve it again on another call. It is expected
                   10696: that a handler would use this once at the beginning to retrieve data,
                   10697: and then again once at the end to send only the new data back.
                   10698: 
                   10699: The data is stored in the user's data directory on the user's
                   10700: homeserver under the ID of the course.
                   10701: 
                   10702: The hash that is returned by restore will have all of the previous
                   10703: value for all of the elements of the hash.
                   10704: 
                   10705: Example:
                   10706: 
                   10707:  #creating a hash
                   10708:  my %hash;
                   10709:  $hash{'foo'}='bar';
                   10710: 
                   10711:  #storing it
                   10712:  &Apache::lonnet::cstore(\%hash);
                   10713: 
                   10714:  #changing a value
                   10715:  $hash{'foo'}='notbar';
                   10716: 
                   10717:  #adding a new value
                   10718:  $hash{'bar'}='foo';
                   10719:  &Apache::lonnet::cstore(\%hash);
                   10720: 
                   10721:  #retrieving the hash
                   10722:  my %history=&Apache::lonnet::restore();
                   10723: 
                   10724:  #print the hash
                   10725:  foreach my $key (sort(keys(%history))) {
                   10726:    print("\%history{$key} = $history{$key}");
                   10727:  }
                   10728: 
                   10729: Will print out:
1.191     harris41 10730: 
1.394     bowersj2 10731:  %history{1:foo} = bar
                   10732:  %history{1:keys} = foo:timestamp
                   10733:  %history{1:timestamp} = 990455579
                   10734:  %history{2:bar} = foo
                   10735:  %history{2:foo} = notbar
                   10736:  %history{2:keys} = foo:bar:timestamp
                   10737:  %history{2:timestamp} = 990455580
                   10738:  %history{bar} = foo
                   10739:  %history{foo} = notbar
                   10740:  %history{timestamp} = 990455580
                   10741:  %history{version} = 2
                   10742: 
                   10743: Note that the special hash entries C<keys>, C<version> and
                   10744: C<timestamp> were added to the hash. C<version> will be equal to the
                   10745: total number of versions of the data that have been stored. The
                   10746: C<timestamp> attribute will be the UNIX time the hash was
                   10747: stored. C<keys> is available in every historical section to list which
                   10748: keys were added or changed at a specific historical revision of a
                   10749: hash.
                   10750: 
                   10751: B<Warning>: do not store the hash that restore returns directly. This
                   10752: will cause a mess since it will restore the historical keys as if the
                   10753: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10754: 
1.394     bowersj2 10755: Calling convention:
1.191     harris41 10756: 
1.394     bowersj2 10757:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10758:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10759: 
1.394     bowersj2 10760: For more detailed information, see lonnet specific documentation.
1.191     harris41 10761: 
1.394     bowersj2 10762: =head1 RETURN MESSAGES
1.191     harris41 10763: 
1.394     bowersj2 10764: =over 4
1.191     harris41 10765: 
1.394     bowersj2 10766: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10767: 
1.394     bowersj2 10768: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10769: when the connection is brought back up
1.191     harris41 10770: 
1.394     bowersj2 10771: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10772: for later delivery
1.191     harris41 10773: 
1.967     bisitz   10774: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10775: 
1.394     bowersj2 10776: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10777: that was requested
1.191     harris41 10778: 
1.243     albertel 10779: =back
1.191     harris41 10780: 
1.243     albertel 10781: =head1 PUBLIC SUBROUTINES
1.191     harris41 10782: 
1.243     albertel 10783: =head2 Session Environment Functions
1.191     harris41 10784: 
1.243     albertel 10785: =over 4
1.191     harris41 10786: 
1.394     bowersj2 10787: =item * 
                   10788: X<appenv()>
1.949     raeburn  10789: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10790: the user envirnoment file, and will be restored for each access this
1.620     albertel 10791: user makes during this session, also modifies the %env for the current
1.949     raeburn  10792: process. Optional rolesarrayref - if defined contains a reference to an array
                   10793: of roles which are exempt from the restriction on modifying user.role entries 
                   10794: in the user's environment.db and in %env.    
1.191     harris41 10795: 
                   10796: =item *
1.394     bowersj2 10797: X<delenv()>
1.987     raeburn  10798: B<delenv($delthis,$regexp)>: removes all items from the session
                   10799: environment file that begin with $delthis. If the 
                   10800: optional second arg - $regexp - is true, $delthis is treated as a 
                   10801: regular expression, otherwise \Q$delthis\E is used. 
                   10802: The values are also deleted from the current processes %env.
1.191     harris41 10803: 
1.795     albertel 10804: =item * get_env_multiple($name) 
                   10805: 
                   10806: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10807: values may be defined and end up as an array ref.
                   10808: 
                   10809: returns an array of values
                   10810: 
1.243     albertel 10811: =back
                   10812: 
                   10813: =head2 User Information
1.191     harris41 10814: 
1.243     albertel 10815: =over 4
1.191     harris41 10816: 
                   10817: =item *
1.394     bowersj2 10818: X<queryauthenticate()>
                   10819: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10820: authentication scheme
                   10821: 
                   10822: =item *
1.394     bowersj2 10823: X<authenticate()>
1.1073    raeburn  10824: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10825: authenticate user from domain's lib servers (first use the current
                   10826: one). C<$upass> should be the users password.
1.1073    raeburn  10827: $checkdefauth is optional (value is 1 if a check should be made to
                   10828:    authenticate user using default authentication method, and allow
                   10829:    account creation if username does not have account in the domain).
                   10830: $clientcancheckhost is optional (value is 1 if checking whether the
                   10831:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10832: 
                   10833: =item *
1.394     bowersj2 10834: X<homeserver()>
                   10835: B<homeserver($uname,$udom)>: find the server which has
                   10836: the user's directory and files (there must be only one), this caches
                   10837: the answer, and also caches if there is a borken connection.
1.191     harris41 10838: 
                   10839: =item *
1.394     bowersj2 10840: X<idget()>
                   10841: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10842: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10843: username, and only 1 username per ID in a specific domain) (returns
                   10844: hash: id=>name,id=>name)
1.191     harris41 10845: 
                   10846: =item *
1.394     bowersj2 10847: X<idrget()>
                   10848: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10849: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10850: 
                   10851: =item *
1.394     bowersj2 10852: X<idput()>
                   10853: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10854: 
                   10855: =item *
1.394     bowersj2 10856: X<rolesinit()>
                   10857: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10858: 
                   10859: =item *
1.551     albertel 10860: X<getsection()>
                   10861: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10862: course $cname, return section name/number or '' for "not in course"
                   10863: and '-1' for "no section"
                   10864: 
                   10865: =item *
1.394     bowersj2 10866: X<userenvironment()>
                   10867: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10868: passed in @what from the requested user's environment, returns a hash
                   10869: 
1.858     raeburn  10870: =item * 
                   10871: X<userlog_query()>
1.859     albertel 10872: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10873: activity.log file. %filters defines filters applied when parsing the
                   10874: log file. These can be start or end timestamps, or the type of action
                   10875: - log to look for Login or Logout events, check for Checkin or
                   10876: Checkout, role for role selection. The response is in the form
                   10877: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10878: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10879: 
1.243     albertel 10880: =back
                   10881: 
                   10882: =head2 User Roles
                   10883: 
                   10884: =over 4
                   10885: 
                   10886: =item *
                   10887: 
1.810     raeburn  10888: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10889:  F: full access
                   10890:  U,I,K: authentication modes (cxx only)
                   10891:  '': forbidden
                   10892:  1: user needs to choose course
                   10893:  2: browse allowed
1.766     albertel 10894:  A: passphrase authentication needed
1.243     albertel 10895: 
                   10896: =item *
                   10897: 
                   10898: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10899: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10900: and course level
                   10901: 
                   10902: =item *
                   10903: 
1.988     raeburn  10904: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10905: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10906: $type is Course (default) or Community.
1.988     raeburn  10907: If $forcedefault evaluates to true, text returned will be default 
                   10908: text for $type. Otherwise, if this is a course, the text returned 
                   10909: will be a custom name for the role (if defined in the course's 
                   10910: environment).  If no custom name is defined the default is returned.
                   10911:    
1.832     raeburn  10912: =item *
                   10913: 
1.935     raeburn  10914: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10915: All arguments are optional. Returns a hash of a roles, either for
                   10916: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10917: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10918: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10919: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10920: For each key, value is set to colon-separated start and end times for
                   10921: the role.  If no username and domain are specified, will default to
1.934     raeburn  10922: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10923: of role statuses (active, future or previous), roles 
                   10924: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10925: to restrict the list of roles reported. If no array ref is 
                   10926: provided for types, will default to return only active roles.
1.834     albertel 10927: 
1.243     albertel 10928: =back
                   10929: 
                   10930: =head2 User Modification
                   10931: 
                   10932: =over 4
                   10933: 
                   10934: =item *
                   10935: 
1.957     raeburn  10936: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10937: user for the level given by URL.  Optional start and end dates (leave empty
                   10938: string or zero for "no date")
1.191     harris41 10939: 
                   10940: =item *
                   10941: 
1.243     albertel 10942: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10943: change a users, password, possible return values are: ok,
                   10944: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10945: refused
1.191     harris41 10946: 
                   10947: =item *
                   10948: 
1.243     albertel 10949: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10950: 
                   10951: =item *
                   10952: 
1.1058    raeburn  10953: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10954:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10955: 
                   10956: will update user information (firstname,middlename,lastname,generation,
                   10957: permanentemail), and if forceid is true, student/employee ID also.
                   10958: A user's institutional affiliation(s) can also be updated.
                   10959: User information fields will not be overwritten with empty entries 
                   10960: unless the field is included in the $candelete array reference.
                   10961: This array is included when a single user is modified via "Manage Users",
                   10962: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10963: 
                   10964: =item *
                   10965: 
1.286     matthew  10966: modifystudent
                   10967: 
1.957     raeburn  10968: modify a student's enrollment and identification information.
1.286     matthew  10969: The course id is resolved based on the current users environment.  
                   10970: This means the envoking user must be a course coordinator or otherwise
                   10971: associated with a course.
                   10972: 
1.297     matthew  10973: This call is essentially a wrapper for lonnet::modifyuser and
                   10974: lonnet::modify_student_enrollment
1.286     matthew  10975: 
                   10976: Inputs: 
                   10977: 
                   10978: =over 4
                   10979: 
1.957     raeburn  10980: =item B<$udom> Student's loncapa domain
1.286     matthew  10981: 
1.957     raeburn  10982: =item B<$uname> Student's loncapa login name
1.286     matthew  10983: 
1.964     bisitz   10984: =item B<$uid> Student/Employee ID
1.286     matthew  10985: 
1.957     raeburn  10986: =item B<$umode> Student's authentication mode
1.286     matthew  10987: 
1.957     raeburn  10988: =item B<$upass> Student's password
1.286     matthew  10989: 
1.957     raeburn  10990: =item B<$first> Student's first name
1.286     matthew  10991: 
1.957     raeburn  10992: =item B<$middle> Student's middle name
1.286     matthew  10993: 
1.957     raeburn  10994: =item B<$last> Student's last name
1.286     matthew  10995: 
1.957     raeburn  10996: =item B<$gene> Student's generation
1.286     matthew  10997: 
1.957     raeburn  10998: =item B<$usec> Student's section in course
1.286     matthew  10999: 
                   11000: =item B<$end> Unix time of the roles expiration
                   11001: 
                   11002: =item B<$start> Unix time of the roles start date
                   11003: 
                   11004: =item B<$forceid> If defined, allow $uid to be changed
                   11005: 
                   11006: =item B<$desiredhome> server to use as home server for student
                   11007: 
1.957     raeburn  11008: =item B<$email> Student's permanent e-mail address
                   11009: 
                   11010: =item B<$type> Type of enrollment (auto or manual)
                   11011: 
1.963     raeburn  11012: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11013: 
                   11014: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11015: 
1.963     raeburn  11016: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11017: 
1.963     raeburn  11018: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11019: 
1.963     raeburn  11020: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11021: 
1.286     matthew  11022: =back
1.297     matthew  11023: 
                   11024: =item *
                   11025: 
                   11026: modify_student_enrollment
                   11027: 
                   11028: Change a students enrollment status in a class.  The environment variable
                   11029: 'role.request.course' must be defined for this function to proceed.
                   11030: 
                   11031: Inputs:
                   11032: 
                   11033: =over 4
                   11034: 
                   11035: =item $udom, students domain
                   11036: 
                   11037: =item $uname, students name
                   11038: 
                   11039: =item $uid, students user id
                   11040: 
                   11041: =item $first, students first name
                   11042: 
                   11043: =item $middle
                   11044: 
                   11045: =item $last
                   11046: 
                   11047: =item $gene
                   11048: 
                   11049: =item $usec
                   11050: 
                   11051: =item $end
                   11052: 
                   11053: =item $start
                   11054: 
1.957     raeburn  11055: =item $type
                   11056: 
                   11057: =item $locktype
                   11058: 
                   11059: =item $cid
                   11060: 
                   11061: =item $selfenroll
                   11062: 
                   11063: =item $context
                   11064: 
1.297     matthew  11065: =back
                   11066: 
1.191     harris41 11067: 
                   11068: =item *
                   11069: 
1.243     albertel 11070: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11071: custom role; give a custom role to a user for the level given by URL.  Specify
                   11072: name and domain of role author, and role name
1.191     harris41 11073: 
                   11074: =item *
                   11075: 
1.243     albertel 11076: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11077: 
                   11078: =item *
                   11079: 
1.243     albertel 11080: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11081: 
                   11082: =back
                   11083: 
                   11084: =head2 Course Infomation
                   11085: 
                   11086: =over 4
1.191     harris41 11087: 
                   11088: =item *
                   11089: 
1.1118    foxr     11090: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11091: specified course id, including all environment settings for the
                   11092: course, the description of the course will be in the hash under the
                   11093: key 'description'
1.191     harris41 11094: 
1.1118    foxr     11095: $options is an optional parameter that if supplied is a hash reference that controls
                   11096: what how this function works.  It has the following key/values:
                   11097: 
                   11098: =over 4
                   11099: 
                   11100: =item freshen_cache
                   11101: 
                   11102: If defined, and the environment cache for the course is valid, it is 
                   11103: returned in the returned hash.
                   11104: 
                   11105: =item one_time
                   11106: 
                   11107: If defined, the last cache time is set to _now_
                   11108: 
                   11109: =item user
                   11110: 
                   11111: If defined, the supplied username is used instead of the current user.
                   11112: 
                   11113: 
                   11114: =back
                   11115: 
1.191     harris41 11116: =item *
                   11117: 
1.624     albertel 11118: resdata($name,$domain,$type,@which) : request for current parameter
                   11119: setting for a specific $type, where $type is either 'course' or 'user',
                   11120: @what should be a list of parameters to ask about. This routine caches
                   11121: answers for 5 minutes.
1.243     albertel 11122: 
1.877     foxr     11123: =item *
                   11124: 
                   11125: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11126: data base, returning a hash that is keyed by the resource name and has
                   11127: values that are the resource value.  I believe that the timestamps and
                   11128: versions are also returned.
                   11129: 
                   11130: 
1.243     albertel 11131: =back
                   11132: 
                   11133: =head2 Course Modification
                   11134: 
                   11135: =over 4
1.191     harris41 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: writecoursepref($courseid,%prefs) : write preferences (environment
                   11140: database) for a course
1.191     harris41 11141: 
                   11142: =item *
                   11143: 
1.1011    raeburn  11144: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11145: 
                   11146: =item *
                   11147: 
1.1038    raeburn  11148: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11149: 
                   11150: =back
                   11151: 
                   11152: =head2 Resource Subroutines
                   11153: 
                   11154: =over 4
1.191     harris41 11155: 
                   11156: =item *
                   11157: 
1.243     albertel 11158: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11159: 
                   11160: =item *
                   11161: 
1.243     albertel 11162: repcopy($filename) : subscribes to the requested file, and attempts to
                   11163: replicate from the owning library server, Might return
1.607     raeburn  11164: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11165: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11166: resource. Expects the local filesystem pathname
                   11167: (/home/httpd/html/res/....)
                   11168: 
                   11169: =back
                   11170: 
                   11171: =head2 Resource Information
                   11172: 
                   11173: =over 4
1.191     harris41 11174: 
                   11175: =item *
                   11176: 
1.243     albertel 11177: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11178: a vairety of different possible values, $varname should be a request
                   11179: string, and the other parameters can be used to specify who and what
                   11180: one is asking about.
                   11181: 
                   11182: Possible values for $varname are environment.lastname (or other item
                   11183: from the envirnment hash), user.name (or someother aspect about the
                   11184: user), resource.0.maxtries (or some other part and parameter of a
                   11185: resource)
1.204     albertel 11186: 
                   11187: =item *
                   11188: 
1.243     albertel 11189: directcondval($number) : get current value of a condition; reads from a state
                   11190: string
1.204     albertel 11191: 
                   11192: =item *
                   11193: 
1.243     albertel 11194: condval($condidx) : value of condition index based on state
1.204     albertel 11195: 
                   11196: =item *
                   11197: 
1.243     albertel 11198: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11199: resource's metadata, $what should be either a specific key, or either
                   11200: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11201: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11202: 
                   11203: this function automatically caches all requests
1.191     harris41 11204: 
                   11205: =item *
                   11206: 
1.243     albertel 11207: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11208: network of library servers; returns file handle of where SQL and regex results
                   11209: will be stored for query
1.191     harris41 11210: 
                   11211: =item *
                   11212: 
1.243     albertel 11213: symbread($filename) : return symbolic list entry (filename argument optional);
                   11214: returns the data handle
1.191     harris41 11215: 
                   11216: =item *
                   11217: 
1.243     albertel 11218: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11219: a possible symb for the URL in $thisfn, and if is an encryypted
                   11220: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11221: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11222: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11223: 
1.191     harris41 11224: 
                   11225: =item *
                   11226: 
1.243     albertel 11227: symbclean($symb) : removes versions numbers from a symb, returns the
                   11228: cleaned symb
1.191     harris41 11229: 
                   11230: =item *
                   11231: 
1.243     albertel 11232: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11233: course map, user must be in a course for it to work.
1.191     harris41 11234: 
                   11235: =item *
                   11236: 
1.243     albertel 11237: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11242: a random seed, all arguments are optional, if they aren't sent it uses the
                   11243: environment to derive them. Note: if symb isn't sent and it can't get one
                   11244: from &symbread it will use the current time as its return value
1.191     harris41 11245: 
                   11246: =item *
                   11247: 
1.243     albertel 11248: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11249: unfakeable, receipt
1.191     harris41 11250: 
                   11251: =item *
                   11252: 
1.620     albertel 11253: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11254: 
                   11255: =item *
                   11256: 
1.243     albertel 11257: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11258: 
                   11259: =item *
                   11260: 
1.243     albertel 11261: 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 11262: 
                   11263: =item *
                   11264: 
1.243     albertel 11265: 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 11266: 
                   11267: =item *
                   11268: 
1.243     albertel 11269: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11270: 
                   11271: =item *
                   11272: 
1.243     albertel 11273: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11274: forcing spreadsheet to reevaluate the resource scores next time.
                   11275: 
                   11276: =back
                   11277: 
                   11278: =head2 Storing/Retreiving Data
                   11279: 
                   11280: =over 4
1.191     harris41 11281: 
                   11282: =item *
                   11283: 
1.243     albertel 11284: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11285: for this url; hashref needs to be given and should be a \%hashname; the
                   11286: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11287: be derived from the env
1.191     harris41 11288: 
                   11289: =item *
                   11290: 
1.243     albertel 11291: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11292: uses critical subroutine
1.191     harris41 11293: 
                   11294: =item *
                   11295: 
1.243     albertel 11296: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11297: all args are optional
1.191     harris41 11298: 
                   11299: =item *
                   11300: 
1.717     albertel 11301: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11302: dumps the complete (or key matching regexp) namespace into a hash
                   11303: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11304: normally &store()ed into
                   11305: 
                   11306: $range should be either an integer '100' (give me the first 100
                   11307:                                            matching records)
                   11308:               or be  two integers sperated by a - with no spaces
                   11309:                  '30-50' (give me the 30th through the 50th matching
                   11310:                           records)
                   11311: 
                   11312: 
                   11313: =item *
                   11314: 
                   11315: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11316: replaces a &store() version of data with a replacement set of data
                   11317: for a particular resource in a namespace passed in the $storehash hash 
                   11318: reference
                   11319: 
                   11320: =item *
                   11321: 
1.243     albertel 11322: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11323: works very similar to store/cstore, but all data is stored in a
                   11324: temporary location and can be reset using tmpreset, $storehash should
                   11325: be a hash reference, returns nothing on success
1.191     harris41 11326: 
                   11327: =item *
                   11328: 
1.243     albertel 11329: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11330: similar to restore, but all data is stored in a temporary location and
                   11331: can be reset using tmpreset. Returns a hash of values on success,
                   11332: error string otherwise.
1.191     harris41 11333: 
                   11334: =item *
                   11335: 
1.243     albertel 11336: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11337: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11338: 
                   11339: =item *
                   11340: 
1.243     albertel 11341: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11342: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11343: 
                   11344: =item *
                   11345: 
1.243     albertel 11346: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11347: namesp ($udom and $uname are optional)
1.191     harris41 11348: 
                   11349: =item *
                   11350: 
1.702     albertel 11351: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11352: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11353: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11354: 
1.702     albertel 11355: $range should be either an integer '100' (give me the first 100
                   11356:                                            matching records)
                   11357:               or be  two integers sperated by a - with no spaces
                   11358:                  '30-50' (give me the 30th through the 50th matching
                   11359:                           records)
1.449     matthew  11360: =item *
                   11361: 
                   11362: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11363: $store can be a scalar, an array reference, or if the amount to be 
                   11364: incremented is > 1, a hash reference.
                   11365: 
                   11366: ($udom and $uname are optional)
1.191     harris41 11367: 
                   11368: =item *
                   11369: 
1.243     albertel 11370: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11371: ($udom and $uname are optional)
1.191     harris41 11372: 
                   11373: =item *
                   11374: 
1.243     albertel 11375: cput($namespace,$storehash,$udom,$uname) : critical put
                   11376: ($udom and $uname are optional)
1.191     harris41 11377: 
                   11378: =item *
                   11379: 
1.748     albertel 11380: newput($namespace,$storehash,$udom,$uname) :
                   11381: 
                   11382: Attempts to store the items in the $storehash, but only if they don't
                   11383: currently exist, if this succeeds you can be certain that you have 
                   11384: successfully created a new key value pair in the $namespace db.
                   11385: 
                   11386: 
                   11387: Args:
                   11388:  $namespace: name of database to store values to
                   11389:  $storehash: hashref to store to the db
                   11390:  $udom: (optional) domain of user containing the db
                   11391:  $uname: (optional) name of user caontaining the db
                   11392: 
                   11393: Returns:
                   11394:  'ok' -> succeeded in storing all keys of $storehash
                   11395:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11396:                         least <key> already existed in the db (other
                   11397:                         requested keys may also already exist)
1.967     bisitz   11398:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11399:  'con_lost' -> unable to contact request server
                   11400:  'refused' -> action was not allowed by remote machine
                   11401: 
                   11402: 
                   11403: =item *
                   11404: 
1.243     albertel 11405: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11406: reference filled in from namesp (encrypts the return communication)
                   11407: ($udom and $uname are optional)
1.191     harris41 11408: 
                   11409: =item *
                   11410: 
1.243     albertel 11411: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11412: critical subroutine
                   11413: 
1.806     raeburn  11414: =item *
                   11415: 
1.860     raeburn  11416: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11417: array reference filled in from namespace found in domain level on either
                   11418: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11419: 
                   11420: =item *
                   11421: 
1.860     raeburn  11422: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11423: domain level either on specified domain server ($uhome) or primary domain 
                   11424: server ($udom and $uhome are optional)
1.806     raeburn  11425: 
1.943     raeburn  11426: =item * 
                   11427: 
                   11428: get_domain_defaults($target_domain) : returns hash with defaults for
                   11429: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11430: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11431: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11432: Values are retrieved from cache (if current), or from domain's configuration.db
                   11433: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11434: or lonTabs/domain.tab. 
                   11435: 
                   11436: %domdefaults = &get_auth_defaults($target_domain);
                   11437: 
1.243     albertel 11438: =back
                   11439: 
                   11440: =head2 Network Status Functions
                   11441: 
                   11442: =over 4
1.191     harris41 11443: 
                   11444: =item *
                   11445: 
                   11446: dirlist($uri) : return directory list based on URI
                   11447: 
                   11448: =item *
                   11449: 
1.243     albertel 11450: spareserver() : find server with least workload from spare.tab
                   11451: 
1.986     foxr     11452: 
                   11453: =item *
                   11454: 
                   11455: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11456: if there is no corresponding loncapa host.
                   11457: 
1.243     albertel 11458: =back
                   11459: 
1.986     foxr     11460: 
1.243     albertel 11461: =head2 Apache Request
                   11462: 
                   11463: =over 4
1.191     harris41 11464: 
                   11465: =item *
                   11466: 
1.243     albertel 11467: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11468: localhost, posts hash
                   11469: 
                   11470: =back
                   11471: 
                   11472: =head2 Data to String to Data
                   11473: 
                   11474: =over 4
1.191     harris41 11475: 
                   11476: =item *
                   11477: 
1.243     albertel 11478: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11479: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11480: 
                   11481: =item *
                   11482: 
1.243     albertel 11483: hashref2str($hashref) : convert a hashref into a string complete with
                   11484: escaping and '=' and '&' separators, supports elements that are
                   11485: arrayrefs and hashrefs
1.191     harris41 11486: 
                   11487: =item *
                   11488: 
1.243     albertel 11489: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11490: with escaping and '&' separators, supports elements that are arrayrefs
                   11491: and hashrefs
1.191     harris41 11492: 
                   11493: =item *
                   11494: 
1.243     albertel 11495: str2hash($string) : convert string to hash using unescaping and
                   11496: splitting on '=' and '&', supports elements that are arrayrefs and
                   11497: hashrefs
1.191     harris41 11498: 
                   11499: =item *
                   11500: 
1.243     albertel 11501: str2array($string) : convert string to hash using unescaping and
                   11502: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11503: 
                   11504: =back
                   11505: 
                   11506: =head2 Logging Routines
                   11507: 
                   11508: 
                   11509: These routines allow one to make log messages in the lonnet.log and
                   11510: lonnet.perm logfiles.
1.191     harris41 11511: 
1.1119    foxr     11512: =over 4
                   11513: 
1.191     harris41 11514: =item *
                   11515: 
1.243     albertel 11516: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11517: 
                   11518: =item *
                   11519: 
1.243     albertel 11520: logthis() : append message to the normal lonnet.log file, it gets
                   11521: preiodically rolled over and deleted.
1.191     harris41 11522: 
                   11523: =item *
                   11524: 
1.243     albertel 11525: logperm() : append a permanent message to lonnet.perm.log, this log
                   11526: file never gets deleted by any automated portion of the system, only
                   11527: messages of critical importance should go in here.
                   11528: 
1.1119    foxr     11529: 
1.243     albertel 11530: =back
                   11531: 
                   11532: =head2 General File Helper Routines
                   11533: 
                   11534: =over 4
1.191     harris41 11535: 
                   11536: =item *
                   11537: 
1.481     raeburn  11538: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11539: (a) files in /uploaded
                   11540:   (i) If a local copy of the file exists - 
                   11541:       compares modification date of local copy with last-modified date for 
                   11542:       definitive version stored on home server for course. If local copy is 
                   11543:       stale, requests a new version from the home server and stores it. 
                   11544:       If the original has been removed from the home server, then local copy 
                   11545:       is unlinked.
                   11546:   (ii) If local copy does not exist -
                   11547:       requests the file from the home server and stores it. 
                   11548:   
                   11549:   If $caller is 'uploadrep':  
                   11550:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11551:     for request for files originally uploaded via DOCS. 
                   11552:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11553:   
                   11554:   Otherwise:
                   11555:      This indicates a call from the content generation phase of the request.
                   11556:      -  returns the entire contents of the file or -1.
                   11557:      
                   11558: (b) files in /res
                   11559:    - returns the entire contents of a file or -1; 
                   11560:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11561: 
1.712     albertel 11562: 
                   11563: =item *
                   11564: 
                   11565: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11566:                   reference
                   11567: 
                   11568: returns either a stat() list of data about the file or an empty list
                   11569: if the file doesn't exist or couldn't find out about it (connection
                   11570: problems or user unknown)
                   11571: 
1.191     harris41 11572: =item *
                   11573: 
1.243     albertel 11574: filelocation($dir,$file) : returns file system location of a file
                   11575: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11576: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11577: and a file of ../bob will become /a/bob)
1.191     harris41 11578: 
                   11579: =item *
                   11580: 
                   11581: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11582: filelocation except for hrefs
                   11583: 
                   11584: =item *
                   11585: 
                   11586: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11587: 
1.243     albertel 11588: =back
                   11589: 
1.608     albertel 11590: =head2 Usererfile file routines (/uploaded*)
                   11591: 
                   11592: =over 4
                   11593: 
                   11594: =item *
                   11595: 
                   11596: userfileupload(): main rotine for putting a file in a user or course's
                   11597:                   filespace, arguments are,
                   11598: 
1.620     albertel 11599:  formname - required - this is the name of the element in $env where the
1.608     albertel 11600:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11601:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11602:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11603:  context - if coursedoc, store the file in the course of the active role
                   11604:              of the current user; 
                   11605:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11606:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11607:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11608:          if undefined, it will be placed in "unknown"
                   11609: 
                   11610:  (This routine calls clean_filename() to remove any dangerous
                   11611:  characters from the filename, and then calls finuserfileupload() to
                   11612:  complete the transaction)
                   11613: 
                   11614:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11615:  and /adm/notfound.html if unsuccessful
                   11616: 
                   11617: =item *
                   11618: 
                   11619: clean_filename(): routine for cleaing a filename up for storage in
                   11620:                  userfile space, argument is:
                   11621: 
                   11622:  filename - proposed filename
                   11623: 
                   11624: returns: the new clean filename
                   11625: 
                   11626: =item *
                   11627: 
1.1090    raeburn  11628: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11629: userspace, probably shouldn't be called directly
                   11630: 
                   11631:   docuname: username or courseid of destination for the file
                   11632:   docudom: domain of user/course of destination for the file
                   11633:   formname: same as for userfileupload()
1.1090    raeburn  11634:   fname: filename (including subdirectories) for the file
                   11635:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11636:   allfiles: reference to hash used to store objects found by parser
                   11637:   codebase: reference to hash used for codebases of java objects found by parser
                   11638:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11639:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11640:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11641:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11642:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11643:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11644:   mimetype: reference to scalar to accommodate mime type determined
                   11645:             from File::MMagic if $parser = parse.
1.608     albertel 11646: 
                   11647:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11648:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11649:  was 'overwrite').
                   11650:  
1.608     albertel 11651: 
                   11652: =item *
                   11653: 
                   11654: renameuserfile(): renames an existing userfile to a new name
                   11655: 
                   11656:   Args:
                   11657:    docuname: username or courseid of destination for the file
                   11658:    docudom: domain of user/course of destination for the file
                   11659:    old: current file name (including any subdirs under userfiles)
                   11660:    new: desired file name (including any subdirs under userfiles)
                   11661: 
                   11662: =item *
                   11663: 
                   11664: mkdiruserfile(): creates a directory is a userfiles dir
                   11665: 
                   11666:   Args:
                   11667:    docuname: username or courseid of destination for the file
                   11668:    docudom: domain of user/course of destination for the file
                   11669:    dir: dir to create (including any subdirs under userfiles)
                   11670: 
                   11671: =item *
                   11672: 
                   11673: removeuserfile(): removes a file that exists in userfiles
                   11674: 
                   11675:   Args:
                   11676:    docuname: username or courseid of destination for the file
                   11677:    docudom: domain of user/course of destination for the file
                   11678:    fname: filname to delete (including any subdirs under userfiles)
                   11679: 
                   11680: =item *
                   11681: 
                   11682: removeuploadedurl(): convience function for removeuserfile()
                   11683: 
                   11684:   Args:
                   11685:    url:  a full /uploaded/... url to delete
                   11686: 
1.747     albertel 11687: =item * 
                   11688: 
                   11689: get_portfile_permissions():
                   11690:   Args:
                   11691:     domain: domain of user or course contain the portfolio files
                   11692:     user: name of user or num of course contain the portfolio files
                   11693:   Returns:
                   11694:     hashref of a dump of the proper file_permissions.db
                   11695:    
                   11696: 
                   11697: =item * 
                   11698: 
                   11699: get_access_controls():
                   11700: 
                   11701: Args:
                   11702:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11703:   group: (optional) the group you want the files associated with
                   11704:   file: (optional) the file you want access info on
                   11705: 
                   11706: Returns:
1.749     raeburn  11707:     a hash (keys are file names) of hashes containing
                   11708:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11709:         values are XML containing access control settings (see below) 
1.747     albertel 11710: 
                   11711: Internal notes:
                   11712: 
1.749     raeburn  11713:  access controls are stored in file_permissions.db as key=value pairs.
                   11714:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11715:         where scope -> public,guest,course,group,domains or users.
                   11716:               end -> UNIX time for end of access (0 -> no end date)
                   11717:               start -> UNIX time for start of access
                   11718: 
                   11719:     value -> XML description of access control
                   11720:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11721:             <start></start>
                   11722:             <end></end>
                   11723: 
                   11724:             <password></password>  for scope type = guest
                   11725: 
                   11726:             <domain></domain>     for scope type = course or group
                   11727:             <number></number>
                   11728:             <roles id="">
                   11729:              <role></role>
                   11730:              <access></access>
                   11731:              <section></section>
                   11732:              <group></group>
                   11733:             </roles>
                   11734: 
                   11735:             <dom></dom>         for scope type = domains
                   11736: 
                   11737:             <users>             for scope type = users
                   11738:              <user>
                   11739:               <uname></uname>
                   11740:               <udom></udom>
                   11741:              </user>
                   11742:             </users>
                   11743:            </scope> 
                   11744:               
                   11745:  Access data is also aggregated for each file in an additional key=value pair:
                   11746:  key -> path to file/file_name\0accesscontrol 
                   11747:  value -> reference to hash
                   11748:           hash contains key = value pairs
                   11749:           where key = uniqueID:scope_end_start
                   11750:                 value = UNIX time record was last updated
                   11751: 
                   11752:           Used to improve speed of look-ups of access controls for each file.  
                   11753:  
                   11754:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11755: 
                   11756: modify_access_controls():
                   11757: 
                   11758: Modifies access controls for a portfolio file
                   11759: Args
                   11760: 1. file name
                   11761: 2. reference to hash of required changes,
                   11762: 3. domain
                   11763: 4. username
                   11764:   where domain,username are the domain of the portfolio owner 
                   11765:   (either a user or a course) 
                   11766: 
                   11767: Returns:
                   11768: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11769: 2. result of deletions ('ok' or 'error', with error message).
                   11770: 3. reference to hash of any new or updated access controls.
                   11771: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11772:    key = integer (inbound ID)
                   11773:    value = uniqueID  
1.747     albertel 11774: 
1.608     albertel 11775: =back
                   11776: 
1.243     albertel 11777: =head2 HTTP Helper Routines
                   11778: 
                   11779: =over 4
                   11780: 
1.191     harris41 11781: =item *
                   11782: 
                   11783: escape() : unpack non-word characters into CGI-compatible hex codes
                   11784: 
                   11785: =item *
                   11786: 
                   11787: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11788: 
1.243     albertel 11789: =back
                   11790: 
                   11791: =head1 PRIVATE SUBROUTINES
                   11792: 
                   11793: =head2 Underlying communication routines (Shouldn't call)
                   11794: 
                   11795: =over 4
                   11796: 
                   11797: =item *
                   11798: 
                   11799: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11800: 
                   11801: =item *
                   11802: 
                   11803: reply() : uses subreply to send a message to remote machine, logs all failures
                   11804: 
                   11805: =item *
                   11806: 
                   11807: critical() : passes a critical message to another server; if cannot
                   11808: get through then place message in connection buffer directory and
                   11809: returns con_delayed, if incapable of saving message, returns
                   11810: con_failed
                   11811: 
                   11812: =item *
                   11813: 
                   11814: reconlonc() : tries to reconnect lonc client processes.
                   11815: 
                   11816: =back
                   11817: 
                   11818: =head2 Resource Access Logging
                   11819: 
                   11820: =over 4
                   11821: 
                   11822: =item *
                   11823: 
                   11824: flushcourselogs() : flush (save) buffer logs and access logs
                   11825: 
                   11826: =item *
                   11827: 
                   11828: courselog($what) : save message for course in hash
                   11829: 
                   11830: =item *
                   11831: 
                   11832: courseacclog($what) : save message for course using &courselog().  Perform
                   11833: special processing for specific resource types (problems, exams, quizzes, etc).
                   11834: 
1.191     harris41 11835: =item *
                   11836: 
                   11837: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11838: as a PerlChildExitHandler
1.243     albertel 11839: 
                   11840: =back
                   11841: 
                   11842: =head2 Other
                   11843: 
                   11844: =over 4
                   11845: 
                   11846: =item *
                   11847: 
                   11848: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11849: 
                   11850: =back
                   11851: 
                   11852: =cut
1.877     foxr     11853: 

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