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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1124  ! raeburn     4: # $Id: lonnet.pm,v 1.1123 2011/08/01 22:13:49 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.1124  ! raeburn   347: sub remote_devalidate_cache {
        !           348:     my ($lonhost,$name,$id) = @_;
        !           349:     my $response = &reply('devalidatecache',&escape($name).':'.&escape($id),$lonhost);
        !           350:     return $response;
        !           351: }
        !           352: 
1.1       albertel  353: # -------------------------------------------------- Non-critical communication
                    354: sub subreply {
                    355:     my ($cmd,$server)=@_;
1.838     albertel  356:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      357:     #
                    358:     #  With loncnew process trimming, there's a timing hole between lonc server
                    359:     #  process exit and the master server picking up the listen on the AF_UNIX
                    360:     #  socket.  In that time interval, a lock file will exist:
                    361: 
                    362:     my $lockfile=$peerfile.".lock";
                    363:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    364: 	sleep(1);
                    365:     }
                    366:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      367:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      368:     #
1.550     foxr      369:     #   We'll give the connection a few tries before abandoning it.  If
                    370:     #   connection is not possible, we'll con_lost back to the client.
                    371:     #   
                    372:     my $client;
                    373:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    374: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    375: 				      Type    => SOCK_STREAM,
                    376: 				      Timeout => 10);
1.869     albertel  377: 	if ($client) {
1.550     foxr      378: 	    last;		# Connected!
1.850     albertel  379: 	} else {
1.853     albertel  380: 	    &create_connection(&hostname($server),$server);
1.550     foxr      381: 	}
1.850     albertel  382:         sleep(1);		# Try again later if failed connection.
1.550     foxr      383:     }
                    384:     my $answer;
                    385:     if ($client) {
1.704     albertel  386: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      387: 	$answer=<$client>;
                    388: 	if (!$answer) { $answer="con_lost"; }
                    389: 	chomp($answer);
                    390:     } else {
                    391: 	$answer = 'con_lost';	# Failed connection.
                    392:     }
1.1       albertel  393:     return $answer;
                    394: }
                    395: 
                    396: sub reply {
                    397:     my ($cmd,$server)=@_;
1.838     albertel  398:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  399:     my $answer=subreply($cmd,$server);
1.65      www       400:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  401:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       402:                 " $cmd to $server returned $answer</font>");
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: # ----------------------------------------------------------- Send USR1 to lonc
                    408: 
                    409: sub reconlonc {
1.891     albertel  410:     my ($lonid) = @_;
                    411:     my $hostname = &hostname($lonid);
                    412:     if ($lonid) {
                    413: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    414: 	if ($hostname && -e $peerfile) {
                    415: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    416: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    417: 					     Type    => SOCK_STREAM,
                    418: 					     Timeout => 10);
                    419: 	    if ($client) {
                    420: 		print $client ("reset_retries\n");
                    421: 		my $answer=<$client>;
                    422: 		#reset just this one.
                    423: 	    }
                    424: 	}
                    425: 	return;
                    426:     }
                    427: 
1.836     www       428:     &logthis("Trying to reconnect lonc");
1.1       albertel  429:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  430:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  431: 	my $loncpid=<$fh>;
                    432:         chomp($loncpid);
                    433:         if (kill 0 => $loncpid) {
                    434: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    435:             kill USR1 => $loncpid;
                    436:             sleep 1;
1.836     www       437:          } else {
1.12      www       438: 	    &logthis(
1.672     albertel  439:                "<font color=\"blue\">WARNING:".
1.12      www       440:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  441:         }
                    442:     } else {
1.836     www       443: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  444:     }
                    445: }
                    446: 
                    447: # ------------------------------------------------------ Critical communication
1.12      www       448: 
1.1       albertel  449: sub critical {
                    450:     my ($cmd,$server)=@_;
1.838     albertel  451:     unless (&hostname($server)) {
1.672     albertel  452:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       453:                " Critical message to unknown server ($server)</font>");
                    454:         return 'no_such_host';
                    455:     }
1.1       albertel  456:     my $answer=reply($cmd,$server);
                    457:     if ($answer eq 'con_lost') {
                    458: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  459: 	my $answer=reply($cmd,$server);
1.1       albertel  460:         if ($answer eq 'con_lost') {
                    461:             my $now=time;
                    462:             my $middlename=$cmd;
1.5       www       463:             $middlename=substr($middlename,0,16);
1.1       albertel  464:             $middlename=~s/\W//g;
                    465:             my $dfilename=
1.305     www       466:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    467:             $dumpcount++;
1.1       albertel  468:             {
1.448     albertel  469: 		my $dfh;
                    470: 		if (open($dfh,">$dfilename")) {
                    471: 		    print $dfh "$cmd\n"; 
                    472: 		    close($dfh);
                    473: 		}
1.1       albertel  474:             }
                    475:             sleep 2;
                    476:             my $wcmd='';
                    477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,"<$dfilename")) {
                    480: 		    $wcmd=<$dfh>; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             chomp($wcmd);
1.7       www       485:             if ($wcmd eq $cmd) {
1.672     albertel  486: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       487:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  488:                 &logperm("D:$server:$cmd");
                    489: 	        return 'con_delayed';
                    490:             } else {
1.672     albertel  491:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       492:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  493:                 &logperm("F:$server:$cmd");
                    494:                 return 'con_failed';
                    495:             }
                    496:         }
                    497:     }
                    498:     return $answer;
1.405     albertel  499: }
                    500: 
1.755     albertel  501: # ------------------------------------------- check if return value is an error
                    502: 
                    503: sub error {
                    504:     my ($result) = @_;
1.756     albertel  505:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  506: 	if ($2 == 2) { return undef; }
                    507: 	return $1;
                    508:     }
                    509:     return undef;
                    510: }
                    511: 
1.783     albertel  512: sub convert_and_load_session_env {
                    513:     my ($lonidsdir,$handle)=@_;
                    514:     my @profile;
                    515:     {
1.917     albertel  516: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    517: 	if (!$opened) {
1.915     albertel  518: 	    return 0;
                    519: 	}
1.783     albertel  520: 	flock($idf,LOCK_SH);
                    521: 	@profile=<$idf>;
                    522: 	close($idf);
                    523:     }
                    524:     my %temp_env;
                    525:     foreach my $line (@profile) {
1.786     albertel  526: 	if ($line !~ m/=/) {
                    527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	chomp($line);
                    530: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    531: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    532:     }
                    533:     unlink("$lonidsdir/$handle.id");
                    534:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    535: 	    0640)) {
                    536: 	%disk_env = %temp_env;
                    537: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    538: 	untie(%disk_env);
                    539:     }
1.786     albertel  540:     return 1;
1.783     albertel  541: }
                    542: 
1.374     www       543: # ------------------------------------------- Transfer profile into environment
1.780     albertel  544: my $env_loaded;
                    545: sub transfer_profile_to_env {
1.788     albertel  546:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    547:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       548: 
1.720     albertel  549:     if (!defined($lonidsdir)) {
                    550: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    551:     }
                    552:     if (!defined($handle)) {
                    553:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    554:     }
                    555: 
1.786     albertel  556:     my $convert;
                    557:     {
1.917     albertel  558:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    559: 	if (!$opened) {
1.915     albertel  560: 	    return;
                    561: 	}
1.786     albertel  562: 	flock($idf,LOCK_SH);
                    563: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    564: 		&GDBM_READER(),0640)) {
                    565: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    566: 	    untie(%disk_env);
                    567: 	} else {
                    568: 	    $convert = 1;
                    569: 	}
                    570:     }
                    571:     if ($convert) {
                    572: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    573: 	    &logthis("Failed to load session, or convert session.");
                    574: 	}
1.374     www       575:     }
1.783     albertel  576: 
1.786     albertel  577:     my %remove;
1.783     albertel  578:     while ( my $envname = each(%env) ) {
1.433     matthew   579:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    580:             if ($time < time-300) {
1.783     albertel  581:                 $remove{$key}++;
1.433     matthew   582:             }
                    583:         }
                    584:     }
1.783     albertel  585: 
1.619     albertel  586:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  587:     $env_loaded=1;
1.783     albertel  588:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   589:         &delenv($expired_key);
1.374     www       590:     }
1.1       albertel  591: }
                    592: 
1.916     albertel  593: # ---------------------------------------------------- Check for valid session 
                    594: sub check_for_valid_session {
                    595:     my ($r) = @_;
                    596:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    597:     my $lonid=$cookies{'lonID'};
                    598:     return undef if (!$lonid);
                    599: 
                    600:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    601:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    602:     return undef if (!-e "$lonidsdir/$handle.id");
                    603: 
1.917     albertel  604:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    605:     return undef if (!$opened);
1.916     albertel  606: 
                    607:     flock($idf,LOCK_SH);
                    608:     my %disk_env;
                    609:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    610: 	    &GDBM_READER(),0640)) {
                    611: 	return undef;	
                    612:     }
                    613: 
                    614:     if (!defined($disk_env{'user.name'})
                    615: 	|| !defined($disk_env{'user.domain'})) {
                    616: 	return undef;
                    617:     }
                    618:     return $handle;
                    619: }
                    620: 
1.830     albertel  621: sub timed_flock {
                    622:     my ($file,$lock_type) = @_;
                    623:     my $failed=0;
                    624:     eval {
                    625: 	local $SIG{__DIE__}='DEFAULT';
                    626: 	local $SIG{ALRM}=sub {
                    627: 	    $failed=1;
                    628: 	    die("failed lock");
                    629: 	};
                    630: 	alarm(13);
                    631: 	flock($file,$lock_type);
                    632: 	alarm(0);
                    633:     };
                    634:     if ($failed) {
                    635: 	return undef;
                    636:     } else {
                    637: 	return 1;
                    638:     }
                    639: }
                    640: 
1.5       www       641: # ---------------------------------------------------------- Append Environment
                    642: 
                    643: sub appenv {
1.949     raeburn   644:     my ($newenv,$roles) = @_;
                    645:     if (ref($newenv) eq 'HASH') {
                    646:         foreach my $key (keys(%{$newenv})) {
                    647:             my $refused = 0;
                    648: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    649:                 $refused = 1;
                    650:                 if (ref($roles) eq 'ARRAY') {
                    651:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    652:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    653:                         $refused = 0;
                    654:                     }
                    655:                 }
                    656:             }
                    657:             if ($refused) {
                    658:                 &logthis("<font color=\"blue\">WARNING: ".
                    659:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    660:                          .'</font>');
                    661: 	        delete($newenv->{$key});
                    662:             } else {
                    663:                 $env{$key}=$newenv->{$key};
                    664:             }
                    665:         }
                    666:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    667:         if ($opened
                    668: 	    && &timed_flock($env_file,LOCK_EX)
                    669: 	    &&
                    670: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    671: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    672: 	    while (my ($key,$value) = each(%{$newenv})) {
                    673: 	        $disk_env{$key} = $value;
                    674: 	    }
                    675: 	    untie(%disk_env);
1.35      www       676:         }
1.191     harris41  677:     }
1.56      www       678:     return 'ok';
                    679: }
                    680: # ----------------------------------------------------- Delete from Environment
                    681: 
                    682: sub delenv {
1.1104    raeburn   683:     my ($delthis,$regexp,$roles) = @_;
                    684:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    685:         my $refused = 1;
                    686:         if (ref($roles) eq 'ARRAY') {
                    687:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    688:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    689:                 $refused = 0;
                    690:             }
                    691:         }
                    692:         if ($refused) {
                    693:             &logthis("<font color=\"blue\">WARNING: ".
                    694:                      "Attempt to delete from environment ".$delthis);
                    695:             return 'error';
                    696:         }
1.56      www       697:     }
1.917     albertel  698:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    699:     if ($opened
1.915     albertel  700: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  701: 	&&
                    702: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    703: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  704: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   705: 	    if ($regexp) {
                    706:                 if ($key=~/^$delthis/) {
                    707:                     delete($env{$key});
                    708:                     delete($disk_env{$key});
                    709:                 } 
                    710:             } else {
                    711:                 if ($key=~/^\Q$delthis\E/) {
                    712: 		    delete($env{$key});
                    713: 		    delete($disk_env{$key});
                    714: 	        }
                    715:             }
1.448     albertel  716: 	}
1.783     albertel  717: 	untie(%disk_env);
1.5       www       718:     }
                    719:     return 'ok';
1.369     albertel  720: }
                    721: 
1.790     albertel  722: sub get_env_multiple {
                    723:     my ($name) = @_;
                    724:     my @values;
                    725:     if (defined($env{$name})) {
                    726:         # exists is it an array
                    727:         if (ref($env{$name})) {
                    728:             @values=@{ $env{$name} };
                    729:         } else {
                    730:             $values[0]=$env{$name};
                    731:         }
                    732:     }
                    733:     return(@values);
                    734: }
                    735: 
1.958     www       736: # ------------------------------------------------------------------- Locking
                    737: 
                    738: sub set_lock {
                    739:     my ($text)=@_;
                    740:     $locknum++;
                    741:     my $id=$$.'-'.$locknum;
                    742:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    743:              'session.lock.'.$id => $text});
                    744:     return $id;
                    745: }
                    746: 
                    747: sub get_locks {
                    748:     my $num=0;
                    749:     my %texts=();
                    750:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    751:        if ($lock=~/\w/) {
                    752:           $num++;
                    753:           $texts{$lock}=$env{'session.lock.'.$lock};
                    754:        }
                    755:    }
                    756:    return ($num,%texts);
                    757: }
                    758: 
                    759: sub remove_lock {
                    760:     my ($id)=@_;
                    761:     my $newlocks='';
                    762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    763:        if (($lock=~/\w/) && ($lock ne $id)) {
                    764:           $newlocks.=','.$lock;
                    765:        }
                    766:     }
                    767:     &appenv({'session.locks' => $newlocks});
                    768:     &delenv('session.lock.'.$id);
                    769: }
                    770: 
                    771: sub remove_all_locks {
                    772:     my $activelocks=$env{'session.locks'};
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           &remove_lock($lock);
                    776:        }
                    777:     }
                    778: }
                    779: 
                    780: 
1.369     albertel  781: # ------------------------------------------ Find out current server userload
                    782: sub userload {
                    783:     my $numusers=0;
                    784:     {
                    785: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    786: 	my $filename;
                    787: 	my $curtime=time;
                    788: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  789: 	    next if ($filename eq '.' || $filename eq '..');
                    790: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  791: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  792: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  793: 	}
                    794: 	closedir(LONIDS);
                    795:     }
                    796:     my $userloadpercent=0;
                    797:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    798:     if ($maxuserload) {
1.371     albertel  799: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  800:     }
1.372     albertel  801:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  802:     return $userloadpercent;
1.283     www       803: }
                    804: 
1.1       albertel  805: # ------------------------------ Find server with least workload from spare.tab
1.11      www       806: 
1.1       albertel  807: sub spareserver {
1.1083    raeburn   808:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  809:     my $spare_server;
1.370     albertel  810:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  811:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    812:                                                      :  $userloadpercent;
1.1083    raeburn   813:     my ($uint_dom,$remotesessions);
                    814:     if (($udom ne '') && (&domain($udom) ne '')) {
                    815:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    816:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    817:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    818:         $remotesessions = $udomdefaults{'remotesessions'};
                    819:     }
1.1123    raeburn   820:     my $spareshash = &this_host_spares($udom);
                    821:     if (ref($spareshash) eq 'HASH') {
                    822:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    823:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    824:                 if ($uint_dom) {
                    825:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    826:                                                  $try_server));
                    827:                 }
                    828: 	        ($spare_server, $lowest_load) =
                    829: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    830:             }
1.1083    raeburn   831:         }
1.784     albertel  832: 
1.1123    raeburn   833:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    834: 
                    835:         if (!$found_server) {
                    836:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    837: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    838:                     if ($uint_dom) {
                    839:                         next unless (&spare_can_host($udom,$uint_dom,
                    840:                                                      $remotesessions,$try_server));
                    841:                     }
                    842: 	            ($spare_server, $lowest_load) =
                    843: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    844:                 }
                    845: 	    }
                    846:         }
1.784     albertel  847:     }
                    848: 
                    849:     if (!$want_server_name) {
1.968     raeburn   850:         my $protocol = 'http';
                    851:         if ($protocol{$spare_server} eq 'https') {
                    852:             $protocol = $protocol{$spare_server};
                    853:         }
1.1001    raeburn   854:         if (defined($spare_server)) {
                    855:             my $hostname = &hostname($spare_server);
1.1083    raeburn   856:             if (defined($hostname)) {
1.1001    raeburn   857: 	        $spare_server = $protocol.'://'.$hostname;
                    858:             }
                    859:         }
1.784     albertel  860:     }
                    861:     return $spare_server;
                    862: }
                    863: 
                    864: sub compare_server_load {
                    865:     my ($try_server, $spare_server, $lowest_load) = @_;
                    866: 
                    867:     my $loadans     = &reply('load',    $try_server);
                    868:     my $userloadans = &reply('userload',$try_server);
                    869: 
                    870:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   871: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  872:     }
                    873: 
                    874:     my $load;
                    875:     if ($loadans =~ /\d/) {
                    876: 	if ($userloadans =~ /\d/) {
                    877: 	    #both are numbers, pick the bigger one
                    878: 	    $load = ($loadans > $userloadans) ? $loadans 
                    879: 		                              : $userloadans;
1.411     albertel  880: 	} else {
1.784     albertel  881: 	    $load = $loadans;
1.411     albertel  882: 	}
1.784     albertel  883:     } else {
                    884: 	$load = $userloadans;
                    885:     }
                    886: 
                    887:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    888: 	$spare_server = $try_server;
                    889: 	$lowest_load  = $load;
1.370     albertel  890:     }
1.784     albertel  891:     return ($spare_server,$lowest_load);
1.202     matthew   892: }
1.914     albertel  893: 
                    894: # --------------------------- ask offload servers if user already has a session
                    895: sub find_existing_session {
                    896:     my ($udom,$uname) = @_;
1.1123    raeburn   897:     my $spareshash = &this_host_spares($udom);
                    898:     if (ref($spareshash) eq 'HASH') {
                    899:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    900:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    901:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    902:             }
                    903:         }
                    904:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    905:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    906:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    907:             }
                    908:         }
1.914     albertel  909:     }
                    910:     return;
                    911: }
                    912: 
                    913: # -------------------------------- ask if server already has a session for user
                    914: sub has_user_session {
                    915:     my ($lonid,$udom,$uname) = @_;
                    916:     my $result = &reply(join(':','userhassession',
                    917: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    918:     return 1 if ($result eq 'ok');
                    919: 
                    920:     return 0;
                    921: }
                    922: 
1.1076    raeburn   923: # --------- determine least loaded server in a user's domain which allows login
                    924: 
                    925: sub choose_server {
1.1115    raeburn   926:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   927:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   928:     my %servers = &get_servers($udom);
1.1076    raeburn   929:     my $lowest_load = 30000;
1.1116    raeburn   930:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   931:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   932:         my $loginvia;
                    933:         if ($checkloginvia) {
                    934:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   935:             if ($loginvia) {
                    936:                 my ($server,$path) = split(/:/,$loginvia);
                    937:                 ($login_host, $lowest_load) =
                    938:                     &compare_server_load($server, $login_host, $lowest_load);
                    939:                 if ($login_host eq $server) {
                    940:                     $portal_path = $path;
                    941:                 }
                    942:             } else {
                    943:                 ($login_host, $lowest_load) =
                    944:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    945:                 if ($login_host eq $lonhost) {
                    946:                     $portal_path = '';
                    947:                 }
                    948:             }
                    949:         } else {
1.1076    raeburn   950:             ($login_host, $lowest_load) =
1.1116    raeburn   951:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   952:         }
                    953:     }
                    954:     if ($login_host ne '') {
1.1116    raeburn   955:         $hostname = &hostname($login_host);
1.1076    raeburn   956:     }
1.1116    raeburn   957:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   958: }
                    959: 
1.202     matthew   960: # --------------------------------------------- Try to change a user's password
                    961: 
                    962: sub changepass {
1.799     raeburn   963:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   964:     $currentpass = &escape($currentpass);
                    965:     $newpass     = &escape($newpass);
1.1030    raeburn   966:     my $lonhost = $perlvar{'lonHostID'};
                    967:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   968: 		       $server);
                    969:     if (! $answer) {
                    970: 	&logthis("No reply on password change request to $server ".
                    971: 		 "by $uname in domain $udom.");
                    972:     } elsif ($answer =~ "^ok") {
                    973:         &logthis("$uname in $udom successfully changed their password ".
                    974: 		 "on $server.");
                    975:     } elsif ($answer =~ "^pwchange_failure") {
                    976: 	&logthis("$uname in $udom was unable to change their password ".
                    977: 		 "on $server.  The action was blocked by either lcpasswd ".
                    978: 		 "or pwchange");
                    979:     } elsif ($answer =~ "^non_authorized") {
                    980:         &logthis("$uname in $udom did not get their password correct when ".
                    981: 		 "attempting to change it on $server.");
                    982:     } elsif ($answer =~ "^auth_mode_error") {
                    983:         &logthis("$uname in $udom attempted to change their password despite ".
                    984: 		 "not being locally or internally authenticated on $server.");
                    985:     } elsif ($answer =~ "^unknown_user") {
                    986:         &logthis("$uname in $udom attempted to change their password ".
                    987: 		 "on $server but were unable to because $server is not ".
                    988: 		 "their home server.");
                    989:     } elsif ($answer =~ "^refused") {
                    990: 	&logthis("$server refused to change $uname in $udom password because ".
                    991: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   992:     } elsif ($answer =~ "invalid_client") {
                    993:         &logthis("$server refused to change $uname in $udom password because ".
                    994:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   995:     }
                    996:     return $answer;
1.1       albertel  997: }
                    998: 
1.169     harris41  999: # ----------------------- Try to determine user's current authentication scheme
                   1000: 
                   1001: sub queryauthenticate {
                   1002:     my ($uname,$udom)=@_;
1.456     albertel 1003:     my $uhome=&homeserver($uname,$udom);
                   1004:     if (!$uhome) {
                   1005: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1006: 	return 'no_host';
                   1007:     }
                   1008:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1009:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1010: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1011:     }
1.456     albertel 1012:     return $answer;
1.169     harris41 1013: }
                   1014: 
1.1       albertel 1015: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1016: 
1.1       albertel 1017: sub authenticate {
1.1073    raeburn  1018:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1019:     $upass=&escape($upass);
                   1020:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1021:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1022:     my $newhome;
1.836     www      1023:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1024: # Maybe the machine was offline and only re-appeared again recently?
                   1025:         &reconlonc();
                   1026: # One more
1.952     raeburn  1027: 	$uhome=&homeserver($uname,$udom,1);
                   1028:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1029:             if (defined(&domain($udom,'primary'))) {
                   1030:                 $newhome=&domain($udom,'primary');
                   1031:             }
                   1032:             if ($newhome ne '') {
                   1033:                 $uhome = $newhome;
                   1034:             }
                   1035:         }
1.836     www      1036: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1037: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1038: 	    return 'no_host';
                   1039:         }
1.1       albertel 1040:     }
1.1073    raeburn  1041:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1042:     if ($answer eq 'authorized') {
1.952     raeburn  1043:         if ($newhome) {
                   1044:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1045:             return 'no_account_on_host'; 
                   1046:         } else {
                   1047:             &logthis("User $uname at $udom authorized by $uhome");
                   1048:             return $uhome;
                   1049:         }
1.471     albertel 1050:     }
                   1051:     if ($answer eq 'non_authorized') {
                   1052: 	&logthis("User $uname at $udom rejected by $uhome");
                   1053: 	return 'no_host'; 
1.9       www      1054:     }
1.471     albertel 1055:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1056:     return 'no_host';
                   1057: }
                   1058: 
1.1073    raeburn  1059: sub can_host_session {
1.1074    raeburn  1060:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1061:     my $canhost = 1;
1.1074    raeburn  1062:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1063:     if (ref($remotesessions) eq 'HASH') {
                   1064:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1065:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1066:                 $canhost = 0;
                   1067:             } else {
                   1068:                 $canhost = 1;
                   1069:             }
                   1070:         }
                   1071:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1072:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1073:                 $canhost = 1;
                   1074:             } else {
                   1075:                 $canhost = 0;
                   1076:             }
                   1077:         }
                   1078:         if ($canhost) {
                   1079:             if ($remotesessions->{'version'} ne '') {
                   1080:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1081:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1082:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1083:                         my $major = $1;
                   1084:                         my $minor = $2;
                   1085:                         if (($major < $reqmajor ) ||
                   1086:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1087:                             $canhost = 0;
                   1088:                         }
                   1089:                     } else {
                   1090:                         $canhost = 0;
                   1091:                     }
                   1092:                 }
                   1093:             }
                   1094:         }
                   1095:     }
                   1096:     if ($canhost) {
                   1097:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1098:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1099:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1100:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1101:                 if (($uint_dom ne '') && 
                   1102:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1103:                     $canhost = 0;
                   1104:                 } else {
                   1105:                     $canhost = 1;
                   1106:                 }
                   1107:             }
                   1108:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1109:                 if (($uint_dom ne '') && 
                   1110:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1111:                     $canhost = 1;
                   1112:                 } else {
                   1113:                     $canhost = 0;
                   1114:                 }
                   1115:             }
                   1116:         }
                   1117:     }
                   1118:     return $canhost;
                   1119: }
                   1120: 
1.1083    raeburn  1121: sub spare_can_host {
                   1122:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1123:     my $canhost=1;
                   1124:     my @intdoms;
                   1125:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1126:     if (ref($internet_names) eq 'ARRAY') {
                   1127:         @intdoms = @{$internet_names};
                   1128:     }
                   1129:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1130:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1131:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1132:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1133:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1134:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1135:                                      $remotesessions,
                   1136:                                      $defdomdefaults{'hostedsessions'});
                   1137:     }
                   1138:     return $canhost;
                   1139: }
                   1140: 
1.1123    raeburn  1141: sub this_host_spares {
                   1142:     my ($dom) = @_;
                   1143:     my $cachetime = 60*60*24;
                   1144:     my @hosts = &current_machine_ids();
                   1145:     foreach my $lonhost (@hosts) {
                   1146:         if (&host_domain($lonhost) eq $dom) {
                   1147:             my ($result,$cached)=&is_cached_new('spares',$dom);
                   1148:             if (defined($cached)) {
                   1149:                 return $result;
                   1150:             } else {
                   1151:                 my %domconfig =
                   1152:                     &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
                   1153:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1154:                     if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1155:                         if (ref($domconfig{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
                   1156:                             return &do_cache_new('spares',$dom,$domconfig{'usersessions'}{'spares'}{$lonhost},$cachetime);
                   1157:                         }
                   1158:                     }
                   1159:                 }
                   1160:             }
                   1161:             last;
                   1162:         }
                   1163:     }
                   1164:     my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   1165:     my ($result,$cached)=&is_cached_new('spares',$serverhomedom);
                   1166:     if (defined($cached)) {
                   1167:         return $result;
                   1168:     } else {
                   1169:         my %homedomconfig =
                   1170:             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
                   1171:         if (ref($homedomconfig{'usersessions'}) eq 'HASH') {
                   1172:             if (ref($homedomconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1173:                 if (ref($homedomconfig{'usersessions'}{'spares'}{$perlvar{'lonHostID'}}) eq 'HASH') {
                   1174:                     return &do_cache_new('spares',$serverhomedom,$homedomconfig{'usersessions'}{'spares'}{$perlvar{'lonHostID'}},$cachetime);
                   1175:                 }
                   1176:             }
                   1177:         }
                   1178:     }
                   1179:     return \%spareid;
                   1180: }
                   1181: 
1.1       albertel 1182: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1183: 
1.599     albertel 1184: my %homecache;
1.1       albertel 1185: sub homeserver {
1.230     stredwic 1186:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1187:     my $index="$uname:$udom";
1.426     albertel 1188: 
1.599     albertel 1189:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1190: 
                   1191:     my %servers = &get_servers($udom,'library');
                   1192:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1193:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1194: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1195: 
                   1196: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1197: 	if ($answer eq 'found') {
                   1198: 	    delete($badServerCache{$tryserver}); 
                   1199: 	    return $homecache{$index}=$tryserver;
                   1200: 	} elsif ($answer eq 'no_host') {
                   1201: 	    $badServerCache{$tryserver}=1;
                   1202: 	}
1.1       albertel 1203:     }    
                   1204:     return 'no_host';
1.70      www      1205: }
                   1206: 
                   1207: # ------------------------------------- Find the usernames behind a list of IDs
                   1208: 
                   1209: sub idget {
                   1210:     my ($udom,@ids)=@_;
                   1211:     my %returnhash=();
                   1212:     
1.841     albertel 1213:     my %servers = &get_servers($udom,'library');
                   1214:     foreach my $tryserver (keys(%servers)) {
                   1215: 	my $idlist=join('&',@ids);
                   1216: 	$idlist=~tr/A-Z/a-z/; 
                   1217: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1218: 	my @answer=();
                   1219: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1220: 	    @answer=split(/\&/,$reply);
                   1221: 	}                    ;
                   1222: 	my $i;
                   1223: 	for ($i=0;$i<=$#ids;$i++) {
                   1224: 	    if ($answer[$i]) {
                   1225: 		$returnhash{$ids[$i]}=$answer[$i];
                   1226: 	    } 
                   1227: 	}
                   1228:     } 
1.70      www      1229:     return %returnhash;
                   1230: }
                   1231: 
                   1232: # ------------------------------------- Find the IDs behind a list of usernames
                   1233: 
                   1234: sub idrget {
                   1235:     my ($udom,@unames)=@_;
                   1236:     my %returnhash=();
1.800     albertel 1237:     foreach my $uname (@unames) {
                   1238:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1239:     }
1.70      www      1240:     return %returnhash;
                   1241: }
                   1242: 
                   1243: # ------------------------------- Store away a list of names and associated IDs
                   1244: 
                   1245: sub idput {
                   1246:     my ($udom,%ids)=@_;
                   1247:     my %servers=();
1.800     albertel 1248:     foreach my $uname (keys(%ids)) {
                   1249: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1250:         my $uhom=&homeserver($uname,$udom);
1.70      www      1251:         if ($uhom ne 'no_host') {
1.800     albertel 1252:             my $id=&escape($ids{$uname});
1.70      www      1253:             $id=~tr/A-Z/a-z/;
1.800     albertel 1254:             my $esc_unam=&escape($uname);
1.70      www      1255: 	    if ($servers{$uhom}) {
1.800     albertel 1256: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1257:             } else {
1.800     albertel 1258:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1259:             }
                   1260:         }
1.191     harris41 1261:     }
1.800     albertel 1262:     foreach my $server (keys(%servers)) {
                   1263:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1264:     }
1.344     www      1265: }
                   1266: 
1.1023    raeburn  1267: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1268: sub dump_dom {
1.1023    raeburn  1269:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1270:     if (!$udom) {
                   1271:         $udom=$env{'user.domain'};
                   1272:     }
                   1273:     my %returnhash;
1.1023    raeburn  1274:     if ($udom) {
                   1275:         my $uname = &get_domainconfiguser($udom);
                   1276:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1277:     }
                   1278:     return %returnhash;
                   1279: }
                   1280: 
1.1023    raeburn  1281: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1282: 
                   1283: sub get_dom {
1.860     raeburn  1284:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1285:     my $items='';
                   1286:     foreach my $item (@$storearr) {
                   1287:         $items.=&escape($item).'&';
                   1288:     }
                   1289:     $items=~s/\&$//;
1.860     raeburn  1290:     if (!$udom) {
                   1291:         $udom=$env{'user.domain'};
                   1292:         if (defined(&domain($udom,'primary'))) {
                   1293:             $uhome=&domain($udom,'primary');
                   1294:         } else {
1.874     albertel 1295:             undef($uhome);
1.860     raeburn  1296:         }
                   1297:     } else {
                   1298:         if (!$uhome) {
                   1299:             if (defined(&domain($udom,'primary'))) {
                   1300:                 $uhome=&domain($udom,'primary');
                   1301:             }
                   1302:         }
                   1303:     }
                   1304:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1305:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1306:         my %returnhash;
1.875     albertel 1307:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1308:             return %returnhash;
                   1309:         }
1.806     raeburn  1310:         my @pairs=split(/\&/,$rep);
                   1311:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1312:             return @pairs;
                   1313:         }
                   1314:         my $i=0;
                   1315:         foreach my $item (@$storearr) {
                   1316:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1317:             $i++;
                   1318:         }
                   1319:         return %returnhash;
                   1320:     } else {
1.880     banghart 1321:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1322:     }
                   1323: }
                   1324: 
                   1325: # -------------------------------------------- put items in domain db files 
                   1326: 
                   1327: sub put_dom {
1.860     raeburn  1328:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1329:     if (!$udom) {
                   1330:         $udom=$env{'user.domain'};
                   1331:         if (defined(&domain($udom,'primary'))) {
                   1332:             $uhome=&domain($udom,'primary');
                   1333:         } else {
1.874     albertel 1334:             undef($uhome);
1.860     raeburn  1335:         }
                   1336:     } else {
                   1337:         if (!$uhome) {
                   1338:             if (defined(&domain($udom,'primary'))) {
                   1339:                 $uhome=&domain($udom,'primary');
                   1340:             }
                   1341:         }
                   1342:     } 
                   1343:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1344:         my $items='';
                   1345:         foreach my $item (keys(%$storehash)) {
                   1346:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1347:         }
                   1348:         $items=~s/\&$//;
                   1349:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1350:     } else {
1.860     raeburn  1351:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1352:     }
                   1353: }
                   1354: 
1.1023    raeburn  1355: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1356: sub newput_dom {
1.1023    raeburn  1357:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1358:     my $result;
                   1359:     if (!$udom) {
                   1360:         $udom=$env{'user.domain'};
                   1361:     }
1.1023    raeburn  1362:     if ($udom) {
                   1363:         my $uname = &get_domainconfiguser($udom);
                   1364:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1365:     }
                   1366:     return $result;
                   1367: }
                   1368: 
1.1023    raeburn  1369: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1370: sub del_dom {
1.1023    raeburn  1371:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1372:     if (ref($storearr) eq 'ARRAY') {
                   1373:         if (!$udom) {
                   1374:             $udom=$env{'user.domain'};
                   1375:         }
1.1023    raeburn  1376:         if ($udom) {
                   1377:             my $uname = &get_domainconfiguser($udom); 
                   1378:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1379:         }
                   1380:     }
                   1381: }
                   1382: 
1.1023    raeburn  1383: # ----------------------------------construct domainconfig user for a domain 
                   1384: sub get_domainconfiguser {
                   1385:     my ($udom) = @_;
                   1386:     return $udom.'-domainconfig';
                   1387: }
                   1388: 
1.837     raeburn  1389: sub retrieve_inst_usertypes {
                   1390:     my ($udom) = @_;
                   1391:     my (%returnhash,@order);
1.989     raeburn  1392:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1393:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1394:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1395:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1396:         @order = @{$domdefs{'inststatusorder'}};
                   1397:     } else {
                   1398:         if (defined(&domain($udom,'primary'))) {
                   1399:             my $uhome=&domain($udom,'primary');
                   1400:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1401:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1402:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1403:                 return (\%returnhash,\@order);
                   1404:             }
                   1405:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1406:             my @pairs=split(/\&/,$hashitems);
                   1407:             foreach my $item (@pairs) {
                   1408:                 my ($key,$value)=split(/=/,$item,2);
                   1409:                 $key = &unescape($key);
                   1410:                 next if ($key =~ /^error: 2 /);
                   1411:                 $returnhash{$key}=&thaw_unescape($value);
                   1412:             }
                   1413:             my @esc_order = split(/\&/,$orderitems);
                   1414:             foreach my $item (@esc_order) {
                   1415:                 push(@order,&unescape($item));
                   1416:             }
                   1417:         } else {
                   1418:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1419:         }
                   1420:     }
                   1421:     return (\%returnhash,\@order);
                   1422: }
                   1423: 
1.868     raeburn  1424: sub is_domainimage {
                   1425:     my ($url) = @_;
                   1426:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1427:         if (&domain($1) ne '') {
                   1428:             return '1';
                   1429:         }
                   1430:     }
                   1431:     return;
                   1432: }
                   1433: 
1.899     raeburn  1434: sub inst_directory_query {
                   1435:     my ($srch) = @_;
                   1436:     my $udom = $srch->{'srchdomain'};
                   1437:     my %results;
                   1438:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1439:     my $outcome;
1.899     raeburn  1440:     if ($homeserver ne '') {
1.904     albertel 1441: 	my $queryid=&reply("querysend:instdirsearch:".
                   1442: 			   &escape($srch->{'srchby'}).':'.
                   1443: 			   &escape($srch->{'srchterm'}).':'.
                   1444: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1445: 	my $host=&hostname($homeserver);
                   1446: 	if ($queryid !~/^\Q$host\E\_/) {
                   1447: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1448: 	    return;
                   1449: 	}
                   1450: 	my $response = &get_query_reply($queryid);
                   1451: 	my $maxtries = 5;
                   1452: 	my $tries = 1;
                   1453: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1454: 	    $response = &get_query_reply($queryid);
                   1455: 	    $tries ++;
                   1456: 	}
                   1457: 
                   1458:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1459:             if ($response eq 'unavailable') {
                   1460:                 $outcome = $response;
                   1461:             } else {
                   1462:                 $outcome = 'ok';
                   1463:                 my @matches = split(/\n/,$response);
                   1464:                 foreach my $match (@matches) {
                   1465:                     my ($key,$value) = split(/=/,$match);
                   1466:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1467:                 }
1.899     raeburn  1468:             }
                   1469:         }
                   1470:     }
1.909     raeburn  1471:     return ($outcome,%results);
1.899     raeburn  1472: }
                   1473: 
                   1474: sub usersearch {
                   1475:     my ($srch) = @_;
                   1476:     my $dom = $srch->{'srchdomain'};
                   1477:     my %results;
                   1478:     my %libserv = &all_library();
                   1479:     my $query = 'usersearch';
                   1480:     foreach my $tryserver (keys(%libserv)) {
                   1481:         if (&host_domain($tryserver) eq $dom) {
                   1482:             my $host=&hostname($tryserver);
                   1483:             my $queryid=
1.911     raeburn  1484:                 &reply("querysend:".&escape($query).':'.
                   1485:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1486:                        &escape($srch->{'srchtype'}).':'.
                   1487:                        &escape($srch->{'srchterm'}),$tryserver);
                   1488:             if ($queryid !~/^\Q$host\E\_/) {
                   1489:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1490:                 next;
1.899     raeburn  1491:             }
                   1492:             my $reply = &get_query_reply($queryid);
                   1493:             my $maxtries = 1;
                   1494:             my $tries = 1;
                   1495:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1496:                 $reply = &get_query_reply($queryid);
                   1497:                 $tries ++;
                   1498:             }
                   1499:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1500:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1501:             } else {
1.911     raeburn  1502:                 my @matches;
                   1503:                 if ($reply =~ /\n/) {
                   1504:                     @matches = split(/\n/,$reply);
                   1505:                 } else {
                   1506:                     @matches = split(/\&/,$reply);
                   1507:                 }
1.899     raeburn  1508:                 foreach my $match (@matches) {
                   1509:                     my ($uname,$udom,%userhash);
1.911     raeburn  1510:                     foreach my $entry (split(/:/,$match)) {
                   1511:                         my ($key,$value) =
                   1512:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1513:                         $userhash{$key} = $value;
                   1514:                         if ($key eq 'username') {
                   1515:                             $uname = $value;
                   1516:                         } elsif ($key eq 'domain') {
                   1517:                             $udom = $value;
1.911     raeburn  1518:                         }
1.899     raeburn  1519:                     }
                   1520:                     $results{$uname.':'.$udom} = \%userhash;
                   1521:                 }
                   1522:             }
                   1523:         }
                   1524:     }
                   1525:     return %results;
                   1526: }
                   1527: 
1.912     raeburn  1528: sub get_instuser {
                   1529:     my ($udom,$uname,$id) = @_;
                   1530:     my $homeserver = &domain($udom,'primary');
                   1531:     my ($outcome,%results);
                   1532:     if ($homeserver ne '') {
                   1533:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1534:                            &escape($id).':'.&escape($udom),$homeserver);
                   1535:         my $host=&hostname($homeserver);
                   1536:         if ($queryid !~/^\Q$host\E\_/) {
                   1537:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1538:             return;
                   1539:         }
                   1540:         my $response = &get_query_reply($queryid);
                   1541:         my $maxtries = 5;
                   1542:         my $tries = 1;
                   1543:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1544:             $response = &get_query_reply($queryid);
                   1545:             $tries ++;
                   1546:         }
                   1547:         if (!&error($response) && $response ne 'refused') {
                   1548:             if ($response eq 'unavailable') {
                   1549:                 $outcome = $response;
                   1550:             } else {
                   1551:                 $outcome = 'ok';
                   1552:                 my @matches = split(/\n/,$response);
                   1553:                 foreach my $match (@matches) {
                   1554:                     my ($key,$value) = split(/=/,$match);
                   1555:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1556:                 }
                   1557:             }
                   1558:         }
                   1559:     }
                   1560:     my %userinfo;
                   1561:     if (ref($results{$uname}) eq 'HASH') {
                   1562:         %userinfo = %{$results{$uname}};
                   1563:     } 
                   1564:     return ($outcome,%userinfo);
                   1565: }
                   1566: 
                   1567: sub inst_rulecheck {
1.923     raeburn  1568:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1569:     my %returnhash;
                   1570:     if ($udom ne '') {
                   1571:         if (ref($rules) eq 'ARRAY') {
                   1572:             @{$rules} = map {&escape($_);} (@{$rules});
                   1573:             my $rulestr = join(':',@{$rules});
                   1574:             my $homeserver=&domain($udom,'primary');
                   1575:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1576:                 my $response;
                   1577:                 if ($item eq 'username') {                
                   1578:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1579:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1580:                                               $homeserver));
1.923     raeburn  1581:                 } elsif ($item eq 'id') {
                   1582:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1583:                                               ':'.&escape($id).':'.$rulestr,
                   1584:                                               $homeserver));
1.945     raeburn  1585:                 } elsif ($item eq 'selfcreate') {
                   1586:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1587:                                                &escape($udom).':'.&escape($uname).
                   1588:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1589:                 }
1.912     raeburn  1590:                 if ($response ne 'refused') {
                   1591:                     my @pairs=split(/\&/,$response);
                   1592:                     foreach my $item (@pairs) {
                   1593:                         my ($key,$value)=split(/=/,$item,2);
                   1594:                         $key = &unescape($key);
                   1595:                         next if ($key =~ /^error: 2 /);
                   1596:                         $returnhash{$key}=&thaw_unescape($value);
                   1597:                     }
                   1598:                 }
                   1599:             }
                   1600:         }
                   1601:     }
                   1602:     return %returnhash;
                   1603: }
                   1604: 
                   1605: sub inst_userrules {
1.923     raeburn  1606:     my ($udom,$check) = @_;
1.912     raeburn  1607:     my (%ruleshash,@ruleorder);
                   1608:     if ($udom ne '') {
                   1609:         my $homeserver=&domain($udom,'primary');
                   1610:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1611:             my $response;
                   1612:             if ($check eq 'id') {
                   1613:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1614:                                  $homeserver);
1.943     raeburn  1615:             } elsif ($check eq 'email') {
                   1616:                 $response=&reply('instemailrules:'.&escape($udom),
                   1617:                                  $homeserver);
1.923     raeburn  1618:             } else {
                   1619:                 $response=&reply('instuserrules:'.&escape($udom),
                   1620:                                  $homeserver);
                   1621:             }
1.912     raeburn  1622:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1623:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1624:                 ($response ne 'no_such_host')) {
                   1625:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1626:                 my @pairs=split(/\&/,$hashitems);
                   1627:                 foreach my $item (@pairs) {
                   1628:                     my ($key,$value)=split(/=/,$item,2);
                   1629:                     $key = &unescape($key);
                   1630:                     next if ($key =~ /^error: 2 /);
                   1631:                     $ruleshash{$key}=&thaw_unescape($value);
                   1632:                 }
                   1633:                 my @esc_order = split(/\&/,$orderitems);
                   1634:                 foreach my $item (@esc_order) {
                   1635:                     push(@ruleorder,&unescape($item));
                   1636:                 }
                   1637:             }
                   1638:         }
                   1639:     }
                   1640:     return (\%ruleshash,\@ruleorder);
                   1641: }
                   1642: 
1.976     raeburn  1643: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1644: 
                   1645: sub get_domain_defaults {
                   1646:     my ($domain) = @_;
                   1647:     my $cachetime = 60*60*24;
                   1648:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1649:     if (defined($cached)) {
                   1650:         if (ref($result) eq 'HASH') {
                   1651:             return %{$result};
                   1652:         }
                   1653:     }
                   1654:     my %domdefaults;
                   1655:     my %domconfig =
1.989     raeburn  1656:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1657:                                   'requestcourses','inststatus',
1.1073    raeburn  1658:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1659:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1660:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1661:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1662:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1663:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1664:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1665:     } else {
                   1666:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1667:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1668:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1669:     }
1.976     raeburn  1670:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1671:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1672:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1673:         } else {
                   1674:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1675:         } 
                   1676:         my @usertools = ('aboutme','blog','portfolio');
                   1677:         foreach my $item (@usertools) {
                   1678:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1679:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1680:             }
                   1681:         }
                   1682:     }
1.985     raeburn  1683:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1684:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1685:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1686:         }
                   1687:     }
1.989     raeburn  1688:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1689:         foreach my $item ('inststatustypes','inststatusorder') {
                   1690:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1691:         }
                   1692:     }
1.1047    raeburn  1693:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1694:         foreach my $item ('canuse_pdfforms') {
                   1695:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1696:         }
                   1697:     }
1.1073    raeburn  1698:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1699:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1700:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1701:         }
                   1702:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1703:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1704:         }
                   1705:     }
1.943     raeburn  1706:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1707:                                   $cachetime);
                   1708:     return %domdefaults;
                   1709: }
                   1710: 
1.344     www      1711: # --------------------------------------------------- Assign a key to a student
                   1712: 
                   1713: sub assign_access_key {
1.364     www      1714: #
                   1715: # a valid key looks like uname:udom#comments
                   1716: # comments are being appended
                   1717: #
1.498     www      1718:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1719:     $kdom=
1.620     albertel 1720:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1721:     $knum=
1.620     albertel 1722:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1723:     $cdom=
1.620     albertel 1724:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1725:     $cnum=
1.620     albertel 1726:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1727:     $udom=$env{'user.name'} unless (defined($udom));
                   1728:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1729:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1730:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1731:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1732:                                                   # assigned to this person
                   1733:                                                   # - this should not happen,
1.345     www      1734:                                                   # unless something went wrong
                   1735:                                                   # the first time around
                   1736: # ready to assign
1.364     www      1737:         $logentry=$1.'; '.$logentry;
1.496     www      1738:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1739:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1740: # key now belongs to user
1.346     www      1741: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1742:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1743:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1744:                 return 'ok';
                   1745:             } else {
                   1746:                 return 
                   1747:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1748: 	    }
                   1749:         } else {
                   1750:             return 'error: Could not assign key, try again later.';
                   1751:         }
1.364     www      1752:     } elsif (!$existing{$ckey}) {
1.345     www      1753: # the key does not exist
                   1754: 	return 'error: The key does not exist';
                   1755:     } else {
                   1756: # the key is somebody else's
                   1757: 	return 'error: The key is already in use';
                   1758:     }
1.344     www      1759: }
                   1760: 
1.364     www      1761: # ------------------------------------------ put an additional comment on a key
                   1762: 
                   1763: sub comment_access_key {
                   1764: #
                   1765: # a valid key looks like uname:udom#comments
                   1766: # comments are being appended
                   1767: #
                   1768:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1769:     $cdom=
1.620     albertel 1770:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1771:     $cnum=
1.620     albertel 1772:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1773:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1774:     if ($existing{$ckey}) {
                   1775:         $existing{$ckey}.='; '.$logentry;
                   1776: # ready to assign
1.367     www      1777:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1778:                                                  $cdom,$cnum) eq 'ok') {
                   1779: 	    return 'ok';
                   1780:         } else {
                   1781: 	    return 'error: Count not store comment.';
                   1782:         }
                   1783:     } else {
                   1784: # the key does not exist
                   1785: 	return 'error: The key does not exist';
                   1786:     }
                   1787: }
                   1788: 
1.344     www      1789: # ------------------------------------------------------ Generate a set of keys
                   1790: 
                   1791: sub generate_access_keys {
1.364     www      1792:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1793:     $cdom=
1.620     albertel 1794:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1795:     $cnum=
1.620     albertel 1796:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1797:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1798:     unless (($cdom) && ($cnum)) { return 0; }
                   1799:     if ($number>10000) { return 0; }
                   1800:     sleep(2); # make sure don't get same seed twice
                   1801:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1802:     my $total=0;
                   1803:     for (my $i=1;$i<=$number;$i++) {
                   1804:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1805:                   sprintf("%lx",int(100000*rand)).'-'.
                   1806:                   sprintf("%lx",int(100000*rand));
                   1807:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1808:        $newkey=~s/0/h/g; # and also 0 and O
                   1809:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1810:        if ($existing{$newkey}) {
                   1811:            $i--;
                   1812:        } else {
1.364     www      1813: 	  if (&put('accesskeys',
                   1814:               { $newkey => '# generated '.localtime().
1.620     albertel 1815:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1816:                            '; '.$logentry },
                   1817: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1818:               $total++;
                   1819: 	  }
                   1820:        }
                   1821:     }
1.620     albertel 1822:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1823:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1824:     return $total;
                   1825: }
                   1826: 
                   1827: # ------------------------------------------------------- Validate an accesskey
                   1828: 
                   1829: sub validate_access_key {
                   1830:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1831:     $cdom=
1.620     albertel 1832:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1833:     $cnum=
1.620     albertel 1834:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1835:     $udom=$env{'user.domain'} unless (defined($udom));
                   1836:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1837:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1838:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1839: }
                   1840: 
                   1841: # ------------------------------------- Find the section of student in a course
1.652     albertel 1842: sub devalidate_getsection_cache {
                   1843:     my ($udom,$unam,$courseid)=@_;
                   1844:     my $hashid="$udom:$unam:$courseid";
                   1845:     &devalidate_cache_new('getsection',$hashid);
                   1846: }
1.298     matthew  1847: 
1.815     albertel 1848: sub courseid_to_courseurl {
                   1849:     my ($courseid) = @_;
                   1850:     #already url style courseid
                   1851:     return $courseid if ($courseid =~ m{^/});
                   1852: 
                   1853:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1854: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1855: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1856: 	return "/$cdom/$cnum";
                   1857:     }
                   1858: 
                   1859:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1860:     if (exists($courseinfo{'num'})) {
                   1861: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1862:     }
                   1863: 
                   1864:     return undef;
                   1865: }
                   1866: 
1.298     matthew  1867: sub getsection {
                   1868:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1869:     my $cachetime=1800;
1.551     albertel 1870: 
                   1871:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1872:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1873:     if (defined($cached)) { return $result; }
                   1874: 
1.298     matthew  1875:     my %Pending; 
                   1876:     my %Expired;
                   1877:     #
                   1878:     # Each role can either have not started yet (pending), be active, 
                   1879:     #    or have expired.
                   1880:     #
                   1881:     # If there is an active role, we are done.
                   1882:     #
                   1883:     # If there is more than one role which has not started yet, 
                   1884:     #     choose the one which will start sooner
                   1885:     # If there is one role which has not started yet, return it.
                   1886:     #
                   1887:     # If there is more than one expired role, choose the one which ended last.
                   1888:     # If there is a role which has expired, return it.
                   1889:     #
1.815     albertel 1890:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1891:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1892:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1893:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1894:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1895:         my $section=$1;
                   1896:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1897:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1898:         my $now=time;
1.548     albertel 1899:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1900:             $Expired{$end}=$section;
                   1901:             next;
                   1902:         }
1.548     albertel 1903:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1904:             $Pending{$start}=$section;
                   1905:             next;
                   1906:         }
1.599     albertel 1907:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1908:     }
                   1909:     #
                   1910:     # Presumedly there will be few matching roles from the above
                   1911:     # loop and the sorting time will be negligible.
                   1912:     if (scalar(keys(%Pending))) {
                   1913:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1914:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1915:     } 
                   1916:     if (scalar(keys(%Expired))) {
                   1917:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1918:         my $time = pop(@sorted);
1.599     albertel 1919:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1920:     }
1.599     albertel 1921:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1922: }
1.70      www      1923: 
1.599     albertel 1924: sub save_cache {
                   1925:     &purge_remembered();
1.722     albertel 1926:     #&Apache::loncommon::validate_page();
1.620     albertel 1927:     undef(%env);
1.780     albertel 1928:     undef($env_loaded);
1.599     albertel 1929: }
1.452     albertel 1930: 
1.599     albertel 1931: my $to_remember=-1;
                   1932: my %remembered;
                   1933: my %accessed;
                   1934: my $kicks=0;
                   1935: my $hits=0;
1.849     albertel 1936: sub make_key {
                   1937:     my ($name,$id) = @_;
1.872     albertel 1938:     if (length($id) > 65 
                   1939: 	&& length(&escape($id)) > 200) {
                   1940: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1941:     }
1.849     albertel 1942:     return &escape($name.':'.$id);
                   1943: }
                   1944: 
1.599     albertel 1945: sub devalidate_cache_new {
                   1946:     my ($name,$id,$debug) = @_;
                   1947:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1948:     $id=&make_key($name,$id);
1.599     albertel 1949:     $memcache->delete($id);
                   1950:     delete($remembered{$id});
                   1951:     delete($accessed{$id});
                   1952: }
                   1953: 
                   1954: sub is_cached_new {
                   1955:     my ($name,$id,$debug) = @_;
1.849     albertel 1956:     $id=&make_key($name,$id);
1.599     albertel 1957:     if (exists($remembered{$id})) {
                   1958: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1959: 	$accessed{$id}=[&gettimeofday()];
                   1960: 	$hits++;
                   1961: 	return ($remembered{$id},1);
                   1962:     }
                   1963:     my $value = $memcache->get($id);
                   1964:     if (!(defined($value))) {
                   1965: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1966: 	return (undef,undef);
1.416     albertel 1967:     }
1.599     albertel 1968:     if ($value eq '__undef__') {
                   1969: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1970: 	$value=undef;
                   1971:     }
                   1972:     &make_room($id,$value,$debug);
                   1973:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1974:     return ($value,1);
                   1975: }
                   1976: 
                   1977: sub do_cache_new {
                   1978:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1979:     $id=&make_key($name,$id);
1.599     albertel 1980:     my $setvalue=$value;
                   1981:     if (!defined($setvalue)) {
                   1982: 	$setvalue='__undef__';
                   1983:     }
1.623     albertel 1984:     if (!defined($time) ) {
                   1985: 	$time=600;
                   1986:     }
1.599     albertel 1987:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1988:     my $result = $memcache->set($id,$setvalue,$time);
                   1989:     if (! $result) {
1.872     albertel 1990: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1991: 	$memcache->disconnect_all();
1.872     albertel 1992:     }
1.600     albertel 1993:     # need to make a copy of $value
1.919     albertel 1994:     &make_room($id,$value,$debug);
1.599     albertel 1995:     return $value;
                   1996: }
                   1997: 
                   1998: sub make_room {
                   1999:     my ($id,$value,$debug)=@_;
1.919     albertel 2000: 
                   2001:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2002:                                     : $value;
1.599     albertel 2003:     if ($to_remember<0) { return; }
                   2004:     $accessed{$id}=[&gettimeofday()];
                   2005:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2006:     my $to_kick;
                   2007:     my $max_time=0;
                   2008:     foreach my $other (keys(%accessed)) {
                   2009: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2010: 	    $to_kick=$other;
                   2011: 	    $max_time=&tv_interval($accessed{$other});
                   2012: 	}
                   2013:     }
                   2014:     delete($remembered{$to_kick});
                   2015:     delete($accessed{$to_kick});
                   2016:     $kicks++;
                   2017:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2018:     return;
                   2019: }
                   2020: 
1.599     albertel 2021: sub purge_remembered {
1.604     albertel 2022:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2023:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2024:     undef(%remembered);
                   2025:     undef(%accessed);
1.428     albertel 2026: }
1.70      www      2027: # ------------------------------------- Read an entry from a user's environment
                   2028: 
                   2029: sub userenvironment {
                   2030:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2031:     my $items;
                   2032:     foreach my $item (@what) {
                   2033:         $items.=&escape($item).'&';
                   2034:     }
                   2035:     $items=~s/\&$//;
1.70      www      2036:     my %returnhash=();
1.1009    raeburn  2037:     my $uhome = &homeserver($unam,$udom);
                   2038:     unless ($uhome eq 'no_host') {
                   2039:         my @answer=split(/\&/, 
                   2040:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2041:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2042:             return %returnhash;
                   2043:         }
1.1009    raeburn  2044:         my $i;
                   2045:         for ($i=0;$i<=$#what;$i++) {
                   2046: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2047:         }
1.70      www      2048:     }
                   2049:     return %returnhash;
1.1       albertel 2050: }
                   2051: 
1.617     albertel 2052: # ---------------------------------------------------------- Get a studentphoto
                   2053: sub studentphoto {
                   2054:     my ($udom,$unam,$ext) = @_;
                   2055:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2056:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2057:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2058:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2059:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2060:             } else {
                   2061:                 my ($result,$perm_reqd)=
1.707     albertel 2062: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2063:                 if ($result eq 'ok') {
                   2064:                     if (!($perm_reqd eq 'yes')) {
                   2065:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2066:                     }
                   2067:                 }
                   2068:             }
                   2069:         }
                   2070:     } else {
                   2071:         my ($result,$perm_reqd) = 
1.707     albertel 2072: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2073:         if ($result eq 'ok') {
                   2074:             if (!($perm_reqd eq 'yes')) {
                   2075:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2076:             }
                   2077:         }
                   2078:     }
                   2079:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2080: }
                   2081: 
                   2082: sub retrievestudentphoto {
                   2083:     my ($udom,$unam,$ext,$type) = @_;
                   2084:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2085:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2086:     if ($ret eq 'ok') {
                   2087:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2088:         if ($type eq 'thumbnail') {
                   2089:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2090:         }
                   2091:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2092:         return $tokenurl;
                   2093:     } else {
                   2094:         if ($type eq 'thumbnail') {
                   2095:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2096:         } else { 
                   2097:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2098:         }
1.617     albertel 2099:     }
                   2100: }
                   2101: 
1.263     www      2102: # -------------------------------------------------------------------- New chat
                   2103: 
                   2104: sub chatsend {
1.724     raeburn  2105:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2106:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2107:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2108:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2109:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2110: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2111: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2112: }
                   2113: 
                   2114: # ------------------------------------------ Find current version of a resource
                   2115: 
                   2116: sub getversion {
                   2117:     my $fname=&clutter(shift);
                   2118:     unless ($fname=~/^\/res\//) { return -1; }
                   2119:     return &currentversion(&filelocation('',$fname));
                   2120: }
                   2121: 
                   2122: sub currentversion {
                   2123:     my $fname=shift;
                   2124:     my $author=$fname;
                   2125:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2126:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2127:     my $home=&homeserver($uname,$udom);
1.292     www      2128:     if ($home eq 'no_host') { 
                   2129:         return -1; 
                   2130:     }
1.1112    www      2131:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2132:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2133: 	return -1;
                   2134:     }
1.1112    www      2135:     return $answer;
1.263     www      2136: }
                   2137: 
1.1111    www      2138: #
                   2139: # Return special version number of resource if set by override, empty otherwise
                   2140: #
                   2141: sub usedversion {
                   2142:     my $fname=shift;
                   2143:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2144:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2145:     if ($urlversion) { return $urlversion; }
                   2146:     return '';
                   2147: }
                   2148: 
1.1       albertel 2149: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2150: 
1.1       albertel 2151: sub subscribe {
                   2152:     my $fname=shift;
1.761     raeburn  2153:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2154:     $fname=~s/[\n\r]//g;
1.1       albertel 2155:     my $author=$fname;
                   2156:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2157:     my ($udom,$uname)=split(/\//,$author);
                   2158:     my $home=homeserver($uname,$udom);
1.335     albertel 2159:     if ($home eq 'no_host') {
                   2160:         return 'not_found';
1.1       albertel 2161:     }
                   2162:     my $answer=reply("sub:$fname",$home);
1.64      www      2163:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2164: 	$answer.=' by '.$home;
                   2165:     }
1.1       albertel 2166:     return $answer;
                   2167: }
                   2168:     
1.8       www      2169: # -------------------------------------------------------------- Replicate file
                   2170: 
                   2171: sub repcopy {
                   2172:     my $filename=shift;
1.23      www      2173:     $filename=~s/\/+/\//g;
1.607     raeburn  2174:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2175:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2176:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2177: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2178: 	return &repcopy_userfile($filename);
                   2179:     }
1.532     albertel 2180:     $filename=~s/[\n\r]//g;
1.8       www      2181:     my $transname="$filename.in.transfer";
1.828     www      2182: # FIXME: this should flock
1.607     raeburn  2183:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2184:     my $remoteurl=subscribe($filename);
1.64      www      2185:     if ($remoteurl =~ /^con_lost by/) {
                   2186: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2187:            return 'unavailable';
1.8       www      2188:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2189: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2190: 	   return 'not_found';
1.64      www      2191:     } elsif ($remoteurl =~ /^rejected by/) {
                   2192: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2193:            return 'forbidden';
1.20      www      2194:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2195:            return 'ok';
1.8       www      2196:     } else {
1.290     www      2197:         my $author=$filename;
                   2198:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2199:         my ($udom,$uname)=split(/\//,$author);
                   2200:         my $home=homeserver($uname,$udom);
                   2201:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2202:            my @parts=split(/\//,$filename);
                   2203:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2204:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2205:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2206: 	       return 'bad_request';
1.8       www      2207:            }
                   2208:            my $count;
                   2209:            for ($count=5;$count<$#parts;$count++) {
                   2210:                $path.="/$parts[$count]";
                   2211:                if ((-e $path)!=1) {
                   2212: 		   mkdir($path,0777);
                   2213:                }
                   2214:            }
                   2215:            my $ua=new LWP::UserAgent;
                   2216:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2217:            my $response=$ua->request($request,$transname);
                   2218:            if ($response->is_error()) {
                   2219: 	       unlink($transname);
                   2220:                my $message=$response->status_line;
1.672     albertel 2221:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2222:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2223:                return 'unavailable';
1.8       www      2224:            } else {
1.16      www      2225: 	       if ($remoteurl!~/\.meta$/) {
                   2226:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2227:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2228:                   if ($mresponse->is_error()) {
                   2229: 		      unlink($filename.'.meta');
                   2230:                       &logthis(
1.672     albertel 2231:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2232:                   }
                   2233: 	       }
1.8       www      2234:                rename($transname,$filename);
1.607     raeburn  2235:                return 'ok';
1.8       www      2236:            }
1.290     www      2237:        }
1.8       www      2238:     }
1.330     www      2239: }
                   2240: 
                   2241: # ------------------------------------------------ Get server side include body
                   2242: sub ssi_body {
1.381     albertel 2243:     my ($filelink,%form)=@_;
1.606     matthew  2244:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2245:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2246:     }
1.953     www      2247:     my $output='';
                   2248:     my $response;
1.980     raeburn  2249:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2250:        ($output,$response)=&externalssi($filelink);
1.953     www      2251:     } else {
1.1004    droeschl 2252:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2253:        $filelink .= 'inhibitmenu=yes';
1.953     www      2254:        ($output,$response)=&ssi($filelink,%form);
                   2255:     }
1.778     albertel 2256:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2257:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2258:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2259:     if (wantarray) {
                   2260:         return ($output, $response);
                   2261:     } else {
                   2262:         return $output;
                   2263:     }
1.8       www      2264: }
                   2265: 
1.15      www      2266: # --------------------------------------------------------- Server Side Include
                   2267: 
1.782     albertel 2268: sub absolute_url {
                   2269:     my ($host_name) = @_;
                   2270:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2271:     if ($host_name eq '') {
                   2272: 	$host_name = $ENV{'SERVER_NAME'};
                   2273:     }
                   2274:     return $protocol.$host_name;
                   2275: }
                   2276: 
1.942     foxr     2277: #
                   2278: #   Server side include.
                   2279: # Parameters:
                   2280: #  fn     Possibly encrypted resource name/id.
                   2281: #  form   Hash that describes how the rendering should be done
                   2282: #         and other things.
1.944     foxr     2283: # Returns:
1.950     raeburn  2284: #   Scalar context: The content of the response.
                   2285: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2286: #     
1.15      www      2287: sub ssi {
                   2288: 
1.944     foxr     2289:     my ($fn,%form)=@_;
1.15      www      2290:     my $ua=new LWP::UserAgent;
1.23      www      2291:     my $request;
1.711     albertel 2292: 
                   2293:     $form{'no_update_last_known'}=1;
1.895     albertel 2294:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2295:     if (%form) {
1.782     albertel 2296:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2297:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2298:     } else {
1.782     albertel 2299:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2300:     }
                   2301: 
1.15      www      2302:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2303:     my $response=$ua->request($request);
                   2304: 
1.944     foxr     2305:     if (wantarray) {
                   2306: 	return ($response->content, $response);
                   2307:     } else {
                   2308: 	return $response->content;
1.942     foxr     2309:     }
1.324     www      2310: }
                   2311: 
                   2312: sub externalssi {
                   2313:     my ($url)=@_;
                   2314:     my $ua=new LWP::UserAgent;
                   2315:     my $request=new HTTP::Request('GET',$url);
                   2316:     my $response=$ua->request($request);
1.954     raeburn  2317:     if (wantarray) {
                   2318:         return ($response->content, $response);
                   2319:     } else {
                   2320:         return $response->content;
                   2321:     }
1.15      www      2322: }
1.254     www      2323: 
1.492     albertel 2324: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2325: 
                   2326: sub allowuploaded {
                   2327:     my ($srcurl,$url)=@_;
                   2328:     $url=&clutter(&declutter($url));
                   2329:     my $dir=$url;
                   2330:     $dir=~s/\/[^\/]+$//;
                   2331:     my %httpref=();
                   2332:     my $httpurl=&hreflocation('',$url);
                   2333:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2334:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2335: }
1.477     raeburn  2336: 
1.478     albertel 2337: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2338: # input: action, courseID, current domain, intended
1.637     raeburn  2339: #        path to file, source of file, instruction to parse file for objects,
                   2340: #        ref to hash for embedded objects,
                   2341: #        ref to hash for codebase of java objects.
1.1095    raeburn  2342: #        reference to scalar to accommodate mime type determined
                   2343: #          from File::MMagic if $parser = parse.
1.637     raeburn  2344: #
1.485     raeburn  2345: # output: url to file (if action was uploaddoc), 
                   2346: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2347: #
1.478     albertel 2348: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2349: # course.
1.477     raeburn  2350: #
1.478     albertel 2351: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2352: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2353: #          course's home server.
1.477     raeburn  2354: #
1.478     albertel 2355: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2356: #          be copied from $source (current location) to 
                   2357: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2358: #         and will then be copied to
                   2359: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2360: #         course's home server.
1.485     raeburn  2361: #
1.481     raeburn  2362: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2363: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2364: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2365: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2366: #         in course's home server.
1.637     raeburn  2367: #
1.477     raeburn  2368: 
                   2369: sub process_coursefile {
1.1095    raeburn  2370:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2371:         $mimetype)=@_;
1.477     raeburn  2372:     my $fetchresult;
1.638     albertel 2373:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2374:     if ($action eq 'propagate') {
1.638     albertel 2375:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2376: 			     $home);
1.481     raeburn  2377:     } else {
1.477     raeburn  2378:         my $fpath = '';
                   2379:         my $fname = $file;
1.478     albertel 2380:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2381:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2382:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2383:         if ($action eq 'copy') {
                   2384:             if ($source eq '') {
                   2385:                 $fetchresult = 'no source file';
                   2386:                 return $fetchresult;
                   2387:             } else {
                   2388:                 my $destination = $filepath.'/'.$fname;
                   2389:                 rename($source,$destination);
                   2390:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2391:                                  $home);
1.481     raeburn  2392:             }
                   2393:         } elsif ($action eq 'uploaddoc') {
                   2394:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2395:             print $fh $env{'form.'.$source};
1.481     raeburn  2396:             close($fh);
1.637     raeburn  2397:             if ($parser eq 'parse') {
1.1024    raeburn  2398:                 my $mm = new File::MMagic;
1.1095    raeburn  2399:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2400:                 if ($type eq 'text/html') {
1.1024    raeburn  2401:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2402:                     unless ($parse_result eq 'ok') {
                   2403:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2404:                     }
1.637     raeburn  2405:                 }
1.1095    raeburn  2406:                 if (ref($mimetype)) {
                   2407:                     $$mimetype = $type;
                   2408:                 } 
1.637     raeburn  2409:             }
1.477     raeburn  2410:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2411:                                  $home);
1.481     raeburn  2412:             if ($fetchresult eq 'ok') {
                   2413:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2414:             } else {
                   2415:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2416:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2417:                 return '/adm/notfound.html';
                   2418:             }
1.477     raeburn  2419:         }
                   2420:     }
1.485     raeburn  2421:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2422:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2423:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2424:     }
                   2425:     return $fetchresult;
                   2426: }
                   2427: 
1.637     raeburn  2428: sub build_filepath {
                   2429:     my ($fpath) = @_;
                   2430:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2431:     unless ($fpath eq '') {
                   2432:         my @parts=split('/',$fpath);
                   2433:         foreach my $part (@parts) {
                   2434:             $filepath.= '/'.$part;
                   2435:             if ((-e $filepath)!=1) {
                   2436:                 mkdir($filepath,0777);
                   2437:             }
                   2438:         }
                   2439:     }
                   2440:     return $filepath;
                   2441: }
                   2442: 
                   2443: sub store_edited_file {
1.638     albertel 2444:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2445:     my $file = $primary_url;
                   2446:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2447:     my $fpath = '';
                   2448:     my $fname = $file;
                   2449:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2450:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2451:     my $filepath = &build_filepath($fpath);
                   2452:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2453:     print $fh $content;
                   2454:     close($fh);
1.638     albertel 2455:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2456:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2457: 			  $home);
1.637     raeburn  2458:     if ($$fetchresult eq 'ok') {
                   2459:         return '/uploaded/'.$fpath.'/'.$fname;
                   2460:     } else {
1.638     albertel 2461:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2462: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2463:         return '/adm/notfound.html';
                   2464:     }
                   2465: }
                   2466: 
1.531     albertel 2467: sub clean_filename {
1.831     albertel 2468:     my ($fname,$args)=@_;
1.315     www      2469: # Replace Windows backslashes by forward slashes
1.257     www      2470:     $fname=~s/\\/\//g;
1.831     albertel 2471:     if (!$args->{'keep_path'}) {
                   2472:         # Get rid of everything but the actual filename
                   2473: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2474:     }
1.315     www      2475: # Replace spaces by underscores
                   2476:     $fname=~s/\s+/\_/g;
                   2477: # Replace all other weird characters by nothing
1.831     albertel 2478:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2479: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2480: # numbers
                   2481:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2482:     return $fname;
                   2483: }
1.1051    raeburn  2484: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2485: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2486: # image with the same aspect ratio as the original, but with dimensions which do 
                   2487: # not exceed $resizewidth and $resizeheight.
                   2488:  
1.984     neumanie 2489: sub resizeImage {
1.1051    raeburn  2490:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2491:     my $ima = Image::Magick->new;
                   2492:     my $resized;
                   2493:     if (-e $img_path) {
                   2494:         $ima->Read($img_path);
                   2495:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2496:             my $width = $ima->Get('width');
                   2497:             my $height = $ima->Get('height');
                   2498:             if ($width > $resizewidth) {
                   2499: 	        my $factor = $width/$resizewidth;
                   2500:                 my $newheight = $height/$factor;
                   2501:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2502:                 $resized = 1;
                   2503:             }
                   2504:         }
                   2505:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2506:             my $width = $ima->Get('width');
                   2507:             my $height = $ima->Get('height');
                   2508:             if ($height > $resizeheight) {
                   2509:                 my $factor = $height/$resizeheight;
                   2510:                 my $newwidth = $width/$factor;
                   2511:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2512:                 $resized = 1;
                   2513:             }
                   2514:         }
                   2515:         if ($resized) {
                   2516:             $ima->Write($img_path);
                   2517:         }
                   2518:     }
                   2519:     return;
1.977     amueller 2520: }
                   2521: 
1.608     albertel 2522: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2523: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2524: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2525: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2526: #                                    canceloverwrite, or ''. 
                   2527: #                   if 'coursedoc': upload to the current course
                   2528: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2529: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2530: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2531: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2532: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2533: #        $allfiles - reference to hash for embedded objects
                   2534: #        $codebase - reference to hash for codebase of java objects
                   2535: #        $desuname - username for permanent storage of uploaded file
                   2536: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2537: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2538: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2539: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2540: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2541: #        $mimetype - reference to scalar to accommodate mime type determined
                   2542: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2543: # 
1.686     albertel 2544: # output: url of file in userspace, or error: <message> 
                   2545: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2546: 
1.531     albertel 2547: sub userfileupload {
1.1090    raeburn  2548:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2549:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2550:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2551:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2552:     $fname=&clean_filename($fname);
1.1090    raeburn  2553:     # See if there is anything left
1.257     www      2554:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2555:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2556:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2557:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2558:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2559:         my $now = time;
1.1090    raeburn  2560:         my $filepath;
1.1095    raeburn  2561:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2562:              $filepath = 'tmp/helprequests/'.$now;
                   2563:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2564:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2565:                          '_'.$env{'user.domain'}.'/pending';
                   2566:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2567:             my ($docuname,$docudom);
                   2568:             if ($destudom) {
                   2569:                 $docudom = $destudom;
                   2570:             } else {
                   2571:                 $docudom = $env{'user.domain'};
                   2572:             }
                   2573:             if ($destuname) {
                   2574:                 $docuname = $destuname;
                   2575:             } else {
                   2576:                 $docuname = $env{'user.name'};
                   2577:             }
                   2578:             if (exists($env{'form.group'})) {
                   2579:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2580:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2581:             }
                   2582:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2583:             if ($context eq 'canceloverwrite') {
                   2584:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2585:                 if (-e  $tempfile) {
                   2586:                     my @info = stat($tempfile);
                   2587:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2588:                         unlink($tempfile);
                   2589:                     }
                   2590:                 }
                   2591:                 return;
1.523     raeburn  2592:             }
                   2593:         }
1.1090    raeburn  2594:         # Create the directory if not present
1.741     raeburn  2595:         my @parts=split(/\//,$filepath);
                   2596:         my $fullpath = $perlvar{'lonDaemons'};
                   2597:         for (my $i=0;$i<@parts;$i++) {
                   2598:             $fullpath .= '/'.$parts[$i];
                   2599:             if ((-e $fullpath)!=1) {
                   2600:                 mkdir($fullpath,0777);
                   2601:             }
                   2602:         }
                   2603:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2604:         print $fh $env{'form.'.$formname};
                   2605:         close($fh);
1.1090    raeburn  2606:         if ($context eq 'existingfile') {
                   2607:             my @info = stat($fullpath.'/'.$fname);
                   2608:             return ($fullpath.'/'.$fname,$info[9]);
                   2609:         } else {
                   2610:             return $fullpath.'/'.$fname;
                   2611:         }
1.523     raeburn  2612:     }
1.995     raeburn  2613:     if ($subdir eq 'scantron') {
                   2614:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2615:     } else {
1.995     raeburn  2616:         $fname="$subdir/$fname";
                   2617:     }
1.1090    raeburn  2618:     if ($context eq 'coursedoc') {
1.638     albertel 2619: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2620: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2621:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2622:             return &finishuserfileupload($docuname,$docudom,
                   2623: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2624: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2625:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2626:         } else {
1.620     albertel 2627:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2628:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2629: 				       $fname,$formname,$parser,
1.1095    raeburn  2630: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2631:         }
1.719     banghart 2632:     } elsif (defined($destuname)) {
                   2633:         my $docuname=$destuname;
                   2634:         my $docudom=$destudom;
1.860     raeburn  2635: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2636: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2637:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2638:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2639:     } else {
1.638     albertel 2640:         my $docuname=$env{'user.name'};
                   2641:         my $docudom=$env{'user.domain'};
1.714     raeburn  2642:         if (exists($env{'form.group'})) {
                   2643:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2644:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2645:         }
1.860     raeburn  2646: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2647: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2648:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2649:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2650:     }
1.271     www      2651: }
                   2652: 
                   2653: sub finishuserfileupload {
1.860     raeburn  2654:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2655:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2656:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2657:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2658:   
1.860     raeburn  2659:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2660:     $file=$fname;
                   2661:     if ($fname=~m|/|) {
                   2662:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2663: 	$path.=$fnamepath.'/';
                   2664:     }
1.259     www      2665:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2666:     my $count;
                   2667:     for ($count=4;$count<=$#parts;$count++) {
                   2668:         $filepath.="/$parts[$count]";
                   2669:         if ((-e $filepath)!=1) {
                   2670: 	    mkdir($filepath,0777);
                   2671:         }
                   2672:     }
1.984     neumanie 2673: 
1.258     www      2674: # Save the file
                   2675:     {
1.701     albertel 2676: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2677: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2678: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2679: 	    return '/adm/notfound.html';
                   2680: 	}
1.1090    raeburn  2681:         if ($context eq 'overwrite') {
1.1117    foxr     2682:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2683:             my $target = $filepath.'/'.$file;
                   2684:             if (-e $source) {
                   2685:                 my @info = stat($source);
                   2686:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2687:                     unless (&File::Copy::move($source,$target)) {
                   2688:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2689:                         return "Moving from $source failed";
                   2690:                     }
                   2691:                 } else {
                   2692:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2693:                 }
                   2694:             } else {
                   2695:                 return "Temporary file: $source missing";
                   2696:             }
                   2697:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2698: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2699: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2700: 	    return '/adm/notfound.html';
                   2701: 	}
1.570     albertel 2702: 	close(FH);
1.1051    raeburn  2703:         if ($resizewidth && $resizeheight) {
                   2704:             my $mm = new File::MMagic;
                   2705:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2706:             if ($mime_type =~ m{^image/}) {
                   2707: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2708:             }  
1.977     amueller 2709: 	}
1.258     www      2710:     }
1.637     raeburn  2711:     if ($parser eq 'parse') {
1.1024    raeburn  2712:         my $mm = new File::MMagic;
1.1095    raeburn  2713:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2714:         if ($type eq 'text/html') {
1.1024    raeburn  2715:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2716:                                                        $allfiles,$codebase);
                   2717:             unless ($parse_result eq 'ok') {
                   2718:                 &logthis('Failed to parse '.$filepath.$file.
                   2719: 	   	         ' for embedded media: '.$parse_result); 
                   2720:             }
1.637     raeburn  2721:         }
1.1095    raeburn  2722:         if (ref($mimetype)) {
                   2723:             $$mimetype = $type;
                   2724:         }
1.637     raeburn  2725:     }
1.860     raeburn  2726:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2727:         my $input = $filepath.'/'.$file;
                   2728:         my $output = $filepath.'/'.'tn-'.$file;
                   2729:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2730:         system("convert -sample $thumbsize $input $output");
                   2731:         if (-e $filepath.'/'.'tn-'.$file) {
                   2732:             $fetchthumb  = 1; 
                   2733:         }
                   2734:     }
1.858     raeburn  2735:  
1.259     www      2736: # Notify homeserver to grep it
                   2737: #
1.984     neumanie 2738:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2739:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2740:     if ($fetchresult eq 'ok') {
1.860     raeburn  2741:         if ($fetchthumb) {
                   2742:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2743:             if ($thumbresult ne 'ok') {
                   2744:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2745:                          $docuhome.': '.$thumbresult);
                   2746:             }
                   2747:         }
1.259     www      2748: #
1.258     www      2749: # Return the URL to it
1.494     albertel 2750:         return '/uploaded/'.$path.$file;
1.263     www      2751:     } else {
1.494     albertel 2752:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2753: 		 ': '.$fetchresult);
1.263     www      2754:         return '/adm/notfound.html';
1.858     raeburn  2755:     }
1.493     albertel 2756: }
                   2757: 
1.637     raeburn  2758: sub extract_embedded_items {
1.961     raeburn  2759:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2760:     my @state = ();
                   2761:     my %javafiles = (
                   2762:                       codebase => '',
                   2763:                       code => '',
                   2764:                       archive => ''
                   2765:                     );
                   2766:     my %mediafiles = (
                   2767:                       src => '',
                   2768:                       movie => '',
                   2769:                      );
1.648     raeburn  2770:     my $p;
                   2771:     if ($content) {
                   2772:         $p = HTML::LCParser->new($content);
                   2773:     } else {
1.961     raeburn  2774:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2775:     }
1.641     albertel 2776:     while (my $t=$p->get_token()) {
1.640     albertel 2777: 	if ($t->[0] eq 'S') {
                   2778: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2779: 	    push(@state, $tagname);
1.648     raeburn  2780:             if (lc($tagname) eq 'allow') {
                   2781:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2782:             }
1.640     albertel 2783: 	    if (lc($tagname) eq 'img') {
                   2784: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2785: 	    }
1.886     albertel 2786: 	    if (lc($tagname) eq 'a') {
                   2787: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2788: 	    }
1.645     raeburn  2789:             if (lc($tagname) eq 'script') {
                   2790:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2791:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2792:                 } else {
                   2793:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2794:                 }
                   2795:             }
                   2796:             if (lc($tagname) eq 'link') {
                   2797:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2798:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2799:                 }
                   2800:             }
1.640     albertel 2801: 	    if (lc($tagname) eq 'object' ||
                   2802: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2803: 		foreach my $item (keys(%javafiles)) {
                   2804: 		    $javafiles{$item} = '';
                   2805: 		}
                   2806: 	    }
                   2807: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2808: 		my $name = lc($attr->{'name'});
                   2809: 		foreach my $item (keys(%javafiles)) {
                   2810: 		    if ($name eq $item) {
                   2811: 			$javafiles{$item} = $attr->{'value'};
                   2812: 			last;
                   2813: 		    }
                   2814: 		}
                   2815: 		foreach my $item (keys(%mediafiles)) {
                   2816: 		    if ($name eq $item) {
                   2817: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2818: 			last;
                   2819: 		    }
                   2820: 		}
                   2821: 	    }
                   2822: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2823: 		foreach my $item (keys(%javafiles)) {
                   2824: 		    if ($attr->{$item}) {
                   2825: 			$javafiles{$item} = $attr->{$item};
                   2826: 			last;
                   2827: 		    }
                   2828: 		}
                   2829: 		foreach my $item (keys(%mediafiles)) {
                   2830: 		    if ($attr->{$item}) {
                   2831: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2832: 			last;
                   2833: 		    }
                   2834: 		}
                   2835: 	    }
                   2836: 	} elsif ($t->[0] eq 'E') {
                   2837: 	    my ($tagname) = ($t->[1]);
                   2838: 	    if ($javafiles{'codebase'} ne '') {
                   2839: 		$javafiles{'codebase'} .= '/';
                   2840: 	    }  
                   2841: 	    if (lc($tagname) eq 'applet' ||
                   2842: 		lc($tagname) eq 'object' ||
                   2843: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2844: 		) {
                   2845: 		foreach my $item (keys(%javafiles)) {
                   2846: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2847: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2848: 			&add_filetype($allfiles,$file,$item);
                   2849: 		    }
                   2850: 		}
                   2851: 	    } 
                   2852: 	    pop @state;
                   2853: 	}
                   2854:     }
1.637     raeburn  2855:     return 'ok';
                   2856: }
                   2857: 
1.639     albertel 2858: sub add_filetype {
                   2859:     my ($allfiles,$file,$type)=@_;
                   2860:     if (exists($allfiles->{$file})) {
                   2861: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2862: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2863: 	}
                   2864:     } else {
                   2865: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2866:     }
                   2867: }
                   2868: 
1.493     albertel 2869: sub removeuploadedurl {
1.984     neumanie 2870:     my ($url)=@_;	
                   2871:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2872:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2873: }
                   2874: 
                   2875: sub removeuserfile {
                   2876:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2877:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2878:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2879:     if ($result eq 'ok') {	
1.798     raeburn  2880:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2881:             my $metafile = $fname.'.meta';
                   2882:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2883: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2884:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2885:             my $sqlresult = 
1.823     albertel 2886:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2887:                                         'portfolio_metadata',$group,
                   2888:                                         'delete');
1.798     raeburn  2889:         }
                   2890:     }
                   2891:     return $result;
1.257     www      2892: }
1.15      www      2893: 
1.530     albertel 2894: sub mkdiruserfile {
                   2895:     my ($docuname,$docudom,$dir)=@_;
                   2896:     my $home=&homeserver($docuname,$docudom);
                   2897:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2898: }
                   2899: 
1.531     albertel 2900: sub renameuserfile {
                   2901:     my ($docuname,$docudom,$old,$new)=@_;
                   2902:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2903:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2904:                         &escape("$old").':'.&escape("$new"),$home);
                   2905:     if ($result eq 'ok') {
                   2906:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2907:             my $oldmeta = $old.'.meta';
                   2908:             my $newmeta = $new.'.meta';
                   2909:             my $metaresult = 
                   2910:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2911: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2912:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2913:             my $sqlresult = 
1.823     albertel 2914:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2915:                                         'portfolio_metadata',$group,
                   2916:                                         'delete');
1.798     raeburn  2917:         }
                   2918:     }
                   2919:     return $result;
1.531     albertel 2920: }
                   2921: 
1.14      www      2922: # ------------------------------------------------------------------------- Log
                   2923: 
                   2924: sub log {
                   2925:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2926:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2927: }
                   2928: 
                   2929: # ------------------------------------------------------------------ Course Log
1.352     www      2930: #
                   2931: # This routine flushes several buffers of non-mission-critical nature
                   2932: #
1.157     www      2933: 
                   2934: sub flushcourselogs {
1.352     www      2935:     &logthis('Flushing log buffers');
                   2936: #
                   2937: # course logs
                   2938: # This is a log of all transactions in a course, which can be used
                   2939: # for data mining purposes
                   2940: #
                   2941: # It also collects the courseid database, which lists last transaction
                   2942: # times and course titles for all courseids
                   2943: #
                   2944:     my %courseidbuffer=();
1.921     raeburn  2945:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2946:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2947: 		          &escape($courselogs{$crsid}),
                   2948: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2949: 	    delete $courselogs{$crsid};
                   2950:         } else {
                   2951:             &logthis('Failed to flush log buffer for '.$crsid);
                   2952:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2953:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2954:                         " exceeded maximum size, deleting.</font>");
                   2955:                delete $courselogs{$crsid};
                   2956:             }
1.352     www      2957:         }
1.920     raeburn  2958:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2959:             'description' => $coursedescrbuf{$crsid},
                   2960:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2961:             'type'        => $coursetypebuf{$crsid},
                   2962:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2963:         };
1.191     harris41 2964:     }
1.352     www      2965: #
                   2966: # Write course id database (reverse lookup) to homeserver of courses 
                   2967: # Is used in pickcourse
                   2968: #
1.840     albertel 2969:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2970:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2971:                                     $courseidbuffer{$crs_home},
                   2972:                                     $crs_home,'timeonly');
1.352     www      2973:     }
                   2974: #
                   2975: # File accesses
                   2976: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2977: #
1.449     matthew  2978:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2979:         if ($entry =~ /___count$/) {
                   2980:             my ($dom,$name);
1.807     albertel 2981:             ($dom,$name,undef)=
1.811     albertel 2982: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2983:             if (! defined($dom) || $dom eq '' || 
                   2984:                 ! defined($name) || $name eq '') {
1.620     albertel 2985:                 my $cid = $env{'request.course.id'};
                   2986:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2987:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2988:             }
1.450     matthew  2989:             my $value = $accesshash{$entry};
                   2990:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2991:             my %temphash=($url => $value);
1.449     matthew  2992:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2993:             if ($result eq 'ok') {
                   2994:                 delete $accesshash{$entry};
                   2995:             } elsif ($result eq 'unknown_cmd') {
                   2996:                 # Target server has old code running on it.
1.450     matthew  2997:                 my %temphash=($entry => $value);
1.449     matthew  2998:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2999:                     delete $accesshash{$entry};
                   3000:                 }
                   3001:             }
                   3002:         } else {
1.811     albertel 3003:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3004:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3005:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3006:                 delete $accesshash{$entry};
                   3007:             }
1.185     www      3008:         }
1.191     harris41 3009:     }
1.352     www      3010: #
                   3011: # Roles
                   3012: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3013: #
1.800     albertel 3014:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3015:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3016: 	    split(/\:/,$entry);
                   3017:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3018:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3019:                 $rudom,$runame) eq 'ok') {
                   3020: 	    delete $userrolehash{$entry};
                   3021:         }
                   3022:     }
1.662     raeburn  3023: #
                   3024: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3025: #
                   3026:     my %domrolebuffer = ();
1.1000    raeburn  3027:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3028:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3029:         if ($domrolebuffer{$rudom}) {
                   3030:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3031:                       '='.&escape($domainrolehash{$entry});
                   3032:         } else {
                   3033:             $domrolebuffer{$rudom}.=&escape($entry).
                   3034:                       '='.&escape($domainrolehash{$entry});
                   3035:         }
                   3036:         delete $domainrolehash{$entry};
                   3037:     }
                   3038:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3039: 	my %servers = &get_servers($dom,'library');
                   3040: 	foreach my $tryserver (keys(%servers)) {
                   3041: 	    unless (&reply('domroleput:'.$dom.':'.
                   3042: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3043: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3044: 	    }
1.662     raeburn  3045:         }
                   3046:     }
1.186     www      3047:     $dumpcount++;
1.157     www      3048: }
                   3049: 
                   3050: sub courselog {
                   3051:     my $what=shift;
1.158     www      3052:     $what=time.':'.$what;
1.620     albertel 3053:     unless ($env{'request.course.id'}) { return ''; }
                   3054:     $coursedombuf{$env{'request.course.id'}}=
                   3055:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3056:     $coursenumbuf{$env{'request.course.id'}}=
                   3057:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3058:     $coursehombuf{$env{'request.course.id'}}=
                   3059:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3060:     $coursedescrbuf{$env{'request.course.id'}}=
                   3061:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3062:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3063:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3064:     $courseownerbuf{$env{'request.course.id'}}=
                   3065:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3066:     $coursetypebuf{$env{'request.course.id'}}=
                   3067:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3068:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3069: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3070:     } else {
1.620     albertel 3071: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3072:     }
1.620     albertel 3073:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3074: 	&flushcourselogs();
                   3075:     }
1.158     www      3076: }
                   3077: 
                   3078: sub courseacclog {
                   3079:     my $fnsymb=shift;
1.620     albertel 3080:     unless ($env{'request.course.id'}) { return ''; }
                   3081:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3082:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3083:         $what.=':POST';
1.583     matthew  3084:         # FIXME: Probably ought to escape things....
1.800     albertel 3085: 	foreach my $key (keys(%env)) {
                   3086:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3087:                 my $formitem = $1;
                   3088:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3089:                     $what.=':'.$formitem.'='.$env{$key};
                   3090:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3091:                     $what.=':'.$formitem.'='.$env{$key};
                   3092:                 }
1.158     www      3093:             }
1.191     harris41 3094:         }
1.583     matthew  3095:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3096:         # FIXME: We should not be depending on a form parameter that someone
                   3097:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3098:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3099:             $what.= ':POST';
                   3100:             # FIXME: Probably ought to escape things....
                   3101:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3102:                                  'crsdiscuss') {
1.620     albertel 3103:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3104:             }
                   3105:         }
1.158     www      3106:     }
                   3107:     &courselog($what);
1.149     www      3108: }
                   3109: 
1.185     www      3110: sub countacc {
                   3111:     my $url=&declutter(shift);
1.458     matthew  3112:     return if (! defined($url) || $url eq '');
1.620     albertel 3113:     unless ($env{'request.course.id'}) { return ''; }
                   3114:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3115:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3116:     $accesshash{$key}++;
1.185     www      3117: }
1.349     www      3118: 
1.361     www      3119: sub linklog {
                   3120:     my ($from,$to)=@_;
                   3121:     $from=&declutter($from);
                   3122:     $to=&declutter($to);
                   3123:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3124:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3125: }
                   3126:   
1.349     www      3127: sub userrolelog {
                   3128:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3129:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3130:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3131:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3132:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3133:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3134:        $userrolehash
                   3135:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3136:                     =$tend.':'.$tstart;
1.662     raeburn  3137:     }
1.898     albertel 3138:     if (($env{'request.role'} =~ /dc\./) &&
                   3139: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3140: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3141: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3142:          ($trole=~/^co/))) {
1.898     albertel 3143:        $userrolehash
                   3144:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3145:                     =$tend.':'.$tstart;
                   3146:     }
1.662     raeburn  3147:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3148:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3149:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3150:         ($trole=~/^sc/)) {
                   3151:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3152:        $domainrolehash
                   3153:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3154:                     = $tend.':'.$tstart;
                   3155:     }
1.351     www      3156: }
                   3157: 
1.957     raeburn  3158: sub courserolelog {
                   3159:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3160:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3161:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3162:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3163:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3164:         ($trole eq 'co')) {
1.957     raeburn  3165:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3166:             my $cdom = $1;
                   3167:             my $cnum = $2;
                   3168:             my $sec = $3;
                   3169:             my $namespace = 'rolelog';
                   3170:             my %storehash = (
                   3171:                                role    => $trole,
                   3172:                                start   => $tstart,
                   3173:                                end     => $tend,
                   3174:                                selfenroll => $selfenroll,
                   3175:                                context    => $context,
                   3176:                             );
                   3177:             if ($trole eq 'gr') {
                   3178:                 $namespace = 'groupslog';
                   3179:                 $storehash{'group'} = $sec;
                   3180:             } else {
                   3181:                 $storehash{'section'} = $sec;
                   3182:             }
                   3183:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3184:             if (($trole ne 'st') || ($sec ne '')) {
                   3185:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3186:             }
1.957     raeburn  3187:         }
                   3188:     }
                   3189:     return;
                   3190: }
                   3191: 
1.351     www      3192: sub get_course_adv_roles {
1.948     raeburn  3193:     my ($cid,$codes) = @_;
1.620     albertel 3194:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3195:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3196:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3197:     my %nothide=();
1.800     albertel 3198:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3199:         if ($user !~ /:/) {
                   3200: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3201:         } else {
                   3202:             $nothide{$user}=1;
                   3203:         }
1.470     www      3204:     }
1.351     www      3205:     my %returnhash=();
                   3206:     my %dumphash=
                   3207:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3208:     my $now=time;
1.997     raeburn  3209:     my %privileged;
1.1000    raeburn  3210:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3211: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3212:         if (($tstart) && ($tstart<0)) { next; }
                   3213:         if (($tend) && ($tend<$now)) { next; }
                   3214:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3215:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3216: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3217:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3218:             my %dompersonnel =
1.998     raeburn  3219:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3220:             $privileged{$domain} = {};
                   3221:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3222:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3223:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3224:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3225:                         $privileged{$udom}{$uname} = 1;
                   3226:                     }
                   3227:                 }
                   3228:             }
                   3229:         }
                   3230:         if ((exists($privileged{$domain}{$username})) && 
                   3231:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3232: 	if ($role eq 'cr') { next; }
1.948     raeburn  3233:         if ($codes) {
                   3234:             if ($section) { $role .= ':'.$section; }
                   3235:             if ($returnhash{$role}) {
                   3236:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3237:             } else {
                   3238:                 $returnhash{$role}=$username.':'.$domain;
                   3239:             }
1.351     www      3240:         } else {
1.988     raeburn  3241:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3242:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3243:             if ($returnhash{$key}) {
                   3244: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3245:             } else {
                   3246:                 $returnhash{$key}=$username.':'.$domain;
                   3247:             }
1.351     www      3248:         }
1.948     raeburn  3249:     }
1.400     www      3250:     return %returnhash;
                   3251: }
                   3252: 
                   3253: sub get_my_roles {
1.937     raeburn  3254:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3255:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3256:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3257:     my (%dumphash,%nothide);
1.1086    raeburn  3258:     if ($context eq 'userroles') {
                   3259:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3260:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3261:     } else {
                   3262:         %dumphash=
1.400     www      3263:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3264:         if ($hidepriv) {
                   3265:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3266:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3267:                 if ($user !~ /:/) {
                   3268:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3269:                 } else {
                   3270:                     $nothide{$user} = 1;
                   3271:                 }
                   3272:             }
                   3273:         }
1.858     raeburn  3274:     }
1.400     www      3275:     my %returnhash=();
                   3276:     my $now=time;
1.999     raeburn  3277:     my %privileged;
1.800     albertel 3278:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3279:         my ($role,$tend,$tstart);
                   3280:         if ($context eq 'userroles') {
                   3281: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3282:         } else {
                   3283:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3284:         }
1.400     www      3285:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3286:         my $status = 'active';
1.939     raeburn  3287:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3288:             $status = 'previous';
                   3289:         } 
                   3290:         if (($tstart) && ($now<$tstart)) {
                   3291:             $status = 'future';
                   3292:         }
                   3293:         if (ref($types) eq 'ARRAY') {
                   3294:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3295:                 next;
                   3296:             } 
                   3297:         } else {
                   3298:             if ($status ne 'active') {
                   3299:                 next;
                   3300:             }
                   3301:         }
1.867     raeburn  3302:         my ($rolecode,$username,$domain,$section,$area);
                   3303:         if ($context eq 'userroles') {
                   3304:             ($area,$rolecode) = split(/_/,$entry);
                   3305:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3306:         } else {
                   3307:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3308:         }
1.832     raeburn  3309:         if (ref($roledoms) eq 'ARRAY') {
                   3310:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3311:                 next;
                   3312:             }
                   3313:         }
                   3314:         if (ref($roles) eq 'ARRAY') {
                   3315:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3316:                 if ($role =~ /^cr\//) {
                   3317:                     if (!grep(/^cr$/,@{$roles})) {
                   3318:                         next;
                   3319:                     }
1.1104    raeburn  3320:                 } elsif ($role =~ /^gr\//) {
                   3321:                     if (!grep(/^gr$/,@{$roles})) {
                   3322:                         next;
                   3323:                     }
1.922     raeburn  3324:                 } else {
                   3325:                     next;
                   3326:                 }
1.832     raeburn  3327:             }
1.867     raeburn  3328:         }
1.937     raeburn  3329:         if ($hidepriv) {
1.999     raeburn  3330:             if ($context eq 'userroles') {
                   3331:                 if ((&privileged($username,$domain)) &&
                   3332:                     (!$nothide{$username.':'.$domain})) {
                   3333:                     next;
                   3334:                 }
                   3335:             } else {
                   3336:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3337:                     my %dompersonnel =
                   3338:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3339:                     $privileged{$domain} = {};
                   3340:                     if (keys(%dompersonnel)) {
                   3341:                         foreach my $server (keys(%dompersonnel)) {
                   3342:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3343:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3344:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3345:                                     $privileged{$udom}{$uname} = $trole;
                   3346:                                 }
                   3347:                             }
                   3348:                         }
                   3349:                     }
                   3350:                 }
                   3351:                 if (exists($privileged{$domain}{$username})) {
                   3352:                     if (!$nothide{$username.':'.$domain}) {
                   3353:                         next;
                   3354:                     }
                   3355:                 }
1.937     raeburn  3356:             }
                   3357:         }
1.933     raeburn  3358:         if ($withsec) {
                   3359:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3360:                 $tstart.':'.$tend;
                   3361:         } else {
                   3362:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3363:         }
1.832     raeburn  3364:     }
1.373     www      3365:     return %returnhash;
1.399     www      3366: }
                   3367: 
                   3368: # ----------------------------------------------------- Frontpage Announcements
                   3369: #
                   3370: #
                   3371: 
                   3372: sub postannounce {
                   3373:     my ($server,$text)=@_;
1.844     albertel 3374:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3375:     unless ($text=~/\w/) { $text=''; }
                   3376:     return &reply('setannounce:'.&escape($text),$server);
                   3377: }
                   3378: 
                   3379: sub getannounce {
1.448     albertel 3380: 
                   3381:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3382: 	my $announcement='';
1.800     albertel 3383: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3384: 	close($fh);
1.399     www      3385: 	if ($announcement=~/\w/) { 
                   3386: 	    return 
                   3387:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3388:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3389: 	} else {
                   3390: 	    return '';
                   3391: 	}
                   3392:     } else {
                   3393: 	return '';
                   3394:     }
1.351     www      3395: }
1.353     www      3396: 
                   3397: # ---------------------------------------------------------- Course ID routines
                   3398: # Deal with domain's nohist_courseid.db files
                   3399: #
                   3400: 
                   3401: sub courseidput {
1.921     raeburn  3402:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3403:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3404:     my $outcome;
                   3405:     if ($caller eq 'timeonly') {
                   3406:         my $cids = '';
                   3407:         foreach my $item (keys(%$storehash)) {
                   3408:             $cids.=&escape($item).'&';
                   3409:         }
                   3410:         $cids=~s/\&$//;
                   3411:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3412:                           $coursehome);       
                   3413:     } else {
                   3414:         my $items = '';
                   3415:         foreach my $item (keys(%$storehash)) {
                   3416:             $items.= &escape($item).'='.
                   3417:                      &freeze_escape($$storehash{$item}).'&';
                   3418:         }
                   3419:         $items=~s/\&$//;
                   3420:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3421:                           $coursehome);
1.918     raeburn  3422:     }
                   3423:     if ($outcome eq 'unknown_cmd') {
                   3424:         my $what;
                   3425:         foreach my $cid (keys(%$storehash)) {
                   3426:             $what .= &escape($cid).'=';
1.921     raeburn  3427:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3428:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3429:             }
                   3430:             $what =~ s/\:$/&/;
                   3431:         }
                   3432:         $what =~ s/\&$//;  
                   3433:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3434:     } else {
                   3435:         return $outcome;
                   3436:     }
1.353     www      3437: }
                   3438: 
                   3439: sub courseiddump {
1.921     raeburn  3440:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3441:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3442:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3443:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3444:     my $as_hash = 1;
                   3445:     my %returnhash;
                   3446:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3447:     my %libserv = &all_library();
                   3448:     foreach my $tryserver (keys(%libserv)) {
                   3449:         if ( (  $hostidflag == 1 
                   3450: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3451: 	     || (!defined($hostidflag)) ) {
                   3452: 
1.918     raeburn  3453: 	    if (($domfilter eq '') ||
                   3454: 		(&host_domain($tryserver) eq $domfilter)) {
                   3455:                 my $rep = 
                   3456:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3457:                          $sincefilter.':'.&escape($descfilter).':'.
                   3458:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3459:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3460:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3461:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3462:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3463:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3464:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3465:                          &escape($creationcontext).':'.$domcloner,
                   3466:                          $tryserver);
1.918     raeburn  3467:                 my @pairs=split(/\&/,$rep);
                   3468:                 foreach my $item (@pairs) {
                   3469:                     my ($key,$value)=split(/\=/,$item,2);
                   3470:                     $key = &unescape($key);
                   3471:                     next if ($key =~ /^error: 2 /);
                   3472:                     my $result = &thaw_unescape($value);
                   3473:                     if (ref($result) eq 'HASH') {
                   3474:                         $returnhash{$key}=$result;
                   3475:                     } else {
1.921     raeburn  3476:                         my @responses = split(/:/,$value);
                   3477:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3478:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3479:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3480:                         }
1.1008    raeburn  3481:                     }
1.353     www      3482:                 }
                   3483:             }
                   3484:         }
                   3485:     }
                   3486:     return %returnhash;
                   3487: }
                   3488: 
1.1055    raeburn  3489: sub courselastaccess {
                   3490:     my ($cdom,$cnum,$hostidref) = @_;
                   3491:     my %returnhash;
                   3492:     if ($cdom && $cnum) {
                   3493:         my $chome = &homeserver($cnum,$cdom);
                   3494:         if ($chome ne 'no_host') {
                   3495:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3496:             &extract_lastaccess(\%returnhash,$rep);
                   3497:         }
                   3498:     } else {
                   3499:         if (!$cdom) { $cdom=''; }
                   3500:         my %libserv = &all_library();
                   3501:         foreach my $tryserver (keys(%libserv)) {
                   3502:             if (ref($hostidref) eq 'ARRAY') {
                   3503:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3504:             } 
                   3505:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3506:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3507:                 &extract_lastaccess(\%returnhash,$rep);
                   3508:             }
                   3509:         }
                   3510:     }
                   3511:     return %returnhash;
                   3512: }
                   3513: 
                   3514: sub extract_lastaccess {
                   3515:     my ($returnhash,$rep) = @_;
                   3516:     if (ref($returnhash) eq 'HASH') {
                   3517:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3518:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3519:                  $rep eq '') {
                   3520:             my @pairs=split(/\&/,$rep);
                   3521:             foreach my $item (@pairs) {
                   3522:                 my ($key,$value)=split(/\=/,$item,2);
                   3523:                 $key = &unescape($key);
                   3524:                 next if ($key =~ /^error: 2 /);
                   3525:                 $returnhash->{$key} = &thaw_unescape($value);
                   3526:             }
                   3527:         }
                   3528:     }
                   3529:     return;
                   3530: }
                   3531: 
1.658     raeburn  3532: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3533: 
                   3534: sub dcmailput {
1.685     raeburn  3535:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3536:     my $status = &Apache::lonnet::critical(
1.740     www      3537:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3538:        &escape($message),$server);
1.662     raeburn  3539:     return $status;
                   3540: }
                   3541: 
1.658     raeburn  3542: sub dcmaildump {
                   3543:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3544:     my %returnhash=();
1.846     albertel 3545: 
                   3546:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3547:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3548:                                                          &escape($enddate).':';
                   3549: 	my @esc_senders=map { &escape($_)} @$senders;
                   3550: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3551: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3552:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3553:             if (($key) && ($value)) {
                   3554:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3555:             }
                   3556:         }
                   3557:     }
                   3558:     return %returnhash;
                   3559: }
1.662     raeburn  3560: # ---------------------------------------------------------- Domain roles
                   3561: 
                   3562: sub get_domain_roles {
                   3563:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3564:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3565:         $startdate = '.';
                   3566:     }
1.1018    raeburn  3567:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3568:         $enddate = '.';
                   3569:     }
1.922     raeburn  3570:     my $rolelist;
                   3571:     if (ref($roles) eq 'ARRAY') {
                   3572:         $rolelist = join(':',@{$roles});
                   3573:     }
1.662     raeburn  3574:     my %personnel = ();
1.841     albertel 3575: 
                   3576:     my %servers = &get_servers($dom,'library');
                   3577:     foreach my $tryserver (keys(%servers)) {
                   3578: 	%{$personnel{$tryserver}}=();
                   3579: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3580: 					    &escape($startdate).':'.
                   3581: 					    &escape($enddate).':'.
                   3582: 					    &escape($rolelist), $tryserver))) {
                   3583: 	    my ($key,$value) = split(/\=/,$line,2);
                   3584: 	    if (($key) && ($value)) {
                   3585: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3586: 	    }
                   3587: 	}
1.662     raeburn  3588:     }
                   3589:     return %personnel;
                   3590: }
1.658     raeburn  3591: 
1.1057    www      3592: # ----------------------------------------------------------- Interval timing 
1.149     www      3593: 
1.504     albertel 3594: sub get_first_access {
                   3595:     my ($type,$argsymb)=@_;
1.790     albertel 3596:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3597:     if ($argsymb) { $symb=$argsymb; }
                   3598:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3599:     if ($type eq 'course') {
                   3600: 	$res='course';
                   3601:     } elsif ($type eq 'map') {
1.588     albertel 3602: 	$res=&symbread($map);
                   3603:     } else {
                   3604: 	$res=$symb;
                   3605:     }
                   3606:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3607:     return $times{"$courseid\0$res"};
1.504     albertel 3608: }
                   3609: 
                   3610: sub set_first_access {
                   3611:     my ($type)=@_;
1.790     albertel 3612:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3613:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3614:     if ($type eq 'course') {
                   3615: 	$res='course';
                   3616:     } elsif ($type eq 'map') {
1.588     albertel 3617: 	$res=&symbread($map);
                   3618:     } else {
                   3619: 	$res=$symb;
                   3620:     }
                   3621:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3622:     if (!$firstaccess) {
1.588     albertel 3623: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3624:     }
                   3625:     return 'already_set';
1.504     albertel 3626: }
                   3627: 
1.110     www      3628: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3629: 
                   3630: sub expirespread {
                   3631:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3632:     my $cid=$env{'request.course.id'}; 
1.110     www      3633:     if ($cid) {
                   3634:        my $now=time;
                   3635:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3636:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3637:                             $env{'course.'.$cid.'.num'}.
1.110     www      3638: 	        	    ':nohist_expirationdates:'.
                   3639:                             &escape($key).'='.$now,
1.620     albertel 3640:                             $env{'course.'.$cid.'.home'})
1.110     www      3641:     }
                   3642:     return 'ok';
1.14      www      3643: }
                   3644: 
1.109     www      3645: # ----------------------------------------------------- Devalidate Spreadsheets
                   3646: 
                   3647: sub devalidate {
1.325     www      3648:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3649:     my $cid=$env{'request.course.id'}; 
1.109     www      3650:     if ($cid) {
1.391     matthew  3651:         # delete the stored spreadsheets for
                   3652:         # - the student level sheet of this user in course's homespace
                   3653:         # - the assessment level sheet for this resource 
                   3654:         #   for this user in user's homespace
1.553     albertel 3655: 	# - current conditional state info
1.325     www      3656: 	my $key=$uname.':'.$udom.':';
1.109     www      3657:         my $status=
1.299     matthew  3658: 	    &del('nohist_calculatedsheets',
1.391     matthew  3659: 		 [$key.'studentcalc:'],
1.620     albertel 3660: 		 $env{'course.'.$cid.'.domain'},
                   3661: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3662: 		.' '.
                   3663: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3664: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3665:         unless ($status eq 'ok ok') {
                   3666:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3667:                     $uname.' at '.$udom.' for '.
1.109     www      3668: 		    $symb.': '.$status);
1.133     albertel 3669:         }
1.553     albertel 3670: 	&delenv('user.state.'.$cid);
1.109     www      3671:     }
                   3672: }
                   3673: 
1.265     albertel 3674: sub get_scalar {
                   3675:     my ($string,$end) = @_;
                   3676:     my $value;
                   3677:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3678: 	$value = $1;
                   3679:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3680: 	$value = $1;
                   3681:     }
                   3682:     return &unescape($value);
                   3683: }
                   3684: 
                   3685: sub array2str {
                   3686:   my (@array) = @_;
                   3687:   my $result=&arrayref2str(\@array);
                   3688:   $result=~s/^__ARRAY_REF__//;
                   3689:   $result=~s/__END_ARRAY_REF__$//;
                   3690:   return $result;
                   3691: }
                   3692: 
1.204     albertel 3693: sub arrayref2str {
                   3694:   my ($arrayref) = @_;
1.265     albertel 3695:   my $result='__ARRAY_REF__';
1.204     albertel 3696:   foreach my $elem (@$arrayref) {
1.265     albertel 3697:     if(ref($elem) eq 'ARRAY') {
                   3698:       $result.=&arrayref2str($elem).'&';
                   3699:     } elsif(ref($elem) eq 'HASH') {
                   3700:       $result.=&hashref2str($elem).'&';
                   3701:     } elsif(ref($elem)) {
                   3702:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3703:     } else {
                   3704:       $result.=&escape($elem).'&';
                   3705:     }
                   3706:   }
                   3707:   $result=~s/\&$//;
1.265     albertel 3708:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3709:   return $result;
                   3710: }
                   3711: 
1.168     albertel 3712: sub hash2str {
1.204     albertel 3713:   my (%hash) = @_;
                   3714:   my $result=&hashref2str(\%hash);
1.265     albertel 3715:   $result=~s/^__HASH_REF__//;
                   3716:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3717:   return $result;
                   3718: }
                   3719: 
                   3720: sub hashref2str {
                   3721:   my ($hashref)=@_;
1.265     albertel 3722:   my $result='__HASH_REF__';
1.800     albertel 3723:   foreach my $key (sort(keys(%$hashref))) {
                   3724:     if (ref($key) eq 'ARRAY') {
                   3725:       $result.=&arrayref2str($key).'=';
                   3726:     } elsif (ref($key) eq 'HASH') {
                   3727:       $result.=&hashref2str($key).'=';
                   3728:     } elsif (ref($key)) {
1.265     albertel 3729:       $result.='=';
1.800     albertel 3730:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3731:     } else {
1.800     albertel 3732: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3733:     }
                   3734: 
1.800     albertel 3735:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3736:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3737:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3738:       $result.=&hashref2str($hashref->{$key}).'&';
                   3739:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3740:        $result.='&';
1.800     albertel 3741:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3742:     } else {
1.800     albertel 3743:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3744:     }
                   3745:   }
1.168     albertel 3746:   $result=~s/\&$//;
1.265     albertel 3747:   $result .= '__END_HASH_REF__';
1.168     albertel 3748:   return $result;
                   3749: }
                   3750: 
                   3751: sub str2hash {
1.265     albertel 3752:     my ($string)=@_;
                   3753:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3754:     return %$hash;
                   3755: }
                   3756: 
                   3757: sub str2hashref {
1.168     albertel 3758:   my ($string) = @_;
1.265     albertel 3759: 
                   3760:   my %hash;
                   3761: 
                   3762:   if($string !~ /^__HASH_REF__/) {
                   3763:       if (! ($string eq '' || !defined($string))) {
                   3764: 	  $hash{'error'}='Not hash reference';
                   3765:       }
                   3766:       return (\%hash, $string);
                   3767:   }
                   3768: 
                   3769:   $string =~ s/^__HASH_REF__//;
                   3770: 
                   3771:   while($string !~ /^__END_HASH_REF__/) {
                   3772:       #key
                   3773:       my $key='';
                   3774:       if($string =~ /^__HASH_REF__/) {
                   3775:           ($key, $string)=&str2hashref($string);
                   3776:           if(defined($key->{'error'})) {
                   3777:               $hash{'error'}='Bad data';
                   3778:               return (\%hash, $string);
                   3779:           }
                   3780:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3781:           ($key, $string)=&str2arrayref($string);
                   3782:           if($key->[0] eq 'Array reference error') {
                   3783:               $hash{'error'}='Bad data';
                   3784:               return (\%hash, $string);
                   3785:           }
                   3786:       } else {
                   3787:           $string =~ s/^(.*?)=//;
1.267     albertel 3788: 	  $key=&unescape($1);
1.265     albertel 3789:       }
                   3790:       $string =~ s/^=//;
                   3791: 
                   3792:       #value
                   3793:       my $value='';
                   3794:       if($string =~ /^__HASH_REF__/) {
                   3795:           ($value, $string)=&str2hashref($string);
                   3796:           if(defined($value->{'error'})) {
                   3797:               $hash{'error'}='Bad data';
                   3798:               return (\%hash, $string);
                   3799:           }
                   3800:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3801:           ($value, $string)=&str2arrayref($string);
                   3802:           if($value->[0] eq 'Array reference error') {
                   3803:               $hash{'error'}='Bad data';
                   3804:               return (\%hash, $string);
                   3805:           }
                   3806:       } else {
                   3807: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3808:       }
                   3809:       $string =~ s/^&//;
                   3810: 
                   3811:       $hash{$key}=$value;
1.204     albertel 3812:   }
1.265     albertel 3813: 
                   3814:   $string =~ s/^__END_HASH_REF__//;
                   3815: 
                   3816:   return (\%hash, $string);
1.204     albertel 3817: }
                   3818: 
                   3819: sub str2array {
1.265     albertel 3820:     my ($string)=@_;
                   3821:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3822:     return @$array;
                   3823: }
                   3824: 
                   3825: sub str2arrayref {
1.204     albertel 3826:   my ($string) = @_;
1.265     albertel 3827:   my @array;
                   3828: 
                   3829:   if($string !~ /^__ARRAY_REF__/) {
                   3830:       if (! ($string eq '' || !defined($string))) {
                   3831: 	  $array[0]='Array reference error';
                   3832:       }
                   3833:       return (\@array, $string);
                   3834:   }
                   3835: 
                   3836:   $string =~ s/^__ARRAY_REF__//;
                   3837: 
                   3838:   while($string !~ /^__END_ARRAY_REF__/) {
                   3839:       my $value='';
                   3840:       if($string =~ /^__HASH_REF__/) {
                   3841:           ($value, $string)=&str2hashref($string);
                   3842:           if(defined($value->{'error'})) {
                   3843:               $array[0] ='Array reference error';
                   3844:               return (\@array, $string);
                   3845:           }
                   3846:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3847:           ($value, $string)=&str2arrayref($string);
                   3848:           if($value->[0] eq 'Array reference error') {
                   3849:               $array[0] ='Array reference error';
                   3850:               return (\@array, $string);
                   3851:           }
                   3852:       } else {
                   3853: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3854:       }
                   3855:       $string =~ s/^&//;
                   3856: 
                   3857:       push(@array, $value);
1.191     harris41 3858:   }
1.265     albertel 3859: 
                   3860:   $string =~ s/^__END_ARRAY_REF__//;
                   3861: 
                   3862:   return (\@array, $string);
1.168     albertel 3863: }
                   3864: 
1.167     albertel 3865: # -------------------------------------------------------------------Temp Store
                   3866: 
1.168     albertel 3867: sub tmpreset {
                   3868:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3869:   if (!$symb) {
                   3870:     $symb=&symbread();
1.620     albertel 3871:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3872:   }
                   3873:   $symb=escape($symb);
                   3874: 
1.620     albertel 3875:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3876:   $namespace=~s/\//\_/g;
                   3877:   $namespace=~s/\W//g;
                   3878: 
1.620     albertel 3879:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3880:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3881:   if ($domain eq 'public' && $stuname eq 'public') {
                   3882:       $stuname=$ENV{'REMOTE_ADDR'};
                   3883:   }
1.1117    foxr     3884:   my $path=LONCAPA::tempdir();
1.168     albertel 3885:   my %hash;
                   3886:   if (tie(%hash,'GDBM_File',
                   3887: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3888: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3889:     foreach my $key (keys(%hash)) {
1.180     albertel 3890:       if ($key=~ /:$symb/) {
1.168     albertel 3891: 	delete($hash{$key});
                   3892:       }
                   3893:     }
                   3894:   }
                   3895: }
                   3896: 
1.167     albertel 3897: sub tmpstore {
1.168     albertel 3898:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3899: 
                   3900:   if (!$symb) {
                   3901:     $symb=&symbread();
1.620     albertel 3902:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3903:   }
                   3904:   $symb=escape($symb);
                   3905: 
                   3906:   if (!$namespace) {
                   3907:     # I don't think we would ever want to store this for a course.
                   3908:     # it seems this will only be used if we don't have a course.
1.620     albertel 3909:     #$namespace=$env{'request.course.id'};
1.168     albertel 3910:     #if (!$namespace) {
1.620     albertel 3911:       $namespace=$env{'request.state'};
1.168     albertel 3912:     #}
                   3913:   }
                   3914:   $namespace=~s/\//\_/g;
                   3915:   $namespace=~s/\W//g;
1.620     albertel 3916:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3917:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3918:   if ($domain eq 'public' && $stuname eq 'public') {
                   3919:       $stuname=$ENV{'REMOTE_ADDR'};
                   3920:   }
1.168     albertel 3921:   my $now=time;
                   3922:   my %hash;
1.1117    foxr     3923:   my $path=LONCAPA::tempdir();
1.168     albertel 3924:   if (tie(%hash,'GDBM_File',
                   3925: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3926: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3927:     $hash{"version:$symb"}++;
                   3928:     my $version=$hash{"version:$symb"};
                   3929:     my $allkeys=''; 
                   3930:     foreach my $key (keys(%$storehash)) {
                   3931:       $allkeys.=$key.':';
1.591     albertel 3932:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3933:     }
                   3934:     $hash{"$version:$symb:timestamp"}=$now;
                   3935:     $allkeys.='timestamp';
                   3936:     $hash{"$version:keys:$symb"}=$allkeys;
                   3937:     if (untie(%hash)) {
                   3938:       return 'ok';
                   3939:     } else {
                   3940:       return "error:$!";
                   3941:     }
                   3942:   } else {
                   3943:     return "error:$!";
                   3944:   }
                   3945: }
1.167     albertel 3946: 
1.168     albertel 3947: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3948: 
1.168     albertel 3949: sub tmprestore {
                   3950:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3951: 
1.168     albertel 3952:   if (!$symb) {
                   3953:     $symb=&symbread();
1.620     albertel 3954:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3955:   }
                   3956:   $symb=escape($symb);
                   3957: 
1.620     albertel 3958:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3959: 
1.620     albertel 3960:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3961:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3962:   if ($domain eq 'public' && $stuname eq 'public') {
                   3963:       $stuname=$ENV{'REMOTE_ADDR'};
                   3964:   }
1.168     albertel 3965:   my %returnhash;
                   3966:   $namespace=~s/\//\_/g;
                   3967:   $namespace=~s/\W//g;
                   3968:   my %hash;
1.1117    foxr     3969:   my $path=LONCAPA::tempdir();
1.168     albertel 3970:   if (tie(%hash,'GDBM_File',
                   3971: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3972: 	  &GDBM_READER(),0640)) {
1.168     albertel 3973:     my $version=$hash{"version:$symb"};
                   3974:     $returnhash{'version'}=$version;
                   3975:     my $scope;
                   3976:     for ($scope=1;$scope<=$version;$scope++) {
                   3977:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3978:       my @keys=split(/:/,$vkeys);
                   3979:       my $key;
                   3980:       $returnhash{"$scope:keys"}=$vkeys;
                   3981:       foreach $key (@keys) {
1.591     albertel 3982: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3983: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3984:       }
                   3985:     }
1.168     albertel 3986:     if (!(untie(%hash))) {
                   3987:       return "error:$!";
                   3988:     }
                   3989:   } else {
                   3990:     return "error:$!";
                   3991:   }
                   3992:   return %returnhash;
1.167     albertel 3993: }
                   3994: 
1.9       www      3995: # ----------------------------------------------------------------------- Store
                   3996: 
                   3997: sub store {
1.124     www      3998:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3999:     my $home='';
                   4000: 
1.168     albertel 4001:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4002: 
1.213     www      4003:     $symb=&symbclean($symb);
1.122     albertel 4004:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4005: 
1.620     albertel 4006:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4007:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4008: 
                   4009:     &devalidate($symb,$stuname,$domain);
1.109     www      4010: 
                   4011:     $symb=escape($symb);
1.187     www      4012:     if (!$namespace) { 
1.620     albertel 4013:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4014:           return ''; 
                   4015:        } 
                   4016:     }
1.620     albertel 4017:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4018: 
                   4019:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4020:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4021: 
1.12      www      4022:     my $namevalue='';
1.800     albertel 4023:     foreach my $key (keys(%$storehash)) {
                   4024:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4025:     }
1.12      www      4026:     $namevalue=~s/\&$//;
1.187     www      4027:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4028:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4029: }
                   4030: 
1.47      www      4031: # -------------------------------------------------------------- Critical Store
                   4032: 
                   4033: sub cstore {
1.124     www      4034:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4035:     my $home='';
                   4036: 
1.168     albertel 4037:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4038: 
1.213     www      4039:     $symb=&symbclean($symb);
1.122     albertel 4040:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4041: 
1.620     albertel 4042:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4043:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4044: 
                   4045:     &devalidate($symb,$stuname,$domain);
1.109     www      4046: 
                   4047:     $symb=escape($symb);
1.187     www      4048:     if (!$namespace) { 
1.620     albertel 4049:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4050:           return ''; 
                   4051:        } 
                   4052:     }
1.620     albertel 4053:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4054: 
                   4055:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4056:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4057: 
1.47      www      4058:     my $namevalue='';
1.800     albertel 4059:     foreach my $key (keys(%$storehash)) {
                   4060:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4061:     }
1.47      www      4062:     $namevalue=~s/\&$//;
1.187     www      4063:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4064:     return critical
                   4065:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4066: }
                   4067: 
1.9       www      4068: # --------------------------------------------------------------------- Restore
                   4069: 
                   4070: sub restore {
1.124     www      4071:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4072:     my $home='';
                   4073: 
1.168     albertel 4074:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4075: 
1.122     albertel 4076:     if (!$symb) {
                   4077:       unless ($symb=escape(&symbread())) { return ''; }
                   4078:     } else {
1.213     www      4079:       $symb=&escape(&symbclean($symb));
1.122     albertel 4080:     }
1.188     www      4081:     if (!$namespace) { 
1.620     albertel 4082:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4083:           return ''; 
                   4084:        } 
                   4085:     }
1.620     albertel 4086:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4087:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4088:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4089:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4090: 
1.12      www      4091:     my %returnhash=();
1.800     albertel 4092:     foreach my $line (split(/\&/,$answer)) {
                   4093: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4094:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4095:     }
1.75      www      4096:     my $version;
                   4097:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4098:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4099:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4100:        }
1.75      www      4101:     }
1.13      www      4102:     return %returnhash;
1.34      www      4103: }
                   4104: 
                   4105: # ---------------------------------------------------------- Course Description
1.1118    foxr     4106: #
                   4107: #  
1.34      www      4108: 
                   4109: sub coursedescription {
1.731     albertel 4110:     my ($courseid,$args)=@_;
1.34      www      4111:     $courseid=~s/^\///;
1.49      www      4112:     $courseid=~s/\_/\//g;
1.34      www      4113:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4114:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4115:     my $normalid=$cdomain.'_'.$cnum;
                   4116:     # need to always cache even if we get errors otherwise we keep 
                   4117:     # trying and trying and trying to get the course description.
                   4118:     my %envhash=();
                   4119:     my %returnhash=();
1.731     albertel 4120:     
                   4121:     my $expiretime=600;
                   4122:     if ($env{'request.course.id'} eq $normalid) {
                   4123: 	$expiretime=120;
                   4124:     }
                   4125: 
                   4126:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4127:     if (!$args->{'freshen_cache'}
                   4128: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4129: 	foreach my $key (keys(%env)) {
                   4130: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4131: 	    my ($setting) = $1;
                   4132: 	    $returnhash{$setting} = $env{$key};
                   4133: 	}
                   4134: 	return %returnhash;
                   4135:     }
                   4136: 
1.1118    foxr     4137:     # get the data again
                   4138: 
1.731     albertel 4139:     if (!$args->{'one_time'}) {
                   4140: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4141:     }
1.811     albertel 4142: 
1.34      www      4143:     if ($chome ne 'no_host') {
1.302     albertel 4144:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4145:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4146: 	   my $username = $env{'user.name'}; # Defult username
                   4147: 	   if(defined $args->{'user'}) {
                   4148: 	       $username = $args->{'user'};
                   4149: 	   }
1.129     albertel 4150:            $returnhash{'home'}= $chome;
                   4151: 	   $returnhash{'domain'} = $cdomain;
                   4152: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4153:            if (!defined($returnhash{'type'})) {
                   4154:                $returnhash{'type'} = 'Course';
                   4155:            }
1.130     albertel 4156:            while (my ($name,$value) = each %returnhash) {
1.53      www      4157:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4158:            }
1.270     www      4159:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4160:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4161: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4162:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4163:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4164:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4165:        }
                   4166:     }
1.731     albertel 4167:     if (!$args->{'one_time'}) {
1.949     raeburn  4168: 	&appenv(\%envhash);
1.731     albertel 4169:     }
1.302     albertel 4170:     return %returnhash;
1.461     www      4171: }
                   4172: 
1.1080    raeburn  4173: sub update_released_required {
                   4174:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4175:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4176:         $cid = $env{'request.course.id'};
                   4177:         $cdom = $env{'course.'.$cid.'.domain'};
                   4178:         $cnum = $env{'course.'.$cid.'.num'};
                   4179:         $chome = $env{'course.'.$cid.'.home'};
                   4180:     }
                   4181:     if ($needsrelease) {
                   4182:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4183:         my $needsupdate;
                   4184:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4185:             $needsupdate = 1;
                   4186:         } else {
                   4187:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4188:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4189:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4190:                 $needsupdate = 1;
                   4191:             }
                   4192:         }
                   4193:         if ($needsupdate) {
                   4194:             my %needshash = (
                   4195:                              'internal.releaserequired' => $needsrelease,
                   4196:                             );
                   4197:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4198:             if ($putresult eq 'ok') {
                   4199:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4200:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4201:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4202:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4203:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4204:                 }
                   4205:             }
                   4206:         }
                   4207:     }
                   4208:     return;
                   4209: }
                   4210: 
1.461     www      4211: # -------------------------------------------------See if a user is privileged
                   4212: 
                   4213: sub privileged {
                   4214:     my ($username,$domain)=@_;
                   4215:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4216: 			&homeserver($username,$domain));
1.1033    raeburn  4217:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4218:         ($rolesdump =~ /^error:/)) {
                   4219:         return 0;
                   4220:     }
1.461     www      4221:     my $now=time;
                   4222:     if ($rolesdump ne '') {
1.800     albertel 4223:         foreach my $entry (split(/&/,$rolesdump)) {
                   4224: 	    if ($entry!~/^rolesdef_/) {
                   4225: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4226: 		$area=~s/\_\w\w$//;
                   4227: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4228: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4229: 		    my $active=1;
                   4230: 		    if ($tend) {
                   4231: 			if ($tend<$now) { $active=0; }
                   4232: 		    }
                   4233: 		    if ($tstart) {
                   4234: 			if ($tstart>$now) { $active=0; }
                   4235: 		    }
                   4236: 		    if ($active) { return 1; }
                   4237: 		}
                   4238: 	    }
                   4239: 	}
                   4240:     }
                   4241:     return 0;
1.9       www      4242: }
1.1       albertel 4243: 
1.103     harris41 4244: # -------------------------------------------------------- Get user privileges
1.11      www      4245: 
                   4246: sub rolesinit {
                   4247:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4248:     my $now=time;
                   4249:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4250:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4251:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4252:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4253:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4254:         return \%userroles;
                   4255:     }
1.11      www      4256:     my %allroles=();
1.678     raeburn  4257:     my %allgroups=();   
1.11      www      4258: 
                   4259:     if ($rolesdump ne '') {
1.800     albertel 4260:         foreach my $entry (split(/&/,$rolesdump)) {
                   4261: 	  if ($entry!~/^rolesdef_/) {
                   4262:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4263: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4264:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4265: 	    if ($role=~/^cr/) { 
1.807     albertel 4266: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4267: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4268: 		    ($tend,$tstart)=split('_',$trest);
                   4269: 		} else {
                   4270: 		    $trole=$role;
                   4271: 		}
1.678     raeburn  4272:             } elsif ($role =~ m|^gr/|) {
                   4273:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4274:                 next if ($tstart eq '-1');
1.678     raeburn  4275:                 ($trole,$group_privs) = split(/\//,$trole);
                   4276:                 $group_privs = &unescape($group_privs);
1.587     albertel 4277: 	    } else {
                   4278: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4279: 	    }
1.743     albertel 4280: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4281: 					 $username);
                   4282: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4283:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4284:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4285:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4286: 		my $spec=$trole.'.'.$area;
                   4287: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4288: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4289:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4290:                 } elsif ($trole eq 'gr') {
                   4291:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4292: 		} else {
1.567     raeburn  4293:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4294: 		}
1.12      www      4295:             }
1.662     raeburn  4296:           }
1.191     harris41 4297:         }
1.743     albertel 4298:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4299:         $userroles{'user.adv'}    = $adv;
                   4300: 	$userroles{'user.author'} = $author;
1.620     albertel 4301:         $env{'user.adv'}=$adv;
1.11      www      4302:     }
1.743     albertel 4303:     return \%userroles;  
1.11      www      4304: }
                   4305: 
1.567     raeburn  4306: sub set_arearole {
                   4307:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4308: # log the associated role with the area
                   4309:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4310:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4311: }
                   4312: 
                   4313: sub custom_roleprivs {
                   4314:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4315:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4316:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4317:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4318:         my ($rdummy,$roledef)=
                   4319:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4320:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4321:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4322:             if (defined($syspriv)) {
1.1043    raeburn  4323:                 if ($trest =~ /^$match_community$/) {
                   4324:                     $syspriv =~ s/bre\&S//; 
                   4325:                 }
1.567     raeburn  4326:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4327:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4328:             }
                   4329:             if ($tdomain ne '') {
                   4330:                 if (defined($dompriv)) {
                   4331:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4332:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4333:                 }
                   4334:                 if (($trest ne '') && (defined($coursepriv))) {
                   4335:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4336:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4337:                 }
                   4338:             }
                   4339:         }
                   4340:     }
                   4341: }
                   4342: 
1.678     raeburn  4343: sub group_roleprivs {
                   4344:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4345:     my $access = 1;
                   4346:     my $now = time;
                   4347:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4348:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4349:     if ($access) {
1.811     albertel 4350:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4351:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4352:     }
                   4353: }
1.567     raeburn  4354: 
                   4355: sub standard_roleprivs {
                   4356:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4357:     if (defined($pr{$trole.':s'})) {
                   4358:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4359:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4360:     }
                   4361:     if ($tdomain ne '') {
                   4362:         if (defined($pr{$trole.':d'})) {
                   4363:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4364:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4365:         }
                   4366:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4367:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4368:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4369:         }
                   4370:     }
                   4371: }
                   4372: 
                   4373: sub set_userprivs {
1.1064    raeburn  4374:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4375:     my $author=0;
                   4376:     my $adv=0;
1.678     raeburn  4377:     my %grouproles = ();
                   4378:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4379:         my @groupkeys; 
1.1000    raeburn  4380:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4381:             push(@groupkeys,$role);
                   4382:         }
                   4383:         if (ref($groups_roles) eq 'HASH') {
                   4384:             foreach my $key (keys(%{$groups_roles})) {
                   4385:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4386:                     push(@groupkeys,$key);
                   4387:                 }
                   4388:             }
                   4389:         }
                   4390:         if (@groupkeys > 0) {
                   4391:             foreach my $role (@groupkeys) {
                   4392:                 my ($trole,$area,$sec,$extendedarea);
                   4393:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4394:                     $trole = $1;
                   4395:                     $area = $2;
                   4396:                     $sec = $3;
                   4397:                     $extendedarea = $area.$sec;
                   4398:                     if (exists($$allgroups{$area})) {
                   4399:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4400:                             my $spec = $trole.'.'.$extendedarea;
                   4401:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4402:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4403:                         }
1.678     raeburn  4404:                     }
                   4405:                 }
                   4406:             }
                   4407:         }
                   4408:     }
1.800     albertel 4409:     foreach my $group (keys(%grouproles)) {
                   4410:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4411:     }
1.800     albertel 4412:     foreach my $role (keys(%{$allroles})) {
                   4413:         my %thesepriv;
1.941     raeburn  4414:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4415:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4416:             if ($item ne '') {
                   4417:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4418:                 if ($restrictions eq '') {
                   4419:                     $thesepriv{$privilege}='F';
                   4420:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4421:                     $thesepriv{$privilege}.=$restrictions;
                   4422:                 }
                   4423:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4424:             }
                   4425:         }
                   4426:         my $thesestr='';
1.1104    raeburn  4427:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4428: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4429: 	}
                   4430:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4431:     }
                   4432:     return ($author,$adv);
                   4433: }
                   4434: 
1.994     raeburn  4435: sub role_status {
1.1104    raeburn  4436:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4437:     my @pwhere = ();
                   4438:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4439:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4440:         unless (!defined($$role) || $$role eq '') {
                   4441:             $$where=join('.',@pwhere);
                   4442:             $$trolecode=$$role.'.'.$$where;
                   4443:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4444:             $$tstatus='is';
1.1104    raeburn  4445:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4446:                 $$tstatus='future';
1.1034    raeburn  4447:                 if ($$tstart<$now) {
                   4448:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4449:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4450:                             my (%allroles,%allgroups,$group_privs,
                   4451:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4452:                             my %userroles = (
                   4453:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4454:                             );
1.1064    raeburn  4455:                             @rolecodes = ('cm'); 
1.1002    raeburn  4456:                             my $spec=$$role.'.'.$$where;
                   4457:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4458:                             if ($$role =~ /^cr\//) {
                   4459:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4460:                                 push(@rolecodes,'cr');
1.1002    raeburn  4461:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4462:                                 push(@rolecodes,$$role);
1.1002    raeburn  4463:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4464:                                                     $env{'user.name'});
1.1064    raeburn  4465:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4466:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4467:                                 $group_privs = &unescape($group_privs);
                   4468:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4469:                                 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  4470:                                 &get_groups_roles($tdomain,$trest,
                   4471:                                                   \%course_roles,\@rolecodes,
                   4472:                                                   \%groups_roles);
1.1002    raeburn  4473:                             } else {
1.1064    raeburn  4474:                                 push(@rolecodes,$$role);
1.1002    raeburn  4475:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4476:                             }
1.1064    raeburn  4477:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4478:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4479:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4480:                         }
                   4481:                     }
1.1034    raeburn  4482:                     $$tstatus = 'is';
1.1002    raeburn  4483:                 }
1.994     raeburn  4484:             }
                   4485:             if ($$tend) {
1.1104    raeburn  4486:                 if ($$tend<$update) {
1.994     raeburn  4487:                     $$tstatus='expired';
                   4488:                 } elsif ($$tend<$now) {
                   4489:                     $$tstatus='will_not';
                   4490:                 }
                   4491:             }
                   4492:         }
                   4493:     }
                   4494: }
                   4495: 
1.1104    raeburn  4496: sub get_groups_roles {
                   4497:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4498:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4499:                   (ref($rolecodes) eq 'ARRAY') && 
                   4500:                   (ref($groups_roles) eq 'HASH')); 
                   4501:     if (keys(%{$cdom_courseroles}) > 0) {
                   4502:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4503:         if ($cdom ne '' && $cnum ne '') {
                   4504:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4505:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4506:                     my $crsrole = $1;
                   4507:                     my $crssec = $2;
                   4508:                     if ($crsrole =~ /^cr/) {
                   4509:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4510:                             push(@{$rolecodes},'cr');
                   4511:                         }
                   4512:                     } else {
                   4513:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4514:                             push(@{$rolecodes},$crsrole);
                   4515:                         }
                   4516:                     }
                   4517:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4518:                     if ($crssec ne '') {
                   4519:                         $rolekey .= "/$crssec";
                   4520:                     }
                   4521:                     $rolekey .= './';
                   4522:                     $groups_roles->{$rolekey} = $rolecodes;
                   4523:                 }
                   4524:             }
                   4525:         }
                   4526:     }
                   4527:     return;
                   4528: }
                   4529: 
                   4530: sub delete_env_groupprivs {
                   4531:     my ($where,$courseroles,$possroles) = @_;
                   4532:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4533:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4534:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4535:         %{$courseroles->{$udom}} =
                   4536:             &get_my_roles('','','userroles',['active'],
                   4537:                           $possroles,[$udom],1);
                   4538:     }
                   4539:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4540:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4541:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4542:             my $area = '/'.$cdom.'/'.$cnum;
                   4543:             my $privkey = "user.priv.$crsrole.$area";
                   4544:             if ($crssec ne '') {
                   4545:                 $privkey .= '/'.$crssec;
                   4546:             }
                   4547:             $privkey .= ".$area/$group";
                   4548:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4549:         }
                   4550:     }
                   4551:     return;
                   4552: }
                   4553: 
1.994     raeburn  4554: sub check_adhoc_privs {
1.1104    raeburn  4555:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4556:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4557:     if ($env{$cckey}) {
                   4558:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4559:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4560:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4561:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4562:         }
                   4563:     } else {
1.1088    raeburn  4564:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4565:     }
                   4566: }
                   4567: 
                   4568: sub set_adhoc_privileges {
                   4569: # role can be cc or ca
1.1088    raeburn  4570:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4571:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4572:     my $spec = $role.'.'.$area;
                   4573:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4574:                                   $env{'user.name'});
                   4575:     my %ccrole = ();
                   4576:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4577:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4578:     &appenv(\%userroles,[$role,'cm']);
                   4579:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4580:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4581:         &appenv( {'request.role'        => $spec,
                   4582:                   'request.role.domain' => $dcdom,
                   4583:                   'request.course.sec'  => ''
                   4584:                  }
                   4585:                );
                   4586:         my $tadv=0;
                   4587:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4588:         &appenv({'request.role.adv'    => $tadv});
                   4589:     }
1.994     raeburn  4590: }
                   4591: 
1.12      www      4592: # --------------------------------------------------------------- get interface
                   4593: 
                   4594: sub get {
1.131     albertel 4595:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4596:    my $items='';
1.800     albertel 4597:    foreach my $item (@$storearr) {
                   4598:        $items.=&escape($item).'&';
1.191     harris41 4599:    }
1.12      www      4600:    $items=~s/\&$//;
1.620     albertel 4601:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4602:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4603:    my $uhome=&homeserver($uname,$udomain);
                   4604: 
1.133     albertel 4605:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4606:    my @pairs=split(/\&/,$rep);
1.273     albertel 4607:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4608:      return @pairs;
                   4609:    }
1.15      www      4610:    my %returnhash=();
1.42      www      4611:    my $i=0;
1.800     albertel 4612:    foreach my $item (@$storearr) {
                   4613:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4614:       $i++;
1.191     harris41 4615:    }
1.15      www      4616:    return %returnhash;
1.27      www      4617: }
                   4618: 
                   4619: # --------------------------------------------------------------- del interface
                   4620: 
                   4621: sub del {
1.133     albertel 4622:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4623:    my $items='';
1.800     albertel 4624:    foreach my $item (@$storearr) {
                   4625:        $items.=&escape($item).'&';
1.191     harris41 4626:    }
1.984     neumanie 4627: 
1.27      www      4628:    $items=~s/\&$//;
1.620     albertel 4629:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4630:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4631:    my $uhome=&homeserver($uname,$udomain);
                   4632:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4633: }
                   4634: 
                   4635: # -------------------------------------------------------------- dump interface
                   4636: 
                   4637: sub dump {
1.1086    raeburn  4638:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4639:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4640:     if (!$uname) { $uname=$env{'user.name'}; }
                   4641:     my $uhome=&homeserver($uname,$udomain);
                   4642:     if ($regexp) {
                   4643: 	$regexp=&escape($regexp);
                   4644:     } else {
                   4645: 	$regexp='.';
                   4646:     }
1.1086    raeburn  4647:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4648:     my @pairs=split(/\&/,$rep);
                   4649:     my %returnhash=();
1.1098    foxr     4650:     if (!($rep =~ /^error/ )) {
                   4651: 	foreach my $item (@pairs) {
                   4652: 	    my ($key,$value)=split(/=/,$item,2);
                   4653: 	    $key = &unescape($key);
                   4654: 	    next if ($key =~ /^error: 2 /);
                   4655: 	    $returnhash{$key}=&thaw_unescape($value);
                   4656: 	}
1.755     albertel 4657:     }
                   4658:     return %returnhash;
1.407     www      4659: }
                   4660: 
1.1098    foxr     4661: 
1.717     albertel 4662: # --------------------------------------------------------- dumpstore interface
                   4663: 
                   4664: sub dumpstore {
                   4665:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4666:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4667:    if (!$uname) { $uname=$env{'user.name'}; }
                   4668:    my $uhome=&homeserver($uname,$udomain);
                   4669:    if ($regexp) {
                   4670:        $regexp=&escape($regexp);
                   4671:    } else {
                   4672:        $regexp='.';
                   4673:    }
                   4674:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4675:    my @pairs=split(/\&/,$rep);
                   4676:    my %returnhash=();
                   4677:    foreach my $item (@pairs) {
                   4678:        my ($key,$value)=split(/=/,$item,2);
                   4679:        next if ($key =~ /^error: 2 /);
                   4680:        $returnhash{$key}=&thaw_unescape($value);
                   4681:    }
                   4682:    return %returnhash;
1.717     albertel 4683: }
                   4684: 
1.407     www      4685: # -------------------------------------------------------------- keys interface
                   4686: 
                   4687: sub getkeys {
                   4688:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4689:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4690:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4691:    my $uhome=&homeserver($uname,$udomain);
                   4692:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4693:    my @keyarray=();
1.800     albertel 4694:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4695:       next if ($key =~ /^error: 2 /);
1.800     albertel 4696:       push(@keyarray,&unescape($key));
1.407     www      4697:    }
                   4698:    return @keyarray;
1.318     matthew  4699: }
                   4700: 
1.319     matthew  4701: # --------------------------------------------------------------- currentdump
                   4702: sub currentdump {
1.328     matthew  4703:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4704:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4705:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4706:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4707:    my $uhome = &homeserver($sname,$sdom);
                   4708:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4709:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4710:    #
1.318     matthew  4711:    my %returnhash=();
1.319     matthew  4712:    #
                   4713:    if ($rep eq "unknown_cmd") { 
                   4714:        # an old lond will not know currentdump
                   4715:        # Do a dump and make it look like a currentdump
1.822     albertel 4716:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4717:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4718:        my %hash = @tmp;
                   4719:        @tmp=();
1.424     matthew  4720:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4721:    } else {
                   4722:        my @pairs=split(/\&/,$rep);
1.800     albertel 4723:        foreach my $pair (@pairs) {
                   4724:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4725:            my ($symb,$param) = split(/:/,$key);
                   4726:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4727:                                                         &thaw_unescape($value);
1.319     matthew  4728:        }
1.191     harris41 4729:    }
1.12      www      4730:    return %returnhash;
1.424     matthew  4731: }
                   4732: 
                   4733: sub convert_dump_to_currentdump{
                   4734:     my %hash = %{shift()};
                   4735:     my %returnhash;
                   4736:     # Code ripped from lond, essentially.  The only difference
                   4737:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4738:     # we might run in to problems with parameter names =~ /^v\./
                   4739:     while (my ($key,$value) = each(%hash)) {
                   4740:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4741: 	$symb  = &unescape($symb);
                   4742: 	$param = &unescape($param);
1.424     matthew  4743:         next if ($v eq 'version' || $symb eq 'keys');
                   4744:         next if (exists($returnhash{$symb}) &&
                   4745:                  exists($returnhash{$symb}->{$param}) &&
                   4746:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4747:         $returnhash{$symb}->{$param}=$value;
                   4748:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4749:     }
                   4750:     #
                   4751:     # Remove all of the keys in the hashes which keep track of
                   4752:     # the version of the parameter.
                   4753:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4754:         # use a foreach because we are going to delete from the hash.
                   4755:         foreach my $key (keys(%$param_hash)) {
                   4756:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4757:         }
                   4758:     }
                   4759:     return \%returnhash;
1.12      www      4760: }
                   4761: 
1.627     albertel 4762: # ------------------------------------------------------ critical inc interface
                   4763: 
                   4764: sub cinc {
                   4765:     return &inc(@_,'critical');
                   4766: }
                   4767: 
1.449     matthew  4768: # --------------------------------------------------------------- inc interface
                   4769: 
                   4770: sub inc {
1.627     albertel 4771:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4772:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4773:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4774:     my $uhome=&homeserver($uname,$udomain);
                   4775:     my $items='';
                   4776:     if (! ref($store)) {
                   4777:         # got a single value, so use that instead
                   4778:         $items = &escape($store).'=&';
                   4779:     } elsif (ref($store) eq 'SCALAR') {
                   4780:         $items = &escape($$store).'=&';        
                   4781:     } elsif (ref($store) eq 'ARRAY') {
                   4782:         $items = join('=&',map {&escape($_);} @{$store});
                   4783:     } elsif (ref($store) eq 'HASH') {
                   4784:         while (my($key,$value) = each(%{$store})) {
                   4785:             $items.= &escape($key).'='.&escape($value).'&';
                   4786:         }
                   4787:     }
                   4788:     $items=~s/\&$//;
1.627     albertel 4789:     if ($critical) {
                   4790: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4791:     } else {
                   4792: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4793:     }
1.449     matthew  4794: }
                   4795: 
1.12      www      4796: # --------------------------------------------------------------- put interface
                   4797: 
                   4798: sub put {
1.134     albertel 4799:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4800:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4801:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4802:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4803:    my $items='';
1.800     albertel 4804:    foreach my $item (keys(%$storehash)) {
                   4805:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4806:    }
1.12      www      4807:    $items=~s/\&$//;
1.134     albertel 4808:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4809: }
                   4810: 
1.631     albertel 4811: # ------------------------------------------------------------ newput interface
                   4812: 
                   4813: sub newput {
                   4814:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4816:    if (!$uname) { $uname=$env{'user.name'}; }
                   4817:    my $uhome=&homeserver($uname,$udomain);
                   4818:    my $items='';
                   4819:    foreach my $key (keys(%$storehash)) {
                   4820:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4821:    }
                   4822:    $items=~s/\&$//;
                   4823:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4824: }
                   4825: 
                   4826: # ---------------------------------------------------------  putstore interface
                   4827: 
1.524     raeburn  4828: sub putstore {
1.715     albertel 4829:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4830:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4831:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4832:    my $uhome=&homeserver($uname,$udomain);
                   4833:    my $items='';
1.715     albertel 4834:    foreach my $key (keys(%$storehash)) {
                   4835:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4836:    }
1.715     albertel 4837:    $items=~s/\&$//;
1.716     albertel 4838:    my $esc_symb=&escape($symb);
                   4839:    my $esc_v=&escape($version);
1.715     albertel 4840:    my $reply =
1.716     albertel 4841:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4842: 	      $uhome);
                   4843:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4844:        # gfall back to way things use to be done
1.715     albertel 4845:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4846: 			    $uname);
1.524     raeburn  4847:    }
1.715     albertel 4848:    return $reply;
                   4849: }
                   4850: 
                   4851: sub old_putstore {
1.716     albertel 4852:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4853:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4854:     if (!$uname) { $uname=$env{'user.name'}; }
                   4855:     my $uhome=&homeserver($uname,$udomain);
                   4856:     my %newstorehash;
1.800     albertel 4857:     foreach my $item (keys(%$storehash)) {
                   4858: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4859: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4860:     }
                   4861:     my $items='';
                   4862:     my %allitems = ();
1.800     albertel 4863:     foreach my $item (keys(%newstorehash)) {
                   4864: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4865: 	    my $key = $1.':keys:'.$2;
                   4866: 	    $allitems{$key} .= $3.':';
                   4867: 	}
1.800     albertel 4868: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4869:     }
1.800     albertel 4870:     foreach my $item (keys(%allitems)) {
                   4871: 	$allitems{$item} =~ s/\:$//;
                   4872: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4873:     }
                   4874:     $items=~s/\&$//;
                   4875:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4876: }
                   4877: 
1.47      www      4878: # ------------------------------------------------------ critical put interface
                   4879: 
                   4880: sub cput {
1.134     albertel 4881:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4882:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4883:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4884:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4885:    my $items='';
1.800     albertel 4886:    foreach my $item (keys(%$storehash)) {
                   4887:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4888:    }
1.47      www      4889:    $items=~s/\&$//;
1.134     albertel 4890:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4891: }
                   4892: 
                   4893: # -------------------------------------------------------------- eget interface
                   4894: 
                   4895: sub eget {
1.133     albertel 4896:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4897:    my $items='';
1.800     albertel 4898:    foreach my $item (@$storearr) {
                   4899:        $items.=&escape($item).'&';
1.191     harris41 4900:    }
1.12      www      4901:    $items=~s/\&$//;
1.620     albertel 4902:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4903:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4904:    my $uhome=&homeserver($uname,$udomain);
                   4905:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4906:    my @pairs=split(/\&/,$rep);
                   4907:    my %returnhash=();
1.42      www      4908:    my $i=0;
1.800     albertel 4909:    foreach my $item (@$storearr) {
                   4910:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4911:       $i++;
1.191     harris41 4912:    }
1.12      www      4913:    return %returnhash;
                   4914: }
                   4915: 
1.667     albertel 4916: # ------------------------------------------------------------ tmpput interface
                   4917: sub tmpput {
1.802     raeburn  4918:     my ($storehash,$server,$context)=@_;
1.667     albertel 4919:     my $items='';
1.800     albertel 4920:     foreach my $item (keys(%$storehash)) {
                   4921: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4922:     }
                   4923:     $items=~s/\&$//;
1.802     raeburn  4924:     if (defined($context)) {
                   4925:         $items .= ':'.&escape($context);
                   4926:     }
1.667     albertel 4927:     return &reply("tmpput:$items",$server);
                   4928: }
                   4929: 
                   4930: # ------------------------------------------------------------ tmpget interface
                   4931: sub tmpget {
1.688     albertel 4932:     my ($token,$server)=@_;
                   4933:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4934:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4935:     my %returnhash;
                   4936:     foreach my $item (split(/\&/,$rep)) {
                   4937: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4938:         next if ($key =~ /^error: 2 /);
1.667     albertel 4939: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4940:     }
                   4941:     return %returnhash;
                   4942: }
                   4943: 
1.1113    raeburn  4944: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4945: sub tmpdel {
                   4946:     my ($token,$server)=@_;
                   4947:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4948:     return &reply("tmpdel:$token",$server);
                   4949: }
                   4950: 
1.765     albertel 4951: # -------------------------------------------------- portfolio access checking
                   4952: 
                   4953: sub portfolio_access {
1.766     albertel 4954:     my ($requrl) = @_;
1.765     albertel 4955:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4956:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4957:     if ($result) {
                   4958:         my %setters;
                   4959:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4960:             my ($startblock,$endblock) =
                   4961:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4962:             if ($startblock && $endblock) {
                   4963:                 return 'B';
                   4964:             }
                   4965:         } else {
                   4966:             my ($startblock,$endblock) =
                   4967:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4968:             if ($startblock && $endblock) {
                   4969:                 return 'B';
                   4970:             }
                   4971:         }
                   4972:     }
1.765     albertel 4973:     if ($result eq 'ok') {
1.766     albertel 4974:        return 'F';
1.765     albertel 4975:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4976:        return 'A';
1.765     albertel 4977:     }
1.766     albertel 4978:     return '';
1.765     albertel 4979: }
                   4980: 
                   4981: sub get_portfolio_access {
1.767     albertel 4982:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4983: 
                   4984:     if (!ref($access_hash)) {
                   4985: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4986: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4987: 						   $file_name);
                   4988: 	$access_hash = $access_controls{$file_name};
                   4989:     }
                   4990: 
1.765     albertel 4991:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4992:     my $now = time;
                   4993:     if (ref($access_hash) eq 'HASH') {
                   4994:         foreach my $key (keys(%{$access_hash})) {
                   4995:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4996:             if ($start > $now) {
                   4997:                 next;
                   4998:             }
                   4999:             if ($end && $end<$now) {
                   5000:                 next;
                   5001:             }
                   5002:             if ($scope eq 'public') {
                   5003:                 $public = $key;
                   5004:                 last;
                   5005:             } elsif ($scope eq 'guest') {
                   5006:                 $guest = $key;
                   5007:             } elsif ($scope eq 'domains') {
                   5008:                 push(@domains,$key);
                   5009:             } elsif ($scope eq 'users') {
                   5010:                 push(@users,$key);
                   5011:             } elsif ($scope eq 'course') {
                   5012:                 push(@courses,$key);
                   5013:             } elsif ($scope eq 'group') {
                   5014:                 push(@groups,$key);
                   5015:             }
                   5016:         }
                   5017:         if ($public) {
                   5018:             return 'ok';
                   5019:         }
                   5020:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5021:             if ($guest) {
                   5022:                 return $guest;
                   5023:             }
                   5024:         } else {
                   5025:             if (@domains > 0) {
                   5026:                 foreach my $domkey (@domains) {
                   5027:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5028:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5029:                             return 'ok';
                   5030:                         }
                   5031:                     }
                   5032:                 }
                   5033:             }
                   5034:             if (@users > 0) {
                   5035:                 foreach my $userkey (@users) {
1.865     raeburn  5036:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5037:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5038:                             if (ref($item) eq 'HASH') {
                   5039:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5040:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5041:                                     return 'ok';
                   5042:                                 }
                   5043:                             }
                   5044:                         }
                   5045:                     } 
1.765     albertel 5046:                 }
                   5047:             }
                   5048:             my %roleshash;
                   5049:             my @courses_and_groups = @courses;
                   5050:             push(@courses_and_groups,@groups); 
                   5051:             if (@courses_and_groups > 0) {
                   5052:                 my (%allgroups,%allroles); 
                   5053:                 my ($start,$end,$role,$sec,$group);
                   5054:                 foreach my $envkey (%env) {
1.1060    raeburn  5055:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5056:                         my $cid = $2.'_'.$3; 
                   5057:                         if ($1 eq 'gr') {
                   5058:                             $group = $4;
                   5059:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5060:                         } else {
                   5061:                             if ($4 eq '') {
                   5062:                                 $sec = 'none';
                   5063:                             } else {
                   5064:                                 $sec = $4;
                   5065:                             }
                   5066:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5067:                         }
1.811     albertel 5068:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5069:                         my $cid = $2.'_'.$3;
                   5070:                         if ($4 eq '') {
                   5071:                             $sec = 'none';
                   5072:                         } else {
                   5073:                             $sec = $4;
                   5074:                         }
                   5075:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5076:                     }
                   5077:                 }
                   5078:                 if (keys(%allroles) == 0) {
                   5079:                     return;
                   5080:                 }
                   5081:                 foreach my $key (@courses_and_groups) {
                   5082:                     my %content = %{$$access_hash{$key}};
                   5083:                     my $cnum = $content{'number'};
                   5084:                     my $cdom = $content{'domain'};
                   5085:                     my $cid = $cdom.'_'.$cnum;
                   5086:                     if (!exists($allroles{$cid})) {
                   5087:                         next;
                   5088:                     }    
                   5089:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5090:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5091:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5092:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5093:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5094:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5095:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5096:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5097:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5098:                                         if (grep/^all$/,@sections) {
                   5099:                                             return 'ok';
                   5100:                                         } else {
                   5101:                                             if (grep/^$sec$/,@sections) {
                   5102:                                                 return 'ok';
                   5103:                                             }
                   5104:                                         }
                   5105:                                     }
                   5106:                                 }
                   5107:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5108:                                     if (grep/^none$/,@groups) {
                   5109:                                         return 'ok';
                   5110:                                     }
                   5111:                                 } else {
                   5112:                                     if (grep/^all$/,@groups) {
                   5113:                                         return 'ok';
                   5114:                                     } 
                   5115:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5116:                                         if (grep/^$group$/,@groups) {
                   5117:                                             return 'ok';
                   5118:                                         }
                   5119:                                     }
                   5120:                                 } 
                   5121:                             }
                   5122:                         }
                   5123:                     }
                   5124:                 }
                   5125:             }
                   5126:             if ($guest) {
                   5127:                 return $guest;
                   5128:             }
                   5129:         }
                   5130:     }
                   5131:     return;
                   5132: }
                   5133: 
                   5134: sub course_group_datechecker {
                   5135:     my ($dates,$now,$status) = @_;
                   5136:     my ($start,$end) = split(/\./,$dates);
                   5137:     if (!$start && !$end) {
                   5138:         return 'ok';
                   5139:     }
                   5140:     if (grep/^active$/,@{$status}) {
                   5141:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5142:             return 'ok';
                   5143:         }
                   5144:     }
                   5145:     if (grep/^previous$/,@{$status}) {
                   5146:         if ($end > $now ) {
                   5147:             return 'ok';
                   5148:         }
                   5149:     }
                   5150:     if (grep/^future$/,@{$status}) {
                   5151:         if ($start > $now) {
                   5152:             return 'ok';
                   5153:         }
                   5154:     }
                   5155:     return; 
                   5156: }
                   5157: 
                   5158: sub parse_portfolio_url {
                   5159:     my ($url) = @_;
                   5160: 
                   5161:     my ($type,$udom,$unum,$group,$file_name);
                   5162:     
1.823     albertel 5163:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5164: 	$type = 1;
                   5165:         $udom = $1;
                   5166:         $unum = $2;
                   5167:         $file_name = $3;
1.823     albertel 5168:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5169: 	$type = 2;
                   5170:         $udom = $1;
                   5171:         $unum = $2;
                   5172:         $group = $3;
                   5173:         $file_name = $3.'/'.$4;
                   5174:     }
                   5175:     if (wantarray) {
                   5176: 	return ($type,$udom,$unum,$file_name,$group);
                   5177:     }
                   5178:     return $type;
                   5179: }
                   5180: 
                   5181: sub is_portfolio_url {
                   5182:     my ($url) = @_;
                   5183:     return scalar(&parse_portfolio_url($url));
                   5184: }
                   5185: 
1.798     raeburn  5186: sub is_portfolio_file {
                   5187:     my ($file) = @_;
1.820     raeburn  5188:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5189:         return 1;
                   5190:     }
                   5191:     return;
                   5192: }
                   5193: 
1.976     raeburn  5194: sub usertools_access {
1.1084    raeburn  5195:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5196:     my ($access,%tools);
                   5197:     if ($context eq '') {
                   5198:         $context = 'tools';
                   5199:     }
                   5200:     if ($context eq 'requestcourses') {
                   5201:         %tools = (
                   5202:                       official   => 1,
                   5203:                       unofficial => 1,
1.1006    raeburn  5204:                       community  => 1,
1.985     raeburn  5205:                  );
                   5206:     } else {
                   5207:         %tools = (
                   5208:                       aboutme   => 1,
                   5209:                       blog      => 1,
                   5210:                       portfolio => 1,
                   5211:                  );
                   5212:     }
1.976     raeburn  5213:     return if (!defined($tools{$tool}));
                   5214: 
                   5215:     if ((!defined($udom)) || (!defined($uname))) {
                   5216:         $udom = $env{'user.domain'};
                   5217:         $uname = $env{'user.name'};
                   5218:     }
                   5219: 
1.978     raeburn  5220:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5221:         if ($action ne 'reload') {
1.985     raeburn  5222:             if ($context eq 'requestcourses') {
                   5223:                 return $env{'environment.canrequest.'.$tool};
                   5224:             } else {
                   5225:                 return $env{'environment.availabletools.'.$tool};
                   5226:             }
                   5227:         }
1.976     raeburn  5228:     }
                   5229: 
                   5230:     my ($toolstatus,$inststatus);
                   5231: 
1.985     raeburn  5232:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5233:          ($action ne 'reload')) {
                   5234:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5235:         $inststatus = $env{'environment.inststatus'};
                   5236:     } else {
1.1084    raeburn  5237:         if (ref($userenvref) eq 'HASH') {
                   5238:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5239:             $inststatus = $userenvref->{'inststatus'};
                   5240:         } else {
                   5241:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5242:             $toolstatus = $userenv{$context.'.'.$tool};
                   5243:             $inststatus = $userenv{'inststatus'};
                   5244:         }
1.976     raeburn  5245:     }
                   5246: 
                   5247:     if ($toolstatus ne '') {
                   5248:         if ($toolstatus) {
                   5249:             $access = 1;
                   5250:         } else {
                   5251:             $access = 0;
                   5252:         }
                   5253:         return $access;
                   5254:     }
                   5255: 
1.1084    raeburn  5256:     my ($is_adv,%domdef);
                   5257:     if (ref($is_advref) eq 'HASH') {
                   5258:         $is_adv = $is_advref->{'is_adv'};
                   5259:     } else {
                   5260:         $is_adv = &is_advanced_user($udom,$uname);
                   5261:     }
                   5262:     if (ref($domdefref) eq 'HASH') {
                   5263:         %domdef = %{$domdefref};
                   5264:     } else {
                   5265:         %domdef = &get_domain_defaults($udom);
                   5266:     }
1.976     raeburn  5267:     if (ref($domdef{$tool}) eq 'HASH') {
                   5268:         if ($is_adv) {
                   5269:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5270:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5271:                     $access = 1;
                   5272:                 } else {
                   5273:                     $access = 0;
                   5274:                 }
                   5275:                 return $access;
                   5276:             }
                   5277:         }
                   5278:         if ($inststatus ne '') {
                   5279:             my ($hasaccess,$hasnoaccess);
                   5280:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5281:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5282:                     if ($domdef{$tool}{$affiliation}) {
                   5283:                         $hasaccess = 1;
                   5284:                     } else {
                   5285:                         $hasnoaccess = 1;
                   5286:                     }
                   5287:                 }
                   5288:             }
                   5289:             if ($hasaccess || $hasnoaccess) {
                   5290:                 if ($hasaccess) {
                   5291:                     $access = 1;
                   5292:                 } elsif ($hasnoaccess) {
                   5293:                     $access = 0; 
                   5294:                 }
                   5295:                 return $access;
                   5296:             }
                   5297:         } else {
                   5298:             if ($domdef{$tool}{'default'} ne '') {
                   5299:                 if ($domdef{$tool}{'default'}) {
                   5300:                     $access = 1;
                   5301:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5302:                     $access = 0;
                   5303:                 }
                   5304:                 return $access;
                   5305:             }
                   5306:         }
                   5307:     } else {
1.985     raeburn  5308:         if ($context eq 'tools') {
                   5309:             $access = 1;
                   5310:         } else {
                   5311:             $access = 0;
                   5312:         }
1.976     raeburn  5313:         return $access;
                   5314:     }
                   5315: }
                   5316: 
1.1050    raeburn  5317: sub is_course_owner {
                   5318:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5319:     if (($udom eq '') || ($uname eq '')) {
                   5320:         $udom = $env{'user.domain'};
                   5321:         $uname = $env{'user.name'};
                   5322:     }
                   5323:     unless (($udom eq '') || ($uname eq '')) {
                   5324:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5325:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5326:                 return 1;
                   5327:             } else {
                   5328:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5329:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5330:                     return 1;
                   5331:                 }
                   5332:             }
                   5333:         }
                   5334:     }
                   5335:     return;
                   5336: }
                   5337: 
1.976     raeburn  5338: sub is_advanced_user {
                   5339:     my ($udom,$uname) = @_;
1.1085    raeburn  5340:     if ($udom ne '' && $uname ne '') {
                   5341:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5342:             return $env{'user.adv'};  
                   5343:         }
                   5344:     }
1.976     raeburn  5345:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5346:     my %allroles;
                   5347:     my $is_adv;
                   5348:     foreach my $role (keys(%roleshash)) {
                   5349:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5350:         my $area = '/'.$tdomain.'/'.$trest;
                   5351:         if ($sec ne '') {
                   5352:             $area .= '/'.$sec;
                   5353:         }
                   5354:         if (($area ne '') && ($trole ne '')) {
                   5355:             my $spec=$trole.'.'.$area;
                   5356:             if ($trole =~ /^cr\//) {
                   5357:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5358:             } elsif ($trole ne 'gr') {
                   5359:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5360:             }
                   5361:         }
                   5362:     }
                   5363:     foreach my $role (keys(%allroles)) {
                   5364:         last if ($is_adv);
                   5365:         foreach my $item (split(/:/,$allroles{$role})) {
                   5366:             if ($item ne '') {
                   5367:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5368:                 if ($privilege eq 'adv') {
                   5369:                     $is_adv = 1;
                   5370:                     last;
                   5371:                 }
                   5372:             }
                   5373:         }
                   5374:     }
                   5375:     return $is_adv;
                   5376: }
1.798     raeburn  5377: 
1.1035    raeburn  5378: sub check_can_request {
1.1036    raeburn  5379:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5380:     my $canreq = 0;
                   5381:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5382:     my @options = ('approval','validate','autolimit');
                   5383:     my $optregex = join('|',@options);
                   5384:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5385:         foreach my $type (@{$types}) {
                   5386:             if (&usertools_access($env{'user.name'},
                   5387:                                   $env{'user.domain'},
                   5388:                                   $type,undef,'requestcourses')) {
                   5389:                 $canreq ++;
1.1036    raeburn  5390:                 if (ref($request_domains) eq 'HASH') {
                   5391:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5392:                 }
1.1035    raeburn  5393:                 if ($dom eq $env{'user.domain'}) {
                   5394:                     $can_request->{$type} = 1;
                   5395:                 }
                   5396:             }
                   5397:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5398:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5399:                 if (@curr > 0) {
1.1036    raeburn  5400:                     foreach my $item (@curr) {
                   5401:                         if (ref($request_domains) eq 'HASH') {
                   5402:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5403:                             if ($otherdom ne '') {
                   5404:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5405:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5406:                                         push(@{$request_domains->{$type}},$otherdom);
                   5407:                                     }
                   5408:                                 } else {
                   5409:                                     push(@{$request_domains->{$type}},$otherdom);
                   5410:                                 }
                   5411:                             }
                   5412:                         }
                   5413:                     }
                   5414:                     unless($dom eq $env{'user.domain'}) {
                   5415:                         $canreq ++;
1.1035    raeburn  5416:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5417:                             $can_request->{$type} = 1;
                   5418:                         }
                   5419:                     }
                   5420:                 }
                   5421:             }
                   5422:         }
                   5423:     }
                   5424:     return $canreq;
                   5425: }
                   5426: 
1.341     www      5427: # ---------------------------------------------- Custom access rule evaluation
                   5428: 
                   5429: sub customaccess {
                   5430:     my ($priv,$uri)=@_;
1.807     albertel 5431:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5432:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5433:     $udom = &LONCAPA::clean_domain($udom);
                   5434:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5435:     my $access=0;
1.800     albertel 5436:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5437: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5438: 	if ($type eq 'user') {
                   5439: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5440: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5441: 		if ($tdom) {
                   5442: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5443: 		}
1.896     albertel 5444: 		if ($tuname) {
                   5445: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5446: 		}
                   5447: 		$access=($effect eq 'allow');
                   5448: 		last;
                   5449: 	    }
                   5450: 	} else {
                   5451: 	    if ($role) {
                   5452: 		if ($role ne $urole) { next; }
                   5453: 	    }
                   5454: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5455: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5456: 		if ($tdom) {
                   5457: 		    if ($tdom ne $udom) { next; }
                   5458: 		}
                   5459: 		if ($tcrs) {
                   5460: 		    if ($tcrs ne $ucrs) { next; }
                   5461: 		}
                   5462: 		if ($tsec) {
                   5463: 		    if ($tsec ne $usec) { next; }
                   5464: 		}
                   5465: 		$access=($effect eq 'allow');
                   5466: 		last;
                   5467: 	    }
                   5468: 	    if ($realm eq '' && $role eq '') {
                   5469: 		$access=($effect eq 'allow');
                   5470: 	    }
1.402     bowersj2 5471: 	}
1.341     www      5472:     }
                   5473:     return $access;
                   5474: }
                   5475: 
1.103     harris41 5476: # ------------------------------------------------- Check for a user privilege
1.12      www      5477: 
                   5478: sub allowed {
1.810     raeburn  5479:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5480:     my $ver_orguri=$uri;
1.439     www      5481:     $uri=&deversion($uri);
1.152     www      5482:     my $orguri=$uri;
1.52      www      5483:     $uri=&declutter($uri);
1.809     raeburn  5484: 
1.810     raeburn  5485:     if ($priv eq 'evb') {
                   5486: # Evade communication block restrictions for specified role in a course
                   5487:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5488:             return $1;
                   5489:         } else {
                   5490:             return;
                   5491:         }
                   5492:     }
                   5493: 
1.620     albertel 5494:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5495: # Free bre access to adm and meta resources
1.775     albertel 5496:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5497: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5498: 	&& ($priv eq 'bre')) {
1.14      www      5499: 	return 'F';
1.159     www      5500:     }
                   5501: 
1.545     banghart 5502: # Free bre access to user's own portfolio contents
1.714     raeburn  5503:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5504:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5505: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5506:         my %setters;
                   5507:         my ($startblock,$endblock) = 
                   5508:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5509:         if ($startblock && $endblock) {
                   5510:             return 'B';
                   5511:         } else {
                   5512:             return 'F';
                   5513:         }
1.545     banghart 5514:     }
                   5515: 
1.762     raeburn  5516: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5517:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5518:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5519:         if (exists($env{'request.course.id'})) {
                   5520:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5521:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5522:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5523:                 my $courseprivid=$env{'request.course.id'};
                   5524:                 $courseprivid=~s/\_/\//;
                   5525:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5526:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5527:                     return $1; 
1.762     raeburn  5528:                 } else {
                   5529:                     if ($env{'request.course.sec'}) {
                   5530:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5531:                     }
                   5532:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5533:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5534:                         return $2;
                   5535:                     }
1.714     raeburn  5536:                 }
                   5537:             }
                   5538:         }
                   5539:     }
                   5540: 
1.159     www      5541: # Free bre to public access
                   5542: 
                   5543:     if ($priv eq 'bre') {
1.238     www      5544:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5545: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5546:            return 'F'; 
                   5547:         }
1.238     www      5548:         if ($copyright eq 'priv') {
                   5549:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5550: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5551: 		return '';
                   5552:             }
                   5553:         }
                   5554:         if ($copyright eq 'domain') {
                   5555:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5556: 	    unless (($env{'user.domain'} eq $1) ||
                   5557:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5558: 		return '';
                   5559:             }
1.262     matthew  5560:         }
1.620     albertel 5561:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5562:             # Library role, so allow browsing of resources in this domain.
                   5563:             return 'F';
1.238     www      5564:         }
1.341     www      5565:         if ($copyright eq 'custom') {
                   5566: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5567:         }
1.14      www      5568:     }
1.264     matthew  5569:     # Domain coordinator is trying to create a course
1.620     albertel 5570:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5571:         # uri is the requested domain in this case.
                   5572:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5573:         # a role of dc for the domain in question.
1.620     albertel 5574:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5575:     }
1.29      www      5576: 
1.52      www      5577:     my $thisallowed='';
                   5578:     my $statecond=0;
                   5579:     my $courseprivid='';
                   5580: 
1.1039    raeburn  5581:     my $ownaccess;
1.1043    raeburn  5582:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5583:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5584:         if ($uri eq '') {
                   5585:             $ownaccess = 1;
                   5586:         } else {
                   5587:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5588:                 my $udom = $env{'user.domain'};
                   5589:                 my $uname = $env{'user.name'};
                   5590:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5591:                     $ownaccess = 1;
1.1040    raeburn  5592:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5593:                     unless ($uri =~ m{\.\./}) {
                   5594:                         $ownaccess = 1;
                   5595:                     }
                   5596:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5597:                     my $now = time;
                   5598:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5599:                         my $adom = $1;
                   5600:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5601:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5602:                                 my ($start,$end) = split('.',$env{$key});
                   5603:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5604:                                     $ownaccess = 1;
                   5605:                                     last;
                   5606:                                 }
                   5607:                             }
                   5608:                         }
                   5609:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5610:                         my $adom = $1;
                   5611:                         my $aname = $2;
1.1042    raeburn  5612:                         foreach my $role ('ca','aa') { 
                   5613:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5614:                                 my ($start,$end) =
                   5615:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5616:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5617:                                     $ownaccess = 1;
                   5618:                                     last;
                   5619:                                 }
1.1039    raeburn  5620:                             }
                   5621:                         }
                   5622:                     }
                   5623:                 }
                   5624:             }
                   5625:         }
                   5626:     }
                   5627: 
1.52      www      5628: # Course
                   5629: 
1.620     albertel 5630:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5631:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5632:             $thisallowed.=$1;
                   5633:         }
1.52      www      5634:     }
1.29      www      5635: 
1.52      www      5636: # Domain
                   5637: 
1.620     albertel 5638:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5639:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5640:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5641:             $thisallowed.=$1;
                   5642:         }
1.12      www      5643:     }
1.52      www      5644: 
                   5645: # Course: uri itself is a course
1.66      www      5646:     my $courseuri=$uri;
                   5647:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5648:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5649: 
1.620     albertel 5650:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5651:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5652:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5653:             $thisallowed.=$1;
                   5654:         }
1.12      www      5655:     }
1.29      www      5656: 
1.665     albertel 5657: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5658: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5659:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5660: 	$thisallowed='';
1.671     raeburn  5661:         my ($match)=&is_on_map($uri);
                   5662:         if ($match) {
                   5663:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5664:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5665:                 $thisallowed.=$1;
                   5666:             }
                   5667:         } else {
1.705     albertel 5668:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5669:             if ($refuri) {
                   5670:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5671:                     $thisallowed='F';
1.671     raeburn  5672:                 } else {
                   5673:                     $refuri=&declutter($refuri);
                   5674:                     my ($match) = &is_on_map($refuri);
                   5675:                     if ($match) {
                   5676:                         $thisallowed='F';
                   5677:                     }
1.669     raeburn  5678:                 }
1.671     raeburn  5679:             }
                   5680:         }
1.314     www      5681:     }
1.492     albertel 5682: 
1.766     albertel 5683:     if ($priv eq 'bre'
                   5684: 	&& $thisallowed ne 'F' 
                   5685: 	&& $thisallowed ne '2'
                   5686: 	&& &is_portfolio_url($uri)) {
                   5687: 	$thisallowed = &portfolio_access($uri);
                   5688:     }
                   5689:     
1.52      www      5690: # Full access at system, domain or course-wide level? Exit.
1.29      www      5691:     if ($thisallowed=~/F/) {
                   5692: 	return 'F';
                   5693:     }
                   5694: 
1.52      www      5695: # If this is generating or modifying users, exit with special codes
1.29      www      5696: 
1.643     www      5697:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5698: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5699: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5700: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5701: 	    unless ($auname) { return $thisallowed; }
                   5702: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5703: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5704: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5705: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5706: 	}
1.52      www      5707: 	return $thisallowed;
                   5708:     }
                   5709: #
1.103     harris41 5710: # Gathered so far: system, domain and course wide privileges
1.52      www      5711: #
                   5712: # Course: See if uri or referer is an individual resource that is part of 
                   5713: # the course
                   5714: 
1.620     albertel 5715:     if ($env{'request.course.id'}) {
1.232     www      5716: 
1.620     albertel 5717:        $courseprivid=$env{'request.course.id'};
                   5718:        if ($env{'request.course.sec'}) {
                   5719:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5720:        }
                   5721:        $courseprivid=~s/\_/\//;
                   5722:        my $checkreferer=1;
1.232     www      5723:        my ($match,$cond)=&is_on_map($uri);
                   5724:        if ($match) {
                   5725:            $statecond=$cond;
1.620     albertel 5726:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5727:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5728:                $thisallowed.=$1;
                   5729:                $checkreferer=0;
                   5730:            }
1.29      www      5731:        }
1.83      www      5732:        
1.148     www      5733:        if ($checkreferer) {
1.620     albertel 5734: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5735:             unless ($refuri) {
1.800     albertel 5736:                 foreach my $key (keys(%env)) {
                   5737: 		    if ($key=~/^httpref\..*\*/) {
                   5738: 			my $pattern=$key;
1.156     www      5739:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5740:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5741:                         $pattern=~s/\//\\\//g;
1.152     www      5742:                         if ($orguri=~/$pattern/) {
1.800     albertel 5743: 			    $refuri=$env{$key};
1.148     www      5744:                         }
                   5745:                     }
1.191     harris41 5746:                 }
1.148     www      5747:             }
1.232     www      5748: 
1.148     www      5749:          if ($refuri) { 
1.152     www      5750: 	  $refuri=&declutter($refuri);
1.232     www      5751:           my ($match,$cond)=&is_on_map($refuri);
                   5752:             if ($match) {
                   5753:               my $refstatecond=$cond;
1.620     albertel 5754:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5755:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5756:                   $thisallowed.=$1;
1.53      www      5757:                   $uri=$refuri;
                   5758:                   $statecond=$refstatecond;
1.52      www      5759:               }
                   5760:           }
1.148     www      5761:         }
1.29      www      5762:        }
1.52      www      5763:    }
1.29      www      5764: 
1.52      www      5765: #
1.103     harris41 5766: # Gathered now: all privileges that could apply, and condition number
1.52      www      5767: # 
                   5768: #
                   5769: # Full or no access?
                   5770: #
1.29      www      5771: 
1.52      www      5772:     if ($thisallowed=~/F/) {
                   5773: 	return 'F';
                   5774:     }
1.29      www      5775: 
1.52      www      5776:     unless ($thisallowed) {
                   5777:         return '';
                   5778:     }
1.29      www      5779: 
1.52      www      5780: # Restrictions exist, deal with them
                   5781: #
                   5782: #   C:according to course preferences
                   5783: #   R:according to resource settings
                   5784: #   L:unless locked
                   5785: #   X:according to user session state
                   5786: #
                   5787: 
                   5788: # Possibly locked functionality, check all courses
1.54      www      5789: # Locks might take effect only after 10 minutes cache expiration for other
                   5790: # courses, and 2 minutes for current course
1.52      www      5791: 
                   5792:     my $envkey;
                   5793:     if ($thisallowed=~/L/) {
1.1000    raeburn  5794:         foreach $envkey (keys(%env)) {
1.54      www      5795:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5796:                my $courseid=$2;
                   5797:                my $roleid=$1.'.'.$2;
1.92      www      5798:                $courseid=~s/^\///;
1.54      www      5799:                my $expiretime=600;
1.620     albertel 5800:                if ($env{'request.role'} eq $roleid) {
1.54      www      5801: 		  $expiretime=120;
                   5802:                }
                   5803: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5804:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5805:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5806: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5807:                }
1.620     albertel 5808:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5809:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5810: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5811:                        &log($env{'user.domain'},$env{'user.name'},
                   5812:                             $env{'user.home'},
1.57      www      5813:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5814:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5815:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5816: 		       return '';
                   5817:                    }
                   5818:                }
1.620     albertel 5819:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5820:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5821: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5822:                        &log($env{'user.domain'},$env{'user.name'},
                   5823:                             $env{'user.home'},
1.57      www      5824:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5825:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5826:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5827: 		       return '';
                   5828:                    }
                   5829:                }
                   5830: 	   }
1.29      www      5831:        }
1.52      www      5832:     }
                   5833:    
                   5834: #
                   5835: # Rest of the restrictions depend on selected course
                   5836: #
                   5837: 
1.620     albertel 5838:     unless ($env{'request.course.id'}) {
1.766     albertel 5839: 	if ($thisallowed eq 'A') {
                   5840: 	    return 'A';
1.814     raeburn  5841:         } elsif ($thisallowed eq 'B') {
                   5842:             return 'B';
1.766     albertel 5843: 	} else {
                   5844: 	    return '1';
                   5845: 	}
1.52      www      5846:     }
1.29      www      5847: 
1.52      www      5848: #
                   5849: # Now user is definitely in a course
                   5850: #
1.53      www      5851: 
                   5852: 
                   5853: # Course preferences
                   5854: 
                   5855:    if ($thisallowed=~/C/) {
1.620     albertel 5856:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5857:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5858:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5859: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5860: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5861: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5862: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5863: 			$env{'request.course.id'});
                   5864: 	   }
1.237     www      5865:            return '';
                   5866:        }
                   5867: 
1.620     albertel 5868:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5869: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5870: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5871: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5872: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5873: 			$env{'request.course.id'});
                   5874: 	   }
1.54      www      5875:            return '';
                   5876:        }
1.53      www      5877:    }
                   5878: 
                   5879: # Resource preferences
                   5880: 
                   5881:    if ($thisallowed=~/R/) {
1.620     albertel 5882:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5883:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5884: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5885: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5886: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5887: 	   }
                   5888: 	   return '';
1.54      www      5889:        }
1.53      www      5890:    }
1.30      www      5891: 
1.246     www      5892: # Restricted by state or randomout?
1.30      www      5893: 
1.52      www      5894:    if ($thisallowed=~/X/) {
1.620     albertel 5895:       if ($env{'acc.randomout'}) {
1.579     albertel 5896: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5897:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5898:             return ''; 
                   5899:          }
1.247     www      5900:       }
                   5901:       if (&condval($statecond)) {
1.52      www      5902: 	 return '2';
                   5903:       } else {
                   5904:          return '';
                   5905:       }
                   5906:    }
1.30      www      5907: 
1.766     albertel 5908:     if ($thisallowed eq 'A') {
                   5909: 	return 'A';
1.814     raeburn  5910:     } elsif ($thisallowed eq 'B') {
                   5911:         return 'B';
1.766     albertel 5912:     }
1.52      www      5913:    return 'F';
1.232     www      5914: }
                   5915: 
1.710     albertel 5916: sub split_uri_for_cond {
                   5917:     my $uri=&deversion(&declutter(shift));
                   5918:     my @uriparts=split(/\//,$uri);
                   5919:     my $filename=pop(@uriparts);
                   5920:     my $pathname=join('/',@uriparts);
                   5921:     return ($pathname,$filename);
                   5922: }
1.232     www      5923: # --------------------------------------------------- Is a resource on the map?
                   5924: 
                   5925: sub is_on_map {
1.710     albertel 5926:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5927:     #Trying to find the conditional for the file
1.620     albertel 5928:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5929: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5930:     if ($match) {
1.289     bowersj2 5931: 	return (1,$1);
                   5932:     } else {
1.434     www      5933: 	return (0,0);
1.289     bowersj2 5934:     }
1.12      www      5935: }
                   5936: 
1.427     www      5937: # --------------------------------------------------------- Get symb from alias
                   5938: 
                   5939: sub get_symb_from_alias {
                   5940:     my $symb=shift;
                   5941:     my ($map,$resid,$url)=&decode_symb($symb);
                   5942: # Already is a symb
                   5943:     if ($url) { return $symb; }
                   5944: # Must be an alias
                   5945:     my $aliassymb='';
                   5946:     my %bighash;
1.620     albertel 5947:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5948:                             &GDBM_READER(),0640)) {
                   5949:         my $rid=$bighash{'mapalias_'.$symb};
                   5950: 	if ($rid) {
                   5951: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5952: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5953: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5954: 	}
                   5955:         untie %bighash;
                   5956:     }
                   5957:     return $aliassymb;
                   5958: }
                   5959: 
1.12      www      5960: # ----------------------------------------------------------------- Define Role
                   5961: 
                   5962: sub definerole {
                   5963:   if (allowed('mcr','/')) {
                   5964:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5965:     foreach my $role (split(':',$sysrole)) {
                   5966: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5967:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5968:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5969: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5970:                return "refused:s:$crole&$cqual"; 
                   5971:             }
                   5972:         }
1.191     harris41 5973:     }
1.800     albertel 5974:     foreach my $role (split(':',$domrole)) {
                   5975: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5976:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5977:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5978: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5979:                return "refused:d:$crole&$cqual"; 
                   5980:             }
                   5981:         }
1.191     harris41 5982:     }
1.800     albertel 5983:     foreach my $role (split(':',$courole)) {
                   5984: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5985:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5986:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5987: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5988:                return "refused:c:$crole&$cqual"; 
                   5989:             }
                   5990:         }
1.191     harris41 5991:     }
1.620     albertel 5992:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5993:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5994: 	        "rolesdef_$rolename=".
                   5995:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5996:     return reply($command,$env{'user.home'});
1.12      www      5997:   } else {
                   5998:     return 'refused';
                   5999:   }
1.105     harris41 6000: }
                   6001: 
                   6002: # ---------------- Make a metadata query against the network of library servers
                   6003: 
                   6004: sub metadata_query {
1.244     matthew  6005:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6006:     my %rhash;
1.845     albertel 6007:     my %libserv = &all_library();
1.244     matthew  6008:     my @server_list = (defined($server_array) ? @$server_array
                   6009:                                               : keys(%libserv) );
                   6010:     for my $server (@server_list) {
1.118     harris41 6011: 	unless ($custom or $customshow) {
                   6012: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6013: 	    $rhash{$server}=$reply;
                   6014: 	}
                   6015: 	else {
                   6016: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6017: 			     &escape($custom).':'.&escape($customshow),
                   6018: 			     $server);
                   6019: 	    $rhash{$server}=$reply;
                   6020: 	}
1.112     harris41 6021:     }
1.118     harris41 6022:     return \%rhash;
1.240     www      6023: }
                   6024: 
                   6025: # ----------------------------------------- Send log queries and wait for reply
                   6026: 
                   6027: sub log_query {
                   6028:     my ($uname,$udom,$query,%filters)=@_;
                   6029:     my $uhome=&homeserver($uname,$udom);
                   6030:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6031:     my $uhost=&hostname($uhome);
1.800     albertel 6032:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6033:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6034:                        $uhome);
1.479     albertel 6035:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6036:     return get_query_reply($queryid);
                   6037: }
                   6038: 
1.818     raeburn  6039: # -------------------------- Update MySQL table for portfolio file
                   6040: 
                   6041: sub update_portfolio_table {
1.821     raeburn  6042:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6043:     if ($group ne '') {
                   6044:         $file_name =~s /^\Q$group\E//;
                   6045:     }
1.818     raeburn  6046:     my $homeserver = &homeserver($uname,$udom);
                   6047:     my $queryid=
1.821     raeburn  6048:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6049:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6050:     my $reply = &get_query_reply($queryid);
                   6051:     return $reply;
                   6052: }
                   6053: 
1.899     raeburn  6054: # -------------------------- Update MySQL allusers table
                   6055: 
                   6056: sub update_allusers_table {
                   6057:     my ($uname,$udom,$names) = @_;
                   6058:     my $homeserver = &homeserver($uname,$udom);
                   6059:     my $queryid=
                   6060:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6061:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6062:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6063:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6064:                'generation='.&escape($names->{'generation'}).'%%'.
                   6065:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6066:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6067:     return;
1.899     raeburn  6068: }
                   6069: 
1.508     raeburn  6070: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6071: 
                   6072: sub fetch_enrollment_query {
1.511     raeburn  6073:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6074:     my $homeserver;
1.547     raeburn  6075:     my $maxtries = 1;
1.508     raeburn  6076:     if ($context eq 'automated') {
                   6077:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6078:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6079:     } else {
                   6080:         $homeserver = &homeserver($cnum,$dom);
                   6081:     }
1.838     albertel 6082:     my $host=&hostname($homeserver);
1.506     raeburn  6083:     my $cmd = '';
1.1000    raeburn  6084:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6085:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6086:     }
                   6087:     $cmd =~ s/%%$//;
                   6088:     $cmd = &escape($cmd);
                   6089:     my $query = 'fetchenrollment';
1.620     albertel 6090:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6091:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6092:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6093:         return 'error: '.$queryid;
                   6094:     }
1.506     raeburn  6095:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6096:     my $tries = 1;
                   6097:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6098:         $reply = &get_query_reply($queryid);
                   6099:         $tries ++;
                   6100:     }
1.526     raeburn  6101:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6102:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6103:     } else {
1.901     albertel 6104:         my @responses = split(/:/,$reply);
1.515     raeburn  6105:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6106:             foreach my $line (@responses) {
                   6107:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6108:                 $$replyref{$key} = $value;
                   6109:             }
                   6110:         } else {
1.1117    foxr     6111:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6112:             foreach my $line (@responses) {
                   6113:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6114:                 $$replyref{$key} = $value;
                   6115:                 if ($value > 0) {
1.800     albertel 6116:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6117:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6118:                         my $destname = $pathname.'/'.$filename;
                   6119:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6120:                         if ($xml_classlist =~ /^error/) {
                   6121:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6122:                         } else {
1.506     raeburn  6123:                             if ( open(FILE,">$destname") ) {
                   6124:                                 print FILE &unescape($xml_classlist);
                   6125:                                 close(FILE);
1.526     raeburn  6126:                             } else {
                   6127:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6128:                             }
                   6129:                         }
                   6130:                     }
                   6131:                 }
                   6132:             }
                   6133:         }
                   6134:         return 'ok';
                   6135:     }
                   6136:     return 'error';
                   6137: }
                   6138: 
1.242     www      6139: sub get_query_reply {
                   6140:     my $queryid=shift;
1.1117    foxr     6141:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6142:     my $reply='';
                   6143:     for (1..100) {
                   6144: 	sleep 2;
                   6145:         if (-e $replyfile.'.end') {
1.448     albertel 6146: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6147: 		$reply = join('',<$fh>);
                   6148: 		close($fh);
1.240     www      6149: 	   } else { return 'error: reply_file_error'; }
1.242     www      6150:            return &unescape($reply);
                   6151: 	}
1.240     www      6152:     }
1.242     www      6153:     return 'timeout:'.$queryid;
1.240     www      6154: }
                   6155: 
                   6156: sub courselog_query {
1.241     www      6157: #
                   6158: # possible filters:
                   6159: # url: url or symb
                   6160: # username
                   6161: # domain
                   6162: # action: view, submit, grade
                   6163: # start: timestamp
                   6164: # end: timestamp
                   6165: #
1.240     www      6166:     my (%filters)=@_;
1.620     albertel 6167:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6168:     if ($filters{'url'}) {
                   6169: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6170:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6171:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6172:     }
1.620     albertel 6173:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6174:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6175:     return &log_query($cname,$cdom,'courselog',%filters);
                   6176: }
                   6177: 
                   6178: sub userlog_query {
1.858     raeburn  6179: #
                   6180: # possible filters:
                   6181: # action: log check role
                   6182: # start: timestamp
                   6183: # end: timestamp
                   6184: #
1.240     www      6185:     my ($uname,$udom,%filters)=@_;
                   6186:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6187: }
                   6188: 
1.506     raeburn  6189: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6190: 
                   6191: sub auto_run {
1.508     raeburn  6192:     my ($cnum,$cdom) = @_;
1.876     raeburn  6193:     my $response = 0;
                   6194:     my $settings;
                   6195:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6196:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6197:         $settings = $domconfig{'autoenroll'};
                   6198:         if ($settings->{'run'} eq '1') {
                   6199:             $response = 1;
                   6200:         }
                   6201:     } else {
1.934     raeburn  6202:         my $homeserver;
                   6203:         if (&is_course($cdom,$cnum)) {
                   6204:             $homeserver = &homeserver($cnum,$cdom);
                   6205:         } else {
                   6206:             $homeserver = &domain($cdom,'primary');
                   6207:         }
                   6208:         if ($homeserver ne 'no_host') {
                   6209:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6210:         }
1.876     raeburn  6211:     }
1.506     raeburn  6212:     return $response;
                   6213: }
1.776     albertel 6214: 
1.506     raeburn  6215: sub auto_get_sections {
1.508     raeburn  6216:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6217:     my $homeserver;
                   6218:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6219:         $homeserver = &homeserver($cnum,$cdom);
                   6220:     }
                   6221:     if (!defined($homeserver)) { 
                   6222:         if ($cdom =~ /^$match_domain$/) {
                   6223:             $homeserver = &domain($cdom,'primary');
                   6224:         }
                   6225:     }
                   6226:     my @secs;
                   6227:     if (defined($homeserver)) {
                   6228:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6229:         unless ($response eq 'refused') {
                   6230:             @secs = split(/:/,$response);
                   6231:         }
1.506     raeburn  6232:     }
                   6233:     return @secs;
                   6234: }
1.776     albertel 6235: 
1.506     raeburn  6236: sub auto_new_course {
1.1099    raeburn  6237:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6238:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6239:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6240:     return $response;
                   6241: }
1.776     albertel 6242: 
1.506     raeburn  6243: sub auto_validate_courseID {
1.508     raeburn  6244:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6245:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6246:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6247:     return $response;
                   6248: }
1.776     albertel 6249: 
1.1007    raeburn  6250: sub auto_validate_instcode {
1.1020    raeburn  6251:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6252:     my ($homeserver,$response);
                   6253:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6254:         $homeserver = &homeserver($cnum,$cdom);
                   6255:     }
                   6256:     if (!defined($homeserver)) {
                   6257:         if ($cdom =~ /^$match_domain$/) {
                   6258:             $homeserver = &domain($cdom,'primary');
                   6259:         }
                   6260:     }
1.1065    raeburn  6261:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6262:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6263:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6264:     return ($outcome,$description);
1.1007    raeburn  6265: }
                   6266: 
1.506     raeburn  6267: sub auto_create_password {
1.873     raeburn  6268:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6269:     my ($homeserver,$response);
1.506     raeburn  6270:     my $create_passwd = 0;
                   6271:     my $authchk = '';
1.873     raeburn  6272:     if ($udom =~ /^$match_domain$/) {
                   6273:         $homeserver = &domain($udom,'primary');
                   6274:     }
                   6275:     if ($homeserver eq '') {
                   6276:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6277:             $homeserver = &homeserver($cnum,$cdom);
                   6278:         }
                   6279:     }
                   6280:     if ($homeserver eq '') {
                   6281:         $authchk = 'nodomain';
1.506     raeburn  6282:     } else {
1.873     raeburn  6283:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6284:         if ($response eq 'refused') {
                   6285:             $authchk = 'refused';
                   6286:         } else {
1.901     albertel 6287:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6288:         }
1.506     raeburn  6289:     }
                   6290:     return ($authparam,$create_passwd,$authchk);
                   6291: }
                   6292: 
1.706     raeburn  6293: sub auto_photo_permission {
                   6294:     my ($cnum,$cdom,$students) = @_;
                   6295:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6296:     my ($outcome,$perm_reqd,$conditions) = 
                   6297: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6298:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6299: 	return (undef,undef);
                   6300:     }
1.706     raeburn  6301:     return ($outcome,$perm_reqd,$conditions);
                   6302: }
                   6303: 
                   6304: sub auto_checkphotos {
                   6305:     my ($uname,$udom,$pid) = @_;
                   6306:     my $homeserver = &homeserver($uname,$udom);
                   6307:     my ($result,$resulttype);
                   6308:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6309: 				   &escape($uname).':'.&escape($pid),
                   6310: 				   $homeserver));
1.709     albertel 6311:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6312: 	return (undef,undef);
                   6313:     }
1.706     raeburn  6314:     if ($outcome) {
                   6315:         ($result,$resulttype) = split(/:/,$outcome);
                   6316:     } 
                   6317:     return ($result,$resulttype);
                   6318: }
                   6319: 
                   6320: sub auto_photochoice {
                   6321:     my ($cnum,$cdom) = @_;
                   6322:     my $homeserver = &homeserver($cnum,$cdom);
                   6323:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6324: 						       &escape($cdom),
                   6325: 						       $homeserver)));
1.709     albertel 6326:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6327: 	return (undef,undef);
                   6328:     }
1.706     raeburn  6329:     return ($update,$comment);
                   6330: }
                   6331: 
                   6332: sub auto_photoupdate {
                   6333:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6334:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6335:     my $host=&hostname($homeserver);
1.706     raeburn  6336:     my $cmd = '';
                   6337:     my $maxtries = 1;
1.800     albertel 6338:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6339:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6340:     }
                   6341:     $cmd =~ s/%%$//;
                   6342:     $cmd = &escape($cmd);
                   6343:     my $query = 'institutionalphotos';
                   6344:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6345:     unless ($queryid=~/^\Q$host\E\_/) {
                   6346:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6347:         return 'error: '.$queryid;
                   6348:     }
                   6349:     my $reply = &get_query_reply($queryid);
                   6350:     my $tries = 1;
                   6351:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6352:         $reply = &get_query_reply($queryid);
                   6353:         $tries ++;
                   6354:     }
                   6355:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6356:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6357:     } else {
                   6358:         my @responses = split(/:/,$reply);
                   6359:         my $outcome = shift(@responses); 
                   6360:         foreach my $item (@responses) {
                   6361:             my ($key,$value) = split(/=/,$item);
                   6362:             $$photo{$key} = $value;
                   6363:         }
                   6364:         return $outcome;
                   6365:     }
                   6366:     return 'error';
                   6367: }
                   6368: 
1.521     raeburn  6369: sub auto_instcode_format {
1.793     albertel 6370:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6371: 	$cat_order) = @_;
1.521     raeburn  6372:     my $courses = '';
1.772     raeburn  6373:     my @homeservers;
1.521     raeburn  6374:     if ($caller eq 'global') {
1.841     albertel 6375: 	my %servers = &get_servers($codedom,'library');
                   6376: 	foreach my $tryserver (keys(%servers)) {
                   6377: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6378: 		push(@homeservers,$tryserver);
                   6379: 	    }
1.584     raeburn  6380:         }
1.1022    raeburn  6381:     } elsif ($caller eq 'requests') {
                   6382:         if ($codedom =~ /^$match_domain$/) {
                   6383:             my $chome = &domain($codedom,'primary');
                   6384:             unless ($chome eq 'no_host') {
                   6385:                 push(@homeservers,$chome);
                   6386:             }
                   6387:         }
1.521     raeburn  6388:     } else {
1.772     raeburn  6389:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6390:     }
1.793     albertel 6391:     foreach my $code (keys(%{$instcodes})) {
                   6392:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6393:     }
                   6394:     chop($courses);
1.772     raeburn  6395:     my $ok_response = 0;
                   6396:     my $response;
                   6397:     while (@homeservers > 0 && $ok_response == 0) {
                   6398:         my $server = shift(@homeservers); 
                   6399:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6400:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6401:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6402: 		split(/:/,$response);
1.772     raeburn  6403:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6404:             push(@{$codetitles},&str2array($codetitles_str));
                   6405:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6406:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6407:             $ok_response = 1;
                   6408:         }
                   6409:     }
                   6410:     if ($ok_response) {
1.521     raeburn  6411:         return 'ok';
1.772     raeburn  6412:     } else {
                   6413:         return $response;
1.521     raeburn  6414:     }
                   6415: }
                   6416: 
1.792     raeburn  6417: sub auto_instcode_defaults {
                   6418:     my ($domain,$returnhash,$code_order) = @_;
                   6419:     my @homeservers;
1.841     albertel 6420: 
                   6421:     my %servers = &get_servers($domain,'library');
                   6422:     foreach my $tryserver (keys(%servers)) {
                   6423: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6424: 	    push(@homeservers,$tryserver);
                   6425: 	}
1.792     raeburn  6426:     }
1.841     albertel 6427: 
1.792     raeburn  6428:     my $response;
1.841     albertel 6429:     foreach my $server (@homeservers) {
1.792     raeburn  6430:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6431:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6432: 	
                   6433: 	foreach my $pair (split(/\&/,$response)) {
                   6434: 	    my ($name,$value)=split(/\=/,$pair);
                   6435: 	    if ($name eq 'code_order') {
                   6436: 		@{$code_order} = split(/\&/,&unescape($value));
                   6437: 	    } else {
                   6438: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6439: 	    }
                   6440: 	}
                   6441: 	return 'ok';
1.792     raeburn  6442:     }
1.841     albertel 6443: 
                   6444:     return $response;
1.1003    raeburn  6445: }
                   6446: 
                   6447: sub auto_possible_instcodes {
1.1007    raeburn  6448:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6449:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6450:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6451:         return;
                   6452:     }
1.1003    raeburn  6453:     my (@homeservers,$uhome);
                   6454:     if (defined(&domain($domain,'primary'))) {
                   6455:         $uhome=&domain($domain,'primary');
                   6456:         push(@homeservers,&domain($domain,'primary'));
                   6457:     } else {
                   6458:         my %servers = &get_servers($domain,'library');
                   6459:         foreach my $tryserver (keys(%servers)) {
                   6460:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6461:                 push(@homeservers,$tryserver);
                   6462:             }
                   6463:         }
                   6464:     }
                   6465:     my $response;
                   6466:     foreach my $server (@homeservers) {
                   6467:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6468:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6469:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6470:             split(':',$response);
                   6471:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6472:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6473:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6474:             my ($name,$value)=split('=',$item);
                   6475:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6476:         }
                   6477:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6478:             my ($name,$value)=split('=',$item);
                   6479:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6480:         }
                   6481:         return 'ok';
                   6482:     }
                   6483:     return $response;
                   6484: }
1.792     raeburn  6485: 
1.1010    raeburn  6486: sub auto_courserequest_checks {
                   6487:     my ($dom) = @_;
1.1020    raeburn  6488:     my ($homeserver,%validations);
                   6489:     if ($dom =~ /^$match_domain$/) {
                   6490:         $homeserver = &domain($dom,'primary');
                   6491:     }
                   6492:     unless ($homeserver eq 'no_host') {
                   6493:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6494:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6495:             my @items = split(/&/,$response);
                   6496:             foreach my $item (@items) {
                   6497:                 my ($key,$value) = split('=',$item);
                   6498:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6499:             }
                   6500:         }
                   6501:     }
1.1010    raeburn  6502:     return %validations; 
                   6503: }
                   6504: 
1.1020    raeburn  6505: sub auto_courserequest_validation {
                   6506:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6507:     my ($homeserver,$response);
                   6508:     if ($dom =~ /^$match_domain$/) {
                   6509:         $homeserver = &domain($dom,'primary');
                   6510:     }
                   6511:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6512:           
1.1020    raeburn  6513:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6514:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6515:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6516:                                     $homeserver));
                   6517:     }
                   6518:     return $response;
                   6519: }
                   6520: 
1.777     albertel 6521: sub auto_validate_class_sec {
1.918     raeburn  6522:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6523:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6524:     my $ownerlist;
                   6525:     if (ref($owners) eq 'ARRAY') {
                   6526:         $ownerlist = join(',',@{$owners});
                   6527:     } else {
                   6528:         $ownerlist = $owners;
                   6529:     }
1.773     raeburn  6530:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6531:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6532:     return $response;
                   6533: }
                   6534: 
1.679     raeburn  6535: # ------------------------------------------------------- Course Group routines
                   6536: 
                   6537: sub get_coursegroups {
1.809     raeburn  6538:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6539:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6540: }
                   6541: 
1.679     raeburn  6542: sub modify_coursegroup {
                   6543:     my ($cdom,$cnum,$groupsettings) = @_;
                   6544:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6545: }
                   6546: 
1.809     raeburn  6547: sub toggle_coursegroup_status {
                   6548:     my ($cdom,$cnum,$group,$action) = @_;
                   6549:     my ($from_namespace,$to_namespace);
                   6550:     if ($action eq 'delete') {
                   6551:         $from_namespace = 'coursegroups';
                   6552:         $to_namespace = 'deleted_groups';
                   6553:     } else {
                   6554:         $from_namespace = 'deleted_groups';
                   6555:         $to_namespace = 'coursegroups';
                   6556:     }
                   6557:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6558:     if (my $tmp = &error(%curr_group)) {
                   6559:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6560:         return ('read error',$tmp);
                   6561:     } else {
                   6562:         my %savedsettings = %curr_group; 
1.809     raeburn  6563:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6564:         my $deloutcome;
                   6565:         if ($result eq 'ok') {
1.809     raeburn  6566:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6567:         } else {
                   6568:             return ('write error',$result);
                   6569:         }
                   6570:         if ($deloutcome eq 'ok') {
                   6571:             return 'ok';
                   6572:         } else {
                   6573:             return ('delete error',$deloutcome);
                   6574:         }
                   6575:     }
                   6576: }
                   6577: 
1.679     raeburn  6578: sub modify_group_roles {
1.957     raeburn  6579:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6580:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6581:     my $role = 'gr/'.&escape($userprivs);
                   6582:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6583:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6584:     if ($result eq 'ok') {
                   6585:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6586:     }
1.679     raeburn  6587:     return $result;
                   6588: }
                   6589: 
                   6590: sub modify_coursegroup_membership {
                   6591:     my ($cdom,$cnum,$membership) = @_;
                   6592:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6593:     return $result;
                   6594: }
                   6595: 
1.682     raeburn  6596: sub get_active_groups {
                   6597:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6598:     my $now = time;
                   6599:     my %groups = ();
                   6600:     foreach my $key (keys(%env)) {
1.811     albertel 6601:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6602:             my ($start,$end) = split(/\./,$env{$key});
                   6603:             if (($end!=0) && ($end<$now)) { next; }
                   6604:             if (($start!=0) && ($start>$now)) { next; }
                   6605:             if ($1 eq $cdom && $2 eq $cnum) {
                   6606:                 $groups{$3} = $env{$key} ;
                   6607:             }
                   6608:         }
                   6609:     }
                   6610:     return %groups;
                   6611: }
                   6612: 
1.683     raeburn  6613: sub get_group_membership {
                   6614:     my ($cdom,$cnum,$group) = @_;
                   6615:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6616: }
                   6617: 
                   6618: sub get_users_groups {
                   6619:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6620:     my @usersgroups;
1.683     raeburn  6621:     my $cachetime=1800;
                   6622: 
                   6623:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6624:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6625:     if (defined($cached)) {
1.734     albertel 6626:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6627:     } else {  
                   6628:         $grouplist = '';
1.816     raeburn  6629:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6630:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6631:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6632:         my $access_end = $env{'course.'.$courseid.
                   6633:                               '.default_enrollment_end_date'};
                   6634:         my $now = time;
                   6635:         foreach my $key (keys(%roleshash)) {
                   6636:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6637:                 my $group = $1;
                   6638:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6639:                     my $start = $2;
                   6640:                     my $end = $1;
                   6641:                     if ($start == -1) { next; } # deleted from group
                   6642:                     if (($start!=0) && ($start>$now)) { next; }
                   6643:                     if (($end!=0) && ($end<$now)) {
                   6644:                         if ($access_end && $access_end < $now) {
                   6645:                             if ($access_end - $end < 86400) {
                   6646:                                 push(@usersgroups,$group);
1.733     raeburn  6647:                             }
                   6648:                         }
1.817     raeburn  6649:                         next;
1.733     raeburn  6650:                     }
1.817     raeburn  6651:                     push(@usersgroups,$group);
1.683     raeburn  6652:                 }
                   6653:             }
                   6654:         }
1.817     raeburn  6655:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6656:         $grouplist = join(':',@usersgroups);
                   6657:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6658:     }
1.733     raeburn  6659:     return @usersgroups;
1.683     raeburn  6660: }
                   6661: 
                   6662: sub devalidate_getgroups_cache {
                   6663:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6664:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6665: 
1.683     raeburn  6666:     my $hashid="$udom:$uname:$courseid";
                   6667:     &devalidate_cache_new('getgroups',$hashid);
                   6668: }
                   6669: 
1.12      www      6670: # ------------------------------------------------------------------ Plain Text
                   6671: 
                   6672: sub plaintext {
1.988     raeburn  6673:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6674:     if ($short =~ m{^cr/}) {
1.758     albertel 6675: 	return (split('/',$short))[-1];
                   6676:     }
1.742     raeburn  6677:     if (!defined($cid)) {
                   6678:         $cid = $env{'request.course.id'};
                   6679:     }
                   6680:     my %rolenames = (
1.1008    raeburn  6681:                       Course    => 'std',
                   6682:                       Community => 'alt1',
1.742     raeburn  6683:                     );
1.1037    raeburn  6684:     if ($cid ne '') {
                   6685:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6686:             unless ($forcedefault) {
                   6687:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6688:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6689:                 return &Apache::lonlocal::mt($roletext);
                   6690:             }
                   6691:         }
                   6692:     }
                   6693:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6694:         (defined($rolenames{$type})) && 
                   6695:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6696:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6697:     } elsif ($cid ne '') {
                   6698:         my $crstype = $env{'course.'.$cid.'.type'};
                   6699:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6700:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6701:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6702:         }
1.742     raeburn  6703:     }
1.1037    raeburn  6704:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6705: }
                   6706: 
                   6707: # ----------------------------------------------------------------- Assign Role
                   6708: 
                   6709: sub assignrole {
1.957     raeburn  6710:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6711:         $context)=@_;
1.21      www      6712:     my $mrole;
                   6713:     if ($role =~ /^cr\//) {
1.393     www      6714:         my $cwosec=$url;
1.811     albertel 6715:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6716: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6717:            my $refused = 1;
                   6718:            if ($context eq 'requestcourses') {
                   6719:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6720:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6721:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6722:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6723:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6724:                            if ($crsenv{'internal.courseowner'} eq
                   6725:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6726:                                $refused = '';
                   6727:                            }
                   6728:                        }
                   6729:                    }
                   6730:                }
                   6731:            }
                   6732:            if ($refused) {
                   6733:                &logthis('Refused custom assignrole: '.
                   6734:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6735:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6736:                return 'refused';
                   6737:            }
1.104     www      6738:         }
1.21      www      6739:         $mrole='cr';
1.678     raeburn  6740:     } elsif ($role =~ /^gr\//) {
                   6741:         my $cwogrp=$url;
1.811     albertel 6742:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6743:         unless (&allowed('mdg',$cwogrp)) {
                   6744:             &logthis('Refused group assignrole: '.
                   6745:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6746:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6747:             return 'refused';
                   6748:         }
                   6749:         $mrole='gr';
1.21      www      6750:     } else {
1.82      www      6751:         my $cwosec=$url;
1.811     albertel 6752:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6753:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6754:             my $refused;
                   6755:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6756:                 if (!(&allowed('c'.$role,$url))) {
                   6757:                     $refused = 1;
                   6758:                 }
                   6759:             } else {
                   6760:                 $refused = 1;
                   6761:             }
1.947     raeburn  6762:             if ($refused) {
1.1045    raeburn  6763:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6764:                 if (!$selfenroll && $context eq 'course') {
                   6765:                     my %crsenv;
                   6766:                     if ($role eq 'cc' || $role eq 'co') {
                   6767:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6768:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6769:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6770:                                 if ($crsenv{'internal.courseowner'} eq 
                   6771:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6772:                                     $refused = '';
                   6773:                                 }
                   6774:                             }
                   6775:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6776:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6777:                                 if ($crsenv{'internal.courseowner'} eq 
                   6778:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6779:                                     $refused = '';
                   6780:                                 }
                   6781:                             }
                   6782:                         }
                   6783:                     }
                   6784:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6785:                     $refused = '';
1.1017    raeburn  6786:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6787:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6788:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6789:                         my $wrongcc;
                   6790:                         if ($cnum =~ /^$match_community$/) {
                   6791:                             $wrongcc = 1 if ($role eq 'cc');
                   6792:                         } else {
                   6793:                             $wrongcc = 1 if ($role eq 'co');
                   6794:                         }
                   6795:                         unless ($wrongcc) {
                   6796:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6797:                             if ($crsenv{'internal.courseowner'} eq 
                   6798:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6799:                                 $refused = '';
                   6800:                             }
1.1017    raeburn  6801:                         }
                   6802:                     }
                   6803:                 }
                   6804:                 if ($refused) {
1.947     raeburn  6805:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6806:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6807: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6808:                     return 'refused';
                   6809:                 }
1.932     raeburn  6810:             }
1.104     www      6811:         }
1.21      www      6812:         $mrole=$role;
                   6813:     }
1.620     albertel 6814:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6815:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6816:     if ($end) { $command.='_'.$end; }
1.21      www      6817:     if ($start) {
                   6818: 	if ($end) { 
1.81      www      6819:            $command.='_'.$start; 
1.21      www      6820:         } else {
1.81      www      6821:            $command.='_0_'.$start;
1.21      www      6822:         }
                   6823:     }
1.739     raeburn  6824:     my $origstart = $start;
                   6825:     my $origend = $end;
1.957     raeburn  6826:     my $delflag;
1.357     www      6827: # actually delete
                   6828:     if ($deleteflag) {
1.373     www      6829: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6830: # modify command to delete the role
1.620     albertel 6831:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6832:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6833: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6834: # set start and finish to negative values for userrolelog
                   6835:            $start=-1;
                   6836:            $end=-1;
1.957     raeburn  6837:            $delflag = 1;
1.357     www      6838:         }
                   6839:     }
                   6840: # send command
1.349     www      6841:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6842: # log new user role if status is ok
1.349     www      6843:     if ($answer eq 'ok') {
1.663     raeburn  6844: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6845: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6846:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6847:         unless ($role =~ /^gr/) {
                   6848:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6849:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6850:         }
1.1053    raeburn  6851:         if ($role eq 'cc') {
                   6852:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6853:         }
1.349     www      6854:     }
                   6855:     return $answer;
1.169     harris41 6856: }
                   6857: 
1.1053    raeburn  6858: sub autoupdate_coowners {
                   6859:     my ($url,$end,$start,$uname,$udom) = @_;
                   6860:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6861:     if (($cdom ne '') && ($cnum ne '')) {
                   6862:         my $now = time;
                   6863:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6864:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6865:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6866:             my $instcode = $coursehash{'internal.coursecode'};
                   6867:             if ($instcode ne '') {
1.1056    raeburn  6868:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6869:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6870:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6871:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6872:                         if ($result eq 'valid') {
                   6873:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6874:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6875:                                     push(@newcoowners,$coowner);
                   6876:                                 }
                   6877:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6878:                                     push(@newcoowners,$uname.':'.$udom);
                   6879:                                 }
                   6880:                                 @newcoowners = sort(@newcoowners);
                   6881:                             } else {
                   6882:                                 push(@newcoowners,$uname.':'.$udom);
                   6883:                             }
                   6884:                         } else {
                   6885:                             if ($coursehash{'internal.co-owners'}) {
                   6886:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6887:                                     unless ($coowner eq $uname.':'.$udom) {
                   6888:                                         push(@newcoowners,$coowner);
                   6889:                                     }
                   6890:                                 }
                   6891:                                 unless (@newcoowners > 0) {
                   6892:                                     $delcoowners = 1;
                   6893:                                     $coowners = '';
                   6894:                                 }
                   6895:                             }
                   6896:                         }
                   6897:                         if (@newcoowners || $delcoowners) {
                   6898:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6899:                                             $delcoowners,@newcoowners);
                   6900:                         }
                   6901:                     }
                   6902:                 }
                   6903:             }
                   6904:         }
                   6905:     }
                   6906: }
                   6907: 
                   6908: sub store_coowners {
                   6909:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6910:     my $cid = $cdom.'_'.$cnum;
                   6911:     my ($coowners,$delresult,$putresult);
                   6912:     if (@newcoowners) {
                   6913:         $coowners = join(',',@newcoowners);
                   6914:         my %coownershash = (
                   6915:                             'internal.co-owners' => $coowners,
                   6916:                            );
                   6917:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6918:         if ($putresult eq 'ok') {
                   6919:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6920:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6921:             }
                   6922:         }
                   6923:     }
                   6924:     if ($delcoowners) {
                   6925:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6926:         if ($delresult eq 'ok') {
                   6927:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6928:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6929:             }
                   6930:         }
                   6931:     }
                   6932:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6933:         my %crsinfo =
                   6934:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6935:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6936:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6937:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6938:         }
                   6939:     }
                   6940: }
                   6941: 
1.169     harris41 6942: # -------------------------------------------------- Modify user authentication
1.197     www      6943: # Overrides without validation
                   6944: 
1.169     harris41 6945: sub modifyuserauth {
                   6946:     my ($udom,$uname,$umode,$upass)=@_;
                   6947:     my $uhome=&homeserver($uname,$udom);
1.197     www      6948:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6949:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6950:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6951:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6952:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6953: 		     &escape($upass),$uhome);
1.620     albertel 6954:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6955:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6956:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6957:     &log($udom,,$uname,$uhome,
1.620     albertel 6958:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6959:                                      $env{'user.name'}.', '.$umode.
1.197     www      6960:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6961:     unless ($reply eq 'ok') {
1.197     www      6962:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6963: 	return 'error: '.$reply;
                   6964:     }   
1.170     harris41 6965:     return 'ok';
1.80      www      6966: }
                   6967: 
1.81      www      6968: # --------------------------------------------------------------- Modify a user
1.80      www      6969: 
1.81      www      6970: sub modifyuser {
1.206     matthew  6971:     my ($udom,    $uname, $uid,
                   6972:         $umode,   $upass, $first,
                   6973:         $middle,  $last,  $gene,
1.1058    raeburn  6974:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6975:     $udom= &LONCAPA::clean_domain($udom);
                   6976:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6977:     my $showcandelete = 'none';
                   6978:     if (ref($candelete) eq 'ARRAY') {
                   6979:         if (@{$candelete} > 0) {
                   6980:             $showcandelete = join(', ',@{$candelete});
                   6981:         }
                   6982:     }
1.81      www      6983:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6984:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6985: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6986:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6987:                                      ' desiredhome not specified'). 
1.620     albertel 6988:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6989:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6990:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6991:     my $newuser;
                   6992:     if ($uhome eq 'no_host') {
                   6993:         $newuser = 1;
                   6994:     }
1.80      www      6995: # ----------------------------------------------------------------- Create User
1.406     albertel 6996:     if (($uhome eq 'no_host') && 
                   6997: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6998:         my $unhome='';
1.844     albertel 6999:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7000:             $unhome = $desiredhome;
1.620     albertel 7001: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7002: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7003:         } else { # load balancing routine for determining $unhome
1.81      www      7004:             my $loadm=10000000;
1.841     albertel 7005: 	    my %servers = &get_servers($udom,'library');
                   7006: 	    foreach my $tryserver (keys(%servers)) {
                   7007: 		my $answer=reply('load',$tryserver);
                   7008: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7009: 		    $loadm=$answer;
                   7010: 		    $unhome=$tryserver;
                   7011: 		}
1.80      www      7012: 	    }
                   7013:         }
                   7014:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7015: 	    return 'error: unable to find a home server for '.$uname.
                   7016:                    ' in domain '.$udom;
1.80      www      7017:         }
                   7018:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7019:                          &escape($upass),$unhome);
                   7020: 	unless ($reply eq 'ok') {
                   7021:             return 'error: '.$reply;
                   7022:         }   
1.230     stredwic 7023:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7024:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7025: 	    return 'error: unable verify users home machine.';
1.80      www      7026:         }
1.209     matthew  7027:     }   # End of creation of new user
1.80      www      7028: # ---------------------------------------------------------------------- Add ID
                   7029:     if ($uid) {
                   7030:        $uid=~tr/A-Z/a-z/;
                   7031:        my %uidhash=&idrget($udom,$uname);
1.196     www      7032:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7033:          && (!$forceid)) {
1.80      www      7034: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7035: 	      return 'error: user id "'.$uid.'" does not match '.
                   7036:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7037:           }
                   7038:        } else {
                   7039: 	  &idput($udom,($uname => $uid));
                   7040:        }
                   7041:     }
                   7042: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7043:     my @tmp=&get('environment',
1.899     raeburn  7044: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7045:                     'permanentemail','inststatus'],
1.134     albertel 7046: 		   $udom,$uname);
1.1075    raeburn  7047:     my (%names,%oldnames);
1.313     matthew  7048:     if ($tmp[0] =~ m/^error:.*/) { 
                   7049:         %names=(); 
                   7050:     } else {
                   7051:         %names = @tmp;
1.1075    raeburn  7052:         %oldnames = %names;
1.313     matthew  7053:     }
1.388     www      7054: #
1.1058    raeburn  7055: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7056: # of users did not contain them), do not overwrite existing values
                   7057: # unless field is in $candelete array ref.  
                   7058: #
                   7059: 
                   7060:     my @fields = ('firstname','middlename','lastname','generation',
                   7061:                   'permanentemail','id');
                   7062:     my %newvalues;
                   7063:     if (ref($candelete) eq 'ARRAY') {
                   7064:         foreach my $field (@fields) {
                   7065:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7066:                 if ($field eq 'firstname') {
                   7067:                     $names{$field} = $first;
                   7068:                 } elsif ($field eq 'middlename') {
                   7069:                     $names{$field} = $middle;
                   7070:                 } elsif ($field eq 'lastname') {
                   7071:                     $names{$field} = $last;
                   7072:                 } elsif ($field eq 'generation') { 
                   7073:                     $names{$field} = $gene;
                   7074:                 } elsif ($field eq 'permanentemail') {
                   7075:                     $names{$field} = $email;
                   7076:                 } elsif ($field eq 'id') {
                   7077:                     $names{$field}  = $uid;
                   7078:                 }
                   7079:             }
                   7080:         }
                   7081:     }
1.388     www      7082:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7083:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7084:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7085:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7086:     if ($email) {
                   7087:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7088:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7089:     }
1.899     raeburn  7090:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7091:     if (defined($inststatus)) {
                   7092:         $names{'inststatus'} = '';
                   7093:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7094:         if (ref($usertypes) eq 'HASH') {
                   7095:             my @okstatuses; 
                   7096:             foreach my $item (split(/:/,$inststatus)) {
                   7097:                 if (defined($usertypes->{$item})) {
                   7098:                     push(@okstatuses,$item);  
                   7099:                 }
                   7100:             }
                   7101:             if (@okstatuses) {
                   7102:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7103:             }
                   7104:         }
                   7105:     }
1.1075    raeburn  7106:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7107:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7108:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7109:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7110:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7111:     } else {
                   7112:         $logmsg .= ' during self creation';
                   7113:     }
1.1075    raeburn  7114:     my $changed;
                   7115:     if ($newuser) {
                   7116:         $changed = 1;
                   7117:     } else {
                   7118:         foreach my $field (@fields) {
                   7119:             if ($names{$field} ne $oldnames{$field}) {
                   7120:                 $changed = 1;
                   7121:                 last;
                   7122:             }
                   7123:         }
                   7124:     }
                   7125:     unless ($changed) {
                   7126:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7127:         &logthis($logmsg);
                   7128:         return 'ok';
                   7129:     }
                   7130:     my $reply = &put('environment', \%names, $udom,$uname);
                   7131:     if ($reply ne 'ok') { 
                   7132:         return 'error: '.$reply;
                   7133:     }
1.1087    raeburn  7134:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7135:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7136:     }
1.1075    raeburn  7137:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7138:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7139:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7140:     &logthis($logmsg);
1.134     albertel 7141:     return 'ok';
1.80      www      7142: }
                   7143: 
1.81      www      7144: # -------------------------------------------------------------- Modify student
1.80      www      7145: 
1.81      www      7146: sub modifystudent {
                   7147:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7148:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7149:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7150:     if (!$cid) {
1.620     albertel 7151: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7152: 	    return 'not_in_class';
                   7153: 	}
1.80      www      7154:     }
                   7155: # --------------------------------------------------------------- Make the user
1.81      www      7156:     my $reply=&modifyuser
1.209     matthew  7157: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7158:          $desiredhome,$email,$inststatus);
1.80      www      7159:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7160:     # This will cause &modify_student_enrollment to get the uid from the
                   7161:     # students environment
                   7162:     $uid = undef if (!$forceid);
1.455     albertel 7163:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7164: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7165:     return $reply;
                   7166: }
                   7167: 
                   7168: sub modify_student_enrollment {
1.957     raeburn  7169:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7170:     my ($cdom,$cnum,$chome);
                   7171:     if (!$cid) {
1.620     albertel 7172: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7173: 	    return 'not_in_class';
                   7174: 	}
1.620     albertel 7175: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7176: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7177:     } else {
                   7178: 	($cdom,$cnum)=split(/_/,$cid);
                   7179:     }
1.620     albertel 7180:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7181:     if (!$chome) {
1.457     raeburn  7182: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7183:     }
1.455     albertel 7184:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7185:     # Make sure the user exists
1.81      www      7186:     my $uhome=&homeserver($uname,$udom);
                   7187:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7188: 	return 'error: no such user';
                   7189:     }
1.297     matthew  7190:     # Get student data if we were not given enough information
                   7191:     if (!defined($first)  || $first  eq '' || 
                   7192:         !defined($last)   || $last   eq '' || 
                   7193:         !defined($uid)    || $uid    eq '' || 
                   7194:         !defined($middle) || $middle eq '' || 
                   7195:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7196:         # They did not supply us with enough data to enroll the student, so
                   7197:         # we need to pick up more information.
1.297     matthew  7198:         my %tmp = &get('environment',
1.294     matthew  7199:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7200:                        ,$udom,$uname);
                   7201: 
1.800     albertel 7202:         #foreach my $key (keys(%tmp)) {
                   7203:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7204:         #}
1.294     matthew  7205:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7206:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7207:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7208:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7209:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7210:     }
1.556     albertel 7211:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7212:     my $reply=cput('classlist',
                   7213: 		   {"$uname:$udom" => 
1.515     raeburn  7214: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7215: 		   $cdom,$cnum);
1.81      www      7216:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7217: 	return 'error: '.$reply;
1.652     albertel 7218:     } else {
                   7219: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7220:     }
1.297     matthew  7221:     # Add student role to user
1.83      www      7222:     my $uurl='/'.$cid;
1.81      www      7223:     $uurl=~s/\_/\//g;
                   7224:     if ($usec) {
                   7225: 	$uurl.='/'.$usec;
                   7226:     }
1.957     raeburn  7227:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7228: }
                   7229: 
1.556     albertel 7230: sub format_name {
                   7231:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7232:     my $name;
                   7233:     if ($first ne 'lastname') {
                   7234: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7235:     } else {
                   7236: 	if ($lastname=~/\S/) {
                   7237: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7238: 	    $name=~s/\s+,/,/;
                   7239: 	} else {
                   7240: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7241: 	}
                   7242:     }
                   7243:     $name=~s/^\s+//;
                   7244:     $name=~s/\s+$//;
                   7245:     $name=~s/\s+/ /g;
                   7246:     return $name;
                   7247: }
                   7248: 
1.84      www      7249: # ------------------------------------------------- Write to course preferences
                   7250: 
                   7251: sub writecoursepref {
                   7252:     my ($courseid,%prefs)=@_;
                   7253:     $courseid=~s/^\///;
                   7254:     $courseid=~s/\_/\//g;
                   7255:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7256:     my $chome=homeserver($cnum,$cdomain);
                   7257:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7258: 	return 'error: no such course';
                   7259:     }
                   7260:     my $cstring='';
1.800     albertel 7261:     foreach my $pref (keys(%prefs)) {
                   7262: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7263:     }
1.84      www      7264:     $cstring=~s/\&$//;
                   7265:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7266: }
                   7267: 
                   7268: # ---------------------------------------------------------- Make/modify course
                   7269: 
                   7270: sub createcourse {
1.741     raeburn  7271:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7272:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7273:     $url=&declutter($url);
                   7274:     my $cid='';
1.1028    raeburn  7275:     if ($context eq 'requestcourses') {
                   7276:         my $can_create = 0;
                   7277:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7278:         if ($udom eq $ownerdom) {
                   7279:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7280:                                   $context)) {
                   7281:                 $can_create = 1;
                   7282:             }
                   7283:         } else {
                   7284:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7285:                                            $category);
                   7286:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7287:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7288:                 if (@curr > 0) {
                   7289:                     my @options = qw(approval validate autolimit);
                   7290:                     my $optregex = join('|',@options);
                   7291:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7292:                         $can_create = 1;
                   7293:                     }
                   7294:                 }
                   7295:             }
                   7296:         }
                   7297:         if ($can_create) {
                   7298:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7299:                 unless (&allowed('ccc',$udom)) {
                   7300:                     return 'refused'; 
                   7301:                 }
1.1017    raeburn  7302:             }
                   7303:         } else {
                   7304:             return 'refused';
                   7305:         }
1.1028    raeburn  7306:     } elsif (!&allowed('ccc',$udom)) {
                   7307:         return 'refused';
1.84      www      7308:     }
1.1011    raeburn  7309: # --------------------------------------------------------------- Get Unique ID
                   7310:     my $uname;
                   7311:     if ($cnum =~ /^$match_courseid$/) {
                   7312:         my $chome=&homeserver($cnum,$udom,'true');
                   7313:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7314:             $uname = $cnum;
                   7315:         } else {
1.1038    raeburn  7316:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7317:         }
                   7318:     } else {
1.1038    raeburn  7319:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7320:     }
                   7321:     return $uname if ($uname =~ /^error/);
                   7322: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7323:     if (!defined($course_server)) {
                   7324:         if (defined(&domain($udom,'primary'))) {
                   7325:             $course_server = &domain($udom,'primary');
                   7326:         } else {
                   7327:             $course_server = $env{'user.home'}; 
                   7328:         }
                   7329:     }
                   7330:     my %host_servers =
                   7331:         &Apache::lonnet::get_servers($udom,'library');
                   7332:     unless ($host_servers{$course_server}) {
                   7333:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7334:     }
1.84      www      7335: # ------------------------------------------------------------- Make the course
                   7336:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7337:                       $course_server);
1.84      www      7338:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7339:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7340:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7341: 	return 'error: no such course';
                   7342:     }
1.271     www      7343: # ----------------------------------------------------------------- Course made
1.516     raeburn  7344: # log existence
1.1029    raeburn  7345:     my $now = time;
1.918     raeburn  7346:     my $newcourse = {
                   7347:                     $udom.'_'.$uname => {
1.921     raeburn  7348:                                      description => $description,
                   7349:                                      inst_code   => $inst_code,
                   7350:                                      owner       => $course_owner,
                   7351:                                      type        => $crstype,
1.1029    raeburn  7352:                                      creator     => $env{'user.name'}.':'.
                   7353:                                                     $env{'user.domain'},
                   7354:                                      created     => $now,
                   7355:                                      context     => $context,
1.918     raeburn  7356:                                                 },
                   7357:                     };
1.921     raeburn  7358:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7359: # set toplevel url
1.271     www      7360:     my $topurl=$url;
                   7361:     unless ($nonstandard) {
                   7362: # ------------------------------------------ For standard courses, make top url
                   7363:         my $mapurl=&clutter($url);
1.278     www      7364:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7365:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7366: <map>
                   7367: <resource id="1" type="start"></resource>
                   7368: <resource id="2" src="$mapurl"></resource>
                   7369: <resource id="3" type="finish"></resource>
                   7370: <link index="1" from="1" to="2"></link>
                   7371: <link index="2" from="2" to="3"></link>
                   7372: </map>
                   7373: ENDINITMAP
                   7374:         $topurl=&declutter(
1.638     albertel 7375:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7376:                           );
                   7377:     }
                   7378: # ----------------------------------------------------------- Write preferences
1.84      www      7379:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7380:                      ('description'              => $description,
                   7381:                       'url'                      => $topurl,
                   7382:                       'internal.creator'         => $env{'user.name'}.':'.
                   7383:                                                     $env{'user.domain'},
                   7384:                       'internal.created'         => $now,
                   7385:                       'internal.creationcontext' => $context)
                   7386:                     );
1.84      www      7387:     return '/'.$udom.'/'.$uname;
                   7388: }
                   7389: 
1.1011    raeburn  7390: # ------------------------------------------------------------------- Create ID
                   7391: sub generate_coursenum {
1.1038    raeburn  7392:     my ($udom,$crstype) = @_;
1.1011    raeburn  7393:     my $domdesc = &domain($udom);
                   7394:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7395:     my $first;
                   7396:     if ($crstype eq 'Community') {
                   7397:         $first = '0';
                   7398:     } else {
                   7399:         $first = int(1+rand(9)); 
                   7400:     } 
                   7401:     my $uname=$first.
1.1011    raeburn  7402:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7403:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7404:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7405: # ----------------------------------------------- Make sure that does not exist
                   7406:     my $uhome=&homeserver($uname,$udom,'true');
                   7407:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7408:         if ($crstype eq 'Community') {
                   7409:             $first = '0';
                   7410:         } else {
                   7411:             $first = int(1+rand(9));
                   7412:         }
                   7413:         $uname=$first.
1.1011    raeburn  7414:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7415:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7416:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7417:         $uhome=&homeserver($uname,$udom,'true');
                   7418:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7419:             return 'error: unable to generate unique course-ID';
                   7420:         }
                   7421:     }
                   7422:     return $uname;
                   7423: }
                   7424: 
1.813     albertel 7425: sub is_course {
                   7426:     my ($cdom,$cnum) = @_;
                   7427:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7428: 				undef,'.');
1.813     albertel 7429:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7430:         return 1;
                   7431:     }
                   7432:     return 0;
                   7433: }
                   7434: 
1.1015    raeburn  7435: sub store_userdata {
                   7436:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7437:     my $result;
1.1016    raeburn  7438:     if ($datakey ne '') {
1.1013    raeburn  7439:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7440:             if ($udom eq '' || $uname eq '') {
                   7441:                 $udom = $env{'user.domain'};
                   7442:                 $uname = $env{'user.name'};
                   7443:             }
                   7444:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7445:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7446:                 $result = 'error: no_host';
                   7447:             } else {
                   7448:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7449:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7450: 
                   7451:                 my $namevalue='';
                   7452:                 foreach my $key (keys(%{$storehash})) {
                   7453:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7454:                 }
                   7455:                 $namevalue=~s/\&$//;
1.1105    raeburn  7456:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7457:                                   $namevalue,$uhome);
1.1013    raeburn  7458:             }
                   7459:         } else {
                   7460:             $result = 'error: data to store was not a hash reference'; 
                   7461:         }
                   7462:     } else {
                   7463:         $result= 'error: invalid requestkey'; 
                   7464:     }
                   7465:     return $result;
                   7466: }
                   7467: 
1.21      www      7468: # ---------------------------------------------------------- Assign Custom Role
                   7469: 
                   7470: sub assigncustomrole {
1.957     raeburn  7471:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7472:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7473:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7474: }
                   7475: 
                   7476: # ----------------------------------------------------------------- Revoke Role
                   7477: 
                   7478: sub revokerole {
1.957     raeburn  7479:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7480:     my $now=time;
1.965     raeburn  7481:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7482: }
                   7483: 
                   7484: # ---------------------------------------------------------- Revoke Custom Role
                   7485: 
                   7486: sub revokecustomrole {
1.957     raeburn  7487:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7488:     my $now=time;
1.357     www      7489:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7490:            $deleteflag,$selfenroll,$context);
1.17      www      7491: }
                   7492: 
1.533     banghart 7493: # ------------------------------------------------------------ Disk usage
1.535     albertel 7494: sub diskusage {
1.955     raeburn  7495:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7496:     $directorypath =~ s/\/$//;
                   7497:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7498:                        .&escape($getpropath).':'.&escape($uname).':'
                   7499:                        .&escape($udom),homeserver($uname,$udom));
                   7500:     if ($listing eq 'unknown_cmd') {
                   7501:         if ($getpropath) {
                   7502:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7503:         }
                   7504:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7505:     }
1.514     albertel 7506:     return $listing;
1.512     banghart 7507: }
                   7508: 
1.566     banghart 7509: sub is_locked {
1.1096    raeburn  7510:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7511:     my @check;
                   7512:     my $is_locked;
1.1093    raeburn  7513:     push (@check,$file_name);
1.613     albertel 7514:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7515: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7516:     my ($tmp)=keys(%locked);
                   7517:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7518:     
1.566     banghart 7519:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7520:         $is_locked = 'false';
                   7521:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7522:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7523:                $is_locked = 'true';
1.1096    raeburn  7524:                if (ref($which) eq 'ARRAY') {
                   7525:                    push(@{$which},$entry);
                   7526:                } else {
                   7527:                    last;
                   7528:                }
1.745     raeburn  7529:            }
                   7530:        }
1.566     banghart 7531:     } else {
                   7532:         $is_locked = 'false';
                   7533:     }
1.1093    raeburn  7534:     return $is_locked;
1.566     banghart 7535: }
                   7536: 
1.759     albertel 7537: sub declutter_portfile {
                   7538:     my ($file) = @_;
1.833     albertel 7539:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7540:     return $file;
                   7541: }
                   7542: 
1.559     banghart 7543: # ------------------------------------------------------------- Mark as Read Only
                   7544: 
                   7545: sub mark_as_readonly {
                   7546:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7547:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7548:     my ($tmp)=keys(%current_permissions);
                   7549:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7550:     foreach my $file (@{$files}) {
1.759     albertel 7551: 	$file = &declutter_portfile($file);
1.561     banghart 7552:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7553:     }
1.613     albertel 7554:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7555:     return;
                   7556: }
                   7557: 
1.572     banghart 7558: # ------------------------------------------------------------Save Selected Files
                   7559: 
                   7560: sub save_selected_files {
                   7561:     my ($user, $path, @files) = @_;
                   7562:     my $filename = $user."savedfiles";
1.573     banghart 7563:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7564:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7565:     foreach my $file (@files) {
1.620     albertel 7566:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7567:     }
                   7568:     foreach my $file (@other_files) {
1.574     banghart 7569:         print (OUT $file."\n");
1.572     banghart 7570:     }
1.574     banghart 7571:     close (OUT);
1.572     banghart 7572:     return 'ok';
                   7573: }
                   7574: 
1.574     banghart 7575: sub clear_selected_files {
                   7576:     my ($user) = @_;
                   7577:     my $filename = $user."savedfiles";
1.1117    foxr     7578:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7579:     print (OUT undef);
                   7580:     close (OUT);
                   7581:     return ("ok");    
                   7582: }
                   7583: 
1.572     banghart 7584: sub files_in_path {
                   7585:     my ($user, $path) = @_;
                   7586:     my $filename = $user."savedfiles";
                   7587:     my %return_files;
1.1117    foxr     7588:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7589:     while (my $line_in = <IN>) {
1.574     banghart 7590:         chomp ($line_in);
                   7591:         my @paths_and_file = split (m!/!, $line_in);
                   7592:         my $file_part = pop (@paths_and_file);
                   7593:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7594:         $path_part.='/';
                   7595:         my $path_and_file = $path_part.$file_part;
                   7596:         if ($path_part eq $path) {
                   7597:             $return_files{$file_part}= 'selected';
                   7598:         }
                   7599:     }
1.574     banghart 7600:     close (IN);
                   7601:     return (\%return_files);
1.572     banghart 7602: }
                   7603: 
                   7604: # called in portfolio select mode, to show files selected NOT in current directory
                   7605: sub files_not_in_path {
                   7606:     my ($user, $path) = @_;
                   7607:     my $filename = $user."savedfiles";
                   7608:     my @return_files;
                   7609:     my $path_part;
1.1117    foxr     7610:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7611:     while (my $line = <IN>) {
1.572     banghart 7612:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7613:         my @paths_and_file = split(m|/|, $line);
                   7614:         my $file_part = pop(@paths_and_file);
                   7615:         chomp($file_part);
                   7616:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7617:         $path_part .= '/';
                   7618:         my $path_and_file = $path_part.$file_part;
                   7619:         if ($path_part ne $path) {
1.800     albertel 7620:             push(@return_files, ($path_and_file));
1.572     banghart 7621:         }
                   7622:     }
1.800     albertel 7623:     close(OUT);
1.574     banghart 7624:     return (@return_files);
1.572     banghart 7625: }
                   7626: 
1.745     raeburn  7627: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7628: 
1.745     raeburn  7629: sub get_portfile_permissions {
                   7630:     my ($domain,$user) = @_;
1.613     albertel 7631:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7632:     my ($tmp)=keys(%current_permissions);
                   7633:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7634:     return \%current_permissions;
                   7635: }
                   7636: 
                   7637: #---------------------------------------------Get portfolio file access controls
                   7638: 
1.749     raeburn  7639: sub get_access_controls {
1.745     raeburn  7640:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7641:     my %access;
                   7642:     my $real_file = $file;
                   7643:     $file =~ s/\.meta$//;
1.745     raeburn  7644:     if (defined($file)) {
1.749     raeburn  7645:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7646:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7647:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7648:             }
                   7649:         }
1.745     raeburn  7650:     } else {
1.749     raeburn  7651:         foreach my $key (keys(%{$current_permissions})) {
                   7652:             if ($key =~ /\0accesscontrol$/) {
                   7653:                 if (defined($group)) {
                   7654:                     if ($key !~ m-^\Q$group\E/-) {
                   7655:                         next;
                   7656:                     }
                   7657:                 }
                   7658:                 my ($fullpath) = split(/\0/,$key);
                   7659:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7660:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7661:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7662:                     }
                   7663:                 }
                   7664:             }
                   7665:         }
                   7666:     }
                   7667:     return %access;
                   7668: }
                   7669: 
                   7670: sub modify_access_controls {
                   7671:     my ($file_name,$changes,$domain,$user)=@_;
                   7672:     my ($outcome,$deloutcome);
                   7673:     my %store_permissions;
                   7674:     my %new_values;
                   7675:     my %new_control;
                   7676:     my %translation;
                   7677:     my @deletions = ();
                   7678:     my $now = time;
                   7679:     if (exists($$changes{'activate'})) {
                   7680:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7681:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7682:             my $numnew = scalar(@newitems);
                   7683:             for (my $i=0; $i<$numnew; $i++) {
                   7684:                 my $newkey = $newitems[$i];
                   7685:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7686:                 if ($newkey =~ /^\d+:/) { 
                   7687:                     $newkey =~ s/^(\d+)/$newid/;
                   7688:                     $translation{$1} = $newid;
                   7689:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7690:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7691:                     $translation{$1} = $newid;
                   7692:                 }
1.749     raeburn  7693:                 $new_values{$file_name."\0".$newkey} = 
                   7694:                                           $$changes{'activate'}{$newitems[$i]};
                   7695:                 $new_control{$newkey} = $now;
                   7696:             }
                   7697:         }
                   7698:     }
                   7699:     my %todelete;
                   7700:     my %changed_items;
                   7701:     foreach my $action ('delete','update') {
                   7702:         if (exists($$changes{$action})) {
                   7703:             if (ref($$changes{$action}) eq 'HASH') {
                   7704:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7705:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7706:                     if ($action eq 'delete') { 
                   7707:                         $todelete{$itemnum} = 1;
                   7708:                     } else {
                   7709:                         $changed_items{$itemnum} = $key;
                   7710:                     }
                   7711:                 }
1.745     raeburn  7712:             }
                   7713:         }
1.749     raeburn  7714:     }
                   7715:     # get lock on access controls for file.
                   7716:     my $lockhash = {
                   7717:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7718:                                                        ':'.$env{'user.domain'},
                   7719:                    }; 
                   7720:     my $tries = 0;
                   7721:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7722:    
                   7723:     while (($gotlock ne 'ok') && $tries <3) {
                   7724:         $tries ++;
                   7725:         sleep 1;
                   7726:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7727:     }
                   7728:     if ($gotlock eq 'ok') {
                   7729:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7730:         my ($tmp)=keys(%curr_permissions);
                   7731:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7732:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7733:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7734:             if (ref($curr_controls) eq 'HASH') {
                   7735:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7736:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7737:                     if (defined($todelete{$itemnum})) {
                   7738:                         push(@deletions,$file_name."\0".$control_item);
                   7739:                     } else {
                   7740:                         if (defined($changed_items{$itemnum})) {
                   7741:                             $new_control{$changed_items{$itemnum}} = $now;
                   7742:                             push(@deletions,$file_name."\0".$control_item);
                   7743:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7744:                         } else {
                   7745:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7746:                         }
                   7747:                     }
1.745     raeburn  7748:                 }
                   7749:             }
                   7750:         }
1.970     raeburn  7751:         my ($group);
                   7752:         if (&is_course($domain,$user)) {
                   7753:             ($group,my $file) = split(/\//,$file_name,2);
                   7754:         }
1.749     raeburn  7755:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7756:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7757:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7758:         #  remove lock
                   7759:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7760:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7761:         my $sqlresult =
1.970     raeburn  7762:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7763:                                     $group);
1.749     raeburn  7764:     } else {
                   7765:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7766:     }
1.749     raeburn  7767:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7768: }
                   7769: 
1.827     raeburn  7770: sub make_public_indefinitely {
                   7771:     my ($requrl) = @_;
                   7772:     my $now = time;
                   7773:     my $action = 'activate';
                   7774:     my $aclnum = 0;
                   7775:     if (&is_portfolio_url($requrl)) {
                   7776:         my (undef,$udom,$unum,$file_name,$group) =
                   7777:             &parse_portfolio_url($requrl);
                   7778:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7779:         my %access_controls = &get_access_controls($current_perms,
                   7780:                                                    $group,$file_name);
                   7781:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7782:             my ($num,$scope,$end,$start) = 
                   7783:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7784:             if ($scope eq 'public') {
                   7785:                 if ($start <= $now && $end == 0) {
                   7786:                     $action = 'none';
                   7787:                 } else {
                   7788:                     $action = 'update';
                   7789:                     $aclnum = $num;
                   7790:                 }
                   7791:                 last;
                   7792:             }
                   7793:         }
                   7794:         if ($action eq 'none') {
                   7795:              return 'ok';
                   7796:         } else {
                   7797:             my %changes;
                   7798:             my $newend = 0;
                   7799:             my $newstart = $now;
                   7800:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7801:             $changes{$action}{$newkey} = {
                   7802:                 type => 'public',
                   7803:                 time => {
                   7804:                     start => $newstart,
                   7805:                     end   => $newend,
                   7806:                 },
                   7807:             };
                   7808:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7809:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7810:             return $outcome;
                   7811:         }
                   7812:     } else {
                   7813:         return 'invalid';
                   7814:     }
                   7815: }
                   7816: 
1.745     raeburn  7817: #------------------------------------------------------Get Marked as Read Only
                   7818: 
                   7819: sub get_marked_as_readonly {
                   7820:     my ($domain,$user,$what,$group) = @_;
                   7821:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7822:     my @readonly_files;
1.629     banghart 7823:     my $cmp1=$what;
                   7824:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7825:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7826:         if (defined($group)) {
                   7827:             if ($file_name !~ m-^\Q$group\E/-) {
                   7828:                 next;
                   7829:             }
                   7830:         }
1.561     banghart 7831:         if (ref($value) eq "ARRAY"){
                   7832:             foreach my $stored_what (@{$value}) {
1.629     banghart 7833:                 my $cmp2=$stored_what;
1.759     albertel 7834:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7835:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7836:                 }
1.629     banghart 7837:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7838:                     push(@readonly_files, $file_name);
1.745     raeburn  7839:                     last;
1.563     banghart 7840:                 } elsif (!defined($what)) {
                   7841:                     push(@readonly_files, $file_name);
1.745     raeburn  7842:                     last;
1.561     banghart 7843:                 }
                   7844:             }
1.745     raeburn  7845:         }
1.561     banghart 7846:     }
                   7847:     return @readonly_files;
                   7848: }
1.577     banghart 7849: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7850: 
1.577     banghart 7851: sub get_marked_as_readonly_hash {
1.745     raeburn  7852:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7853:     my %readonly_files;
1.745     raeburn  7854:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7855:         if (defined($group)) {
                   7856:             if ($file_name !~ m-^\Q$group\E/-) {
                   7857:                 next;
                   7858:             }
                   7859:         }
1.577     banghart 7860:         if (ref($value) eq "ARRAY"){
                   7861:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7862:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7863:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7864:                         if ($lock_descriptor eq 'graded') {
                   7865:                             $readonly_files{$file_name} = 'graded';
                   7866:                         } elsif ($lock_descriptor eq 'handback') {
                   7867:                             $readonly_files{$file_name} = 'handback';
                   7868:                         } else {
                   7869:                             if (!exists($readonly_files{$file_name})) {
                   7870:                                 $readonly_files{$file_name} = 'locked';
                   7871:                             }
                   7872:                         }
1.745     raeburn  7873:                     }
1.750     banghart 7874:                 } 
1.577     banghart 7875:             }
                   7876:         } 
                   7877:     }
                   7878:     return %readonly_files;
                   7879: }
1.559     banghart 7880: # ------------------------------------------------------------ Unmark as Read Only
                   7881: 
                   7882: sub unmark_as_readonly {
1.629     banghart 7883:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7884:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7885:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7886:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7887:     my $symb_crs = $what;
                   7888:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7889:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7890:     my ($tmp)=keys(%current_permissions);
                   7891:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7892:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7893:     foreach my $file (@readonly_files) {
1.759     albertel 7894: 	my $clean_file = &declutter_portfile($file);
                   7895: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7896: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7897:         my @new_locks;
                   7898:         my @del_keys;
                   7899:         if (ref($current_locks) eq "ARRAY"){
                   7900:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7901:                 my $compare=$locker;
1.749     raeburn  7902:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7903:                     $compare=join('',@{$locker});
1.746     raeburn  7904:                     if ($compare ne $symb_crs) {
                   7905:                         push(@new_locks, $locker);
                   7906:                     }
1.563     banghart 7907:                 }
                   7908:             }
1.650     albertel 7909:             if (scalar(@new_locks) > 0) {
1.563     banghart 7910:                 $current_permissions{$file} = \@new_locks;
                   7911:             } else {
                   7912:                 push(@del_keys, $file);
1.613     albertel 7913:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7914:                 delete($current_permissions{$file});
1.563     banghart 7915:             }
                   7916:         }
1.561     banghart 7917:     }
1.613     albertel 7918:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7919:     return;
                   7920: }
1.512     banghart 7921: 
1.17      www      7922: # ------------------------------------------------------------ Directory lister
                   7923: 
                   7924: sub dirlist {
1.955     raeburn  7925:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7926:     $uri=~s/^\///;
                   7927:     $uri=~s/\/$//;
1.253     stredwic 7928:     my ($udom, $uname);
1.955     raeburn  7929:     if ($getuserdir) {
1.253     stredwic 7930:         $udom = $userdomain;
                   7931:         $uname = $username;
1.955     raeburn  7932:     } else {
                   7933:         (undef,$udom,$uname)=split(/\//,$uri);
                   7934:         if(defined($userdomain)) {
                   7935:             $udom = $userdomain;
                   7936:         }
                   7937:         if(defined($username)) {
                   7938:             $uname = $username;
                   7939:         }
1.253     stredwic 7940:     }
1.955     raeburn  7941:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7942: 
1.955     raeburn  7943:     $dirRoot = $perlvar{'lonDocRoot'};
                   7944:     if (defined($getpropath)) {
                   7945:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7946:         $dirRoot =~ s/\/$//;
1.955     raeburn  7947:     } elsif (defined($getuserdir)) {
                   7948:         my $subdir=$uname.'__';
                   7949:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7950:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7951:                    ."/$udom/$subdir/$uname";
                   7952:     } elsif (defined($alternateRoot)) {
                   7953:         $dirRoot = $alternateRoot;
1.751     banghart 7954:     }
1.253     stredwic 7955: 
                   7956:     if($udom) {
                   7957:         if($uname) {
1.955     raeburn  7958:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7959:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7960:                               .':'.&escape($uname).':'.&escape($udom),
                   7961:                               &homeserver($uname,$udom));
                   7962:             if ($listing eq 'unknown_cmd') {
                   7963:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7964:                                   &homeserver($uname,$udom));
                   7965:             } else {
                   7966:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7967:             }
1.605     matthew  7968:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7969:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7970: 				  &homeserver($uname,$udom));
1.605     matthew  7971:                 @listing_results = split(/:/,$listing);
                   7972:             } else {
                   7973:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7974:             }
                   7975:             return @listing_results;
1.955     raeburn  7976:         } elsif(!$alternateRoot) {
1.800     albertel 7977:             my %allusers;
1.841     albertel 7978: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7979:  	    foreach my $tryserver (keys(%servers)) {
                   7980:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7981:                                   &escape($udom),$tryserver);
                   7982:                 if ($listing eq 'unknown_cmd') {
                   7983: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7984: 				      $udom, $tryserver);
                   7985:                 } else {
                   7986:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7987:                 }
1.841     albertel 7988: 		if ($listing eq 'unknown_cmd') {
                   7989: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7990: 				      $udom, $tryserver);
                   7991: 		    @listing_results = split(/:/,$listing);
                   7992: 		} else {
                   7993: 		    @listing_results =
                   7994: 			map { &unescape($_); } split(/:/,$listing);
                   7995: 		}
                   7996: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7997: 		    $listing_results[0] ne 'empty'       &&
                   7998: 		    $listing_results[0] ne 'con_lost') {
                   7999: 		    foreach my $line (@listing_results) {
                   8000: 			my ($entry) = split(/&/,$line,2);
                   8001: 			$allusers{$entry} = 1;
                   8002: 		    }
                   8003: 		}
1.253     stredwic 8004:             }
                   8005:             my $alluserstr='';
1.800     albertel 8006:             foreach my $user (sort(keys(%allusers))) {
                   8007:                 $alluserstr.=$user.'&user:';
1.253     stredwic 8008:             }
                   8009:             $alluserstr=~s/:$//;
                   8010:             return split(/:/,$alluserstr);
                   8011:         } else {
1.800     albertel 8012:             return ('missing user name');
1.253     stredwic 8013:         }
1.955     raeburn  8014:     } elsif(!defined($getpropath)) {
1.841     albertel 8015:         my @all_domains = sort(&all_domains());
1.955     raeburn  8016:         foreach my $domain (@all_domains) {
                   8017:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   8018:         }
                   8019:         return @all_domains;
                   8020:     } else {
1.800     albertel 8021:         return ('missing domain');
1.275     stredwic 8022:     }
                   8023: }
                   8024: 
                   8025: # --------------------------------------------- GetFileTimestamp
                   8026: # This function utilizes dirlist and returns the date stamp for
                   8027: # when it was last modified.  It will also return an error of -1
                   8028: # if an error occurs
                   8029: 
                   8030: sub GetFileTimestamp {
1.955     raeburn  8031:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8032:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8033:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  8034:     my ($fileStat) = 
                   8035:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   8036:                                  undef,$getuserdir);
1.275     stredwic 8037:     my @stats = split('&', $fileStat);
                   8038:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  8039:         # @stats contains first the filename, then the stat output
                   8040:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8041:     } else {
                   8042:         return -1;
1.253     stredwic 8043:     }
1.26      www      8044: }
                   8045: 
1.712     albertel 8046: sub stat_file {
                   8047:     my ($uri) = @_;
1.787     albertel 8048:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8049: 
1.955     raeburn  8050:     my ($udom,$uname,$file);
1.712     albertel 8051:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8052: 	($udom,$uname,$file) =
1.811     albertel 8053: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8054: 	$file = 'userfiles/'.$file;
                   8055:     }
                   8056:     if ($uri =~ m-^/res/-) {
                   8057: 	($udom,$uname) = 
1.807     albertel 8058: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8059: 	$file = $uri;
                   8060:     }
                   8061: 
                   8062:     if (!$udom || !$uname || !$file) {
                   8063: 	# unable to handle the uri
                   8064: 	return ();
                   8065:     }
1.956     raeburn  8066:     my $getpropath;
                   8067:     if ($file =~ /^userfiles\//) {
                   8068:         $getpropath = 1;
                   8069:     }
1.955     raeburn  8070:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8071:     my @stats = split('&', $result);
1.721     banghart 8072:     
1.712     albertel 8073:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8074: 	shift(@stats); #filename is first
                   8075: 	return @stats;
                   8076:     }
                   8077:     return ();
                   8078: }
                   8079: 
1.26      www      8080: # -------------------------------------------------------- Value of a Condition
                   8081: 
1.713     albertel 8082: # gets the value of a specific preevaluated condition
                   8083: #    stored in the string  $env{user.state.<cid>}
                   8084: # or looks up a condition reference in the bighash and if if hasn't
                   8085: # already been evaluated recurses into docondval to get the value of
                   8086: # the condition, then memoizing it to 
                   8087: #   $env{user.state.<cid>.<condition>}
1.40      www      8088: sub directcondval {
                   8089:     my $number=shift;
1.620     albertel 8090:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8091: 	&Apache::lonuserstate::evalstate();
                   8092:     }
1.713     albertel 8093:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8094: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8095:     } elsif ($number =~ /^_/) {
                   8096: 	my $sub_condition;
                   8097: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8098: 		&GDBM_READER(),0640)) {
                   8099: 	    $sub_condition=$bighash{'conditions'.$number};
                   8100: 	    untie(%bighash);
                   8101: 	}
                   8102: 	my $value = &docondval($sub_condition);
1.949     raeburn  8103: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8104: 	return $value;
                   8105:     }
1.620     albertel 8106:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8107:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8108:     } else {
                   8109:        return 2;
                   8110:     }
                   8111: }
                   8112: 
1.713     albertel 8113: # get the collection of conditions for this resource
1.26      www      8114: sub condval {
                   8115:     my $condidx=shift;
1.54      www      8116:     my $allpathcond='';
1.713     albertel 8117:     foreach my $cond (split(/\|/,$condidx)) {
                   8118: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8119: 	    $allpathcond.=
                   8120: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8121: 	}
1.191     harris41 8122:     }
1.54      www      8123:     $allpathcond=~s/\|$//;
1.713     albertel 8124:     return &docondval($allpathcond);
                   8125: }
                   8126: 
                   8127: #evaluates an expression of conditions
                   8128: sub docondval {
                   8129:     my ($allpathcond) = @_;
                   8130:     my $result=0;
                   8131:     if ($env{'request.course.id'}
                   8132: 	&& defined($allpathcond)) {
                   8133: 	my $operand='|';
                   8134: 	my @stack;
                   8135: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8136: 	    if ($chunk eq '(') {
                   8137: 		push @stack,($operand,$result);
                   8138: 	    } elsif ($chunk eq ')') {
                   8139: 		my $before=pop @stack;
                   8140: 		if (pop @stack eq '&') {
                   8141: 		    $result=$result>$before?$before:$result;
                   8142: 		} else {
                   8143: 		    $result=$result>$before?$result:$before;
                   8144: 		}
                   8145: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8146: 		$operand=$chunk;
                   8147: 	    } else {
                   8148: 		my $new=directcondval($chunk);
                   8149: 		if ($operand eq '&') {
                   8150: 		    $result=$result>$new?$new:$result;
                   8151: 		} else {
                   8152: 		    $result=$result>$new?$result:$new;
                   8153: 		}
                   8154: 	    }
                   8155: 	}
1.26      www      8156:     }
                   8157:     return $result;
1.421     albertel 8158: }
                   8159: 
                   8160: # ---------------------------------------------------- Devalidate courseresdata
                   8161: 
                   8162: sub devalidatecourseresdata {
                   8163:     my ($coursenum,$coursedomain)=@_;
                   8164:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8165:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8166: }
                   8167: 
1.763     www      8168: 
1.200     www      8169: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8170: #
                   8171: #  Parameters:
                   8172: #      $coursenum    - Number of the course.
                   8173: #      $coursedomain - Domain at which the course was created.
                   8174: #  Returns:
                   8175: #     A hash of the course parameters along (I think) with timestamps
                   8176: #     and version info.
1.877     foxr     8177: 
1.624     albertel 8178: sub get_courseresdata {
                   8179:     my ($coursenum,$coursedomain)=@_;
1.200     www      8180:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8181:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8182:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8183:     my %dumpreply;
1.417     albertel 8184:     unless (defined($cached)) {
1.624     albertel 8185: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8186: 	$result=\%dumpreply;
1.251     albertel 8187: 	my ($tmp) = keys(%dumpreply);
                   8188: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8189: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8190: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8191: 	    return $tmp;
1.416     albertel 8192: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8193: 	    $result=undef;
1.599     albertel 8194: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8195: 	}
                   8196:     }
1.624     albertel 8197:     return $result;
                   8198: }
                   8199: 
1.633     albertel 8200: sub devalidateuserresdata {
                   8201:     my ($uname,$udom)=@_;
                   8202:     my $hashid="$udom:$uname";
                   8203:     &devalidate_cache_new('userres',$hashid);
                   8204: }
                   8205: 
1.624     albertel 8206: sub get_userresdata {
                   8207:     my ($uname,$udom)=@_;
                   8208:     #most student don\'t have any data set, check if there is some data
                   8209:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8210: 
                   8211:     my $hashid="$udom:$uname";
                   8212:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8213:     if (!defined($cached)) {
                   8214: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8215: 	$result=\%resourcedata;
                   8216: 	&do_cache_new('userres',$hashid,$result,600);
                   8217:     }
                   8218:     my ($tmp)=keys(%$result);
                   8219:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8220: 	return $result;
                   8221:     }
                   8222:     #error 2 occurs when the .db doesn't exist
                   8223:     if ($tmp!~/error: 2 /) {
1.672     albertel 8224: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8225: 		 " Trying to get resource data for ".
                   8226: 		 $uname." at ".$udom.": ".
                   8227: 		 $tmp."</font>");
                   8228:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8229: 	#&EXT_cache_set($udom,$uname);
                   8230: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8231: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8232:     }
                   8233:     return $tmp;
                   8234: }
1.879     foxr     8235: #----------------------------------------------- resdata - return resource data
                   8236: #  Purpose:
                   8237: #    Return resource data for either users or for a course.
                   8238: #  Parameters:
                   8239: #     $name      - Course/user name.
                   8240: #     $domain    - Name of the domain the user/course is registered on.
                   8241: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8242: #     @which     - Array of names of resources desired.
                   8243: #  Returns:
                   8244: #     The value of the first reasource in @which that is found in the
                   8245: #     resource hash.
                   8246: #  Exceptional Conditions:
                   8247: #     If the $type passed in is not valid (not the string 'course' or 
                   8248: #     'user', an undefined  reference is returned.
                   8249: #     If none of the resources are found, an undef is returned
1.624     albertel 8250: sub resdata {
                   8251:     my ($name,$domain,$type,@which)=@_;
                   8252:     my $result;
                   8253:     if ($type eq 'course') {
                   8254: 	$result=&get_courseresdata($name,$domain);
                   8255:     } elsif ($type eq 'user') {
                   8256: 	$result=&get_userresdata($name,$domain);
                   8257:     }
                   8258:     if (!ref($result)) { return $result; }    
1.251     albertel 8259:     foreach my $item (@which) {
1.927     albertel 8260: 	if (defined($result->{$item->[0]})) {
                   8261: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8262: 	}
1.250     albertel 8263:     }
1.291     albertel 8264:     return undef;
1.200     www      8265: }
                   8266: 
1.379     matthew  8267: #
                   8268: # EXT resource caching routines
                   8269: #
                   8270: 
                   8271: sub clear_EXT_cache_status {
1.383     albertel 8272:     &delenv('cache.EXT.');
1.379     matthew  8273: }
                   8274: 
                   8275: sub EXT_cache_status {
                   8276:     my ($target_domain,$target_user) = @_;
1.383     albertel 8277:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8278:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8279:         # We know already the user has no data
                   8280:         return 1;
                   8281:     } else {
                   8282:         return 0;
                   8283:     }
                   8284: }
                   8285: 
                   8286: sub EXT_cache_set {
                   8287:     my ($target_domain,$target_user) = @_;
1.383     albertel 8288:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8289:     #&appenv({$cachename => time});
1.379     matthew  8290: }
                   8291: 
1.28      www      8292: # --------------------------------------------------------- Value of a Variable
1.58      www      8293: sub EXT {
1.715     albertel 8294: 
1.395     albertel 8295:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8296:     unless ($varname) { return ''; }
1.218     albertel 8297:     #get real user name/domain, courseid and symb
                   8298:     my $courseid;
1.359     albertel 8299:     my $publicuser;
1.427     www      8300:     if ($symbparm) {
                   8301: 	$symbparm=&get_symb_from_alias($symbparm);
                   8302:     }
1.218     albertel 8303:     if (!($uname && $udom)) {
1.790     albertel 8304:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8305:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8306:     } else {
1.620     albertel 8307: 	$courseid=$env{'request.course.id'};
1.218     albertel 8308:     }
1.48      www      8309:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8310:     my $rest;
1.320     albertel 8311:     if (defined($therest[0])) {
1.48      www      8312:        $rest=join('.',@therest);
                   8313:     } else {
                   8314:        $rest='';
                   8315:     }
1.320     albertel 8316: 
1.57      www      8317:     my $qualifierrest=$qualifier;
                   8318:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8319:     my $spacequalifierrest=$space;
                   8320:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8321:     if ($realm eq 'user') {
1.48      www      8322: # --------------------------------------------------------------- user.resource
                   8323: 	if ($space eq 'resource') {
1.651     albertel 8324: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8325: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8326: 		 &&
1.744     albertel 8327: 		 ($symbparm eq &symbread()) ) {	
                   8328: 		# if we are in the middle of processing the resource the
                   8329: 		# get the value we are planning on committing
                   8330:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8331:                     return $Apache::lonhomework::results{$qualifierrest};
                   8332:                 } else {
                   8333:                     return $Apache::lonhomework::history{$qualifierrest};
                   8334:                 }
1.335     albertel 8335: 	    } else {
1.359     albertel 8336: 		my %restored;
1.620     albertel 8337: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8338: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8339: 		} else {
                   8340: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8341: 		}
1.335     albertel 8342: 		return $restored{$qualifierrest};
                   8343: 	    }
1.48      www      8344: # ----------------------------------------------------------------- user.access
                   8345:         } elsif ($space eq 'access') {
1.218     albertel 8346: 	    # FIXME - not supporting calls for a specific user
1.48      www      8347:             return &allowed($qualifier,$rest);
                   8348: # ------------------------------------------ user.preferences, user.environment
                   8349:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8350: 	    if (($uname eq $env{'user.name'}) &&
                   8351: 		($udom eq $env{'user.domain'})) {
                   8352: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8353: 	    } else {
1.359     albertel 8354: 		my %returnhash;
                   8355: 		if (!$publicuser) {
                   8356: 		    %returnhash=&userenvironment($udom,$uname,
                   8357: 						 $qualifierrest);
                   8358: 		}
1.218     albertel 8359: 		return $returnhash{$qualifierrest};
                   8360: 	    }
1.48      www      8361: # ----------------------------------------------------------------- user.course
                   8362:         } elsif ($space eq 'course') {
1.218     albertel 8363: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8364:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8365: # ------------------------------------------------------------------- user.role
                   8366:         } elsif ($space eq 'role') {
1.218     albertel 8367: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8368:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8369:             if ($qualifier eq 'value') {
                   8370: 		return $role;
                   8371:             } elsif ($qualifier eq 'extent') {
                   8372:                 return $where;
                   8373:             }
                   8374: # ----------------------------------------------------------------- user.domain
                   8375:         } elsif ($space eq 'domain') {
1.218     albertel 8376:             return $udom;
1.48      www      8377: # ------------------------------------------------------------------- user.name
                   8378:         } elsif ($space eq 'name') {
1.218     albertel 8379:             return $uname;
1.48      www      8380: # ---------------------------------------------------- Any other user namespace
1.29      www      8381:         } else {
1.359     albertel 8382: 	    my %reply;
                   8383: 	    if (!$publicuser) {
                   8384: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8385: 	    }
                   8386: 	    return $reply{$qualifierrest};
1.48      www      8387:         }
1.236     www      8388:     } elsif ($realm eq 'query') {
                   8389: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8390:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8391: 						[$spacequalifierrest]);
1.620     albertel 8392: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8393:    } elsif ($realm eq 'request') {
1.48      www      8394: # ------------------------------------------------------------- request.browser
                   8395:         if ($space eq 'browser') {
1.430     www      8396: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8397: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8398: 		    return 1;
                   8399: 		} else {
                   8400: 		    return 0;
                   8401: 		}
                   8402: 	    } else {
1.620     albertel 8403: 		return $env{'browser.'.$qualifier};
1.430     www      8404: 	    }
1.57      www      8405: # ------------------------------------------------------------ request.filename
                   8406:         } else {
1.620     albertel 8407:             return $env{'request.'.$spacequalifierrest};
1.29      www      8408:         }
1.28      www      8409:     } elsif ($realm eq 'course') {
1.48      www      8410: # ---------------------------------------------------------- course.description
1.620     albertel 8411:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8412:     } elsif ($realm eq 'resource') {
1.165     www      8413: 
1.620     albertel 8414: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8415: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8416: 	}
1.693     albertel 8417: 
                   8418: 	if ($space eq 'title') {
                   8419: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8420: 	    return &gettitle($symbparm);
                   8421: 	}
                   8422: 	
                   8423: 	if ($space eq 'map') {
                   8424: 	    my ($map) = &decode_symb($symbparm);
                   8425: 	    return &symbread($map);
                   8426: 	}
1.905     albertel 8427: 	if ($space eq 'filename') {
                   8428: 	    if ($symbparm) {
                   8429: 		return &clutter((&decode_symb($symbparm))[2]);
                   8430: 	    }
                   8431: 	    return &hreflocation('',$env{'request.filename'});
                   8432: 	}
1.693     albertel 8433: 
                   8434: 	my ($section, $group, @groups);
1.593     albertel 8435: 	my ($courselevelm,$courselevel);
1.539     albertel 8436: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8437: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8438: 
1.218     albertel 8439: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8440: 
1.60      www      8441: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8442: 	    my $symbp=$symbparm;
1.735     albertel 8443: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8444: 
                   8445: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8446: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8447: 
1.620     albertel 8448: 	    if (($env{'user.name'} eq $uname) &&
                   8449: 		($env{'user.domain'} eq $udom)) {
                   8450: 		$section=$env{'request.course.sec'};
1.733     raeburn  8451:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8452:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8453: 	    } else {
1.539     albertel 8454: 		if (! defined($usection)) {
1.551     albertel 8455: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8456: 		} else {
                   8457: 		    $section = $usection;
                   8458: 		}
1.733     raeburn  8459:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8460: 	    }
                   8461: 
                   8462: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8463: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8464: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8465: 
1.593     albertel 8466: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8467: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8468: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8469: 
1.60      www      8470: # ----------------------------------------------------------- first, check user
1.624     albertel 8471: 
                   8472: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8473: 				       ([$courselevelr,'resource'],
                   8474: 					[$courselevelm,'map'     ],
                   8475: 					[$courselevel, 'course'  ]));
1.931     albertel 8476: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8477: 
1.594     albertel 8478: # ------------------------------------------------ second, check some of course
1.684     raeburn  8479:             my $coursereply;
1.691     raeburn  8480:             if (@groups > 0) {
                   8481:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8482:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8483:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8484:             }
1.96      www      8485: 
1.684     raeburn  8486: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8487: 				  $env{'course.'.$courseid.'.domain'},
                   8488: 				  'course',
                   8489: 				  ([$seclevelr,   'resource'],
                   8490: 				   [$seclevelm,   'map'     ],
                   8491: 				   [$seclevel,    'course'  ],
                   8492: 				   [$courselevelr,'resource']));
                   8493: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8494: 
1.60      www      8495: # ------------------------------------------------------ third, check map parms
1.218     albertel 8496: 	    my %parmhash=();
                   8497: 	    my $thisparm='';
                   8498: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8499: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8500: 		    &GDBM_READER(),0640)) {
1.218     albertel 8501: 		$thisparm=$parmhash{$symbparm};
                   8502: 		untie(%parmhash);
                   8503: 	    }
1.927     albertel 8504: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8505: 	}
1.594     albertel 8506: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8507: 
1.218     albertel 8508: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8509: 	my $filename;
                   8510: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8511: 	if ($symbparm) {
1.409     www      8512: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8513: 	} else {
1.620     albertel 8514: 	    $filename=$env{'request.filename'};
1.282     albertel 8515: 	}
                   8516: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8517: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8518: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8519: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8520: 
1.927     albertel 8521: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8522: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8523: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8524: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8525: 				     $env{'course.'.$courseid.'.domain'},
                   8526: 				     'course',
1.927     albertel 8527: 				     ([$courselevelm,'map'   ],
                   8528: 				      [$courselevel, 'course']));
                   8529: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8530: 	}
1.145     www      8531: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8532: 	unless ($space eq '0') {
1.336     albertel 8533: 	    my @parts=split(/_/,$space);
                   8534: 	    my $id=pop(@parts);
                   8535: 	    my $part=join('_',@parts);
                   8536: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8537: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8538: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8539: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8540: 	}
1.395     albertel 8541: 	if ($recurse) { return undef; }
                   8542: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8543: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8544: # ---------------------------------------------------- Any other user namespace
                   8545:     } elsif ($realm eq 'environment') {
                   8546: # ----------------------------------------------------------------- environment
1.620     albertel 8547: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8548: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8549: 	} else {
1.770     albertel 8550: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8551: 		return '';
                   8552: 	    }
1.219     albertel 8553: 	    my %returnhash=&userenvironment($udom,$uname,
                   8554: 					    $spacequalifierrest);
                   8555: 	    return $returnhash{$spacequalifierrest};
                   8556: 	}
1.28      www      8557:     } elsif ($realm eq 'system') {
1.48      www      8558: # ----------------------------------------------------------------- system.time
                   8559: 	if ($space eq 'time') {
                   8560: 	    return time;
                   8561:         }
1.696     albertel 8562:     } elsif ($realm eq 'server') {
                   8563: # ----------------------------------------------------------------- system.time
                   8564: 	if ($space eq 'name') {
                   8565: 	    return $ENV{'SERVER_NAME'};
                   8566:         }
1.28      www      8567:     }
1.48      www      8568:     return '';
1.61      www      8569: }
                   8570: 
1.927     albertel 8571: sub get_reply {
                   8572:     my ($reply_value) = @_;
1.940     raeburn  8573:     if (ref($reply_value) eq 'ARRAY') {
                   8574:         if (wantarray) {
                   8575: 	    return @$reply_value;
                   8576:         }
                   8577:         return $reply_value->[0];
                   8578:     } else {
                   8579:         return $reply_value;
1.927     albertel 8580:     }
                   8581: }
                   8582: 
1.691     raeburn  8583: sub check_group_parms {
                   8584:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8585:     my @groupitems = ();
                   8586:     my $resultitem;
1.927     albertel 8587:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8588:     foreach my $group (@{$groups}) {
                   8589:         foreach my $level (@levels) {
1.927     albertel 8590:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8591:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8592:         }
                   8593:     }
                   8594:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8595:                             $env{'course.'.$courseid.'.domain'},
                   8596:                                      'course',@groupitems);
                   8597:     return $coursereply;
                   8598: }
                   8599: 
                   8600: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8601:     my ($courseid,@groups) = @_;
                   8602:     @groups = sort(@groups);
1.691     raeburn  8603:     return @groups;
                   8604: }
                   8605: 
1.395     albertel 8606: sub packages_tab_default {
                   8607:     my ($uri,$varname)=@_;
                   8608:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8609: 
                   8610:     my (@extension,@specifics,$do_default);
                   8611:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8612: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8613: 	if ($pack_type eq 'default') {
                   8614: 	    $do_default=1;
                   8615: 	} elsif ($pack_type eq 'extension') {
                   8616: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8617: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8618: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8619: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8620: 	}
                   8621:     }
                   8622:     # first look for a package that matches the requested part id
                   8623:     foreach my $package (@specifics) {
                   8624: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8625: 	next if ($pack_part ne $part);
                   8626: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8627: 	    return $packagetab{"$pack_type&$name&default"};
                   8628: 	}
                   8629:     }
                   8630:     # look for any possible matching non extension_ package
                   8631:     foreach my $package (@specifics) {
                   8632: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8633: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8634: 	    return $packagetab{"$pack_type&$name&default"};
                   8635: 	}
1.585     albertel 8636: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8637: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8638: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8639: 	}
                   8640:     }
1.738     albertel 8641:     # look for any posible extension_ match
                   8642:     foreach my $package (@extension) {
                   8643: 	my ($package,$pack_type)=@{$package};
                   8644: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8645: 	    return $packagetab{"$pack_type&$name&default"};
                   8646: 	}
                   8647: 	if (defined($packagetab{$package."&$name&default"})) {
                   8648: 	    return $packagetab{$package."&$name&default"};
                   8649: 	}
                   8650:     }
                   8651:     # look for a global default setting
                   8652:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8653: 	return $packagetab{"default&$name&default"};
                   8654:     }
1.395     albertel 8655:     return undef;
                   8656: }
                   8657: 
1.334     albertel 8658: sub add_prefix_and_part {
                   8659:     my ($prefix,$part)=@_;
                   8660:     my $keyroot;
                   8661:     if (defined($prefix) && $prefix !~ /^__/) {
                   8662: 	# prefix that has a part already
                   8663: 	$keyroot=$prefix;
                   8664:     } elsif (defined($prefix)) {
                   8665: 	# prefix that is missing a part
                   8666: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8667:     } else {
                   8668: 	# no prefix at all
                   8669: 	if (defined($part)) { $keyroot='_'.$part; }
                   8670:     }
                   8671:     return $keyroot;
                   8672: }
                   8673: 
1.71      www      8674: # ---------------------------------------------------------------- Get metadata
                   8675: 
1.599     albertel 8676: my %metaentry;
1.1070    www      8677: my %importedpartids;
1.71      www      8678: sub metadata {
1.176     www      8679:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8680:     $uri=&declutter($uri);
1.288     albertel 8681:     # if it is a non metadata possible uri return quickly
1.529     albertel 8682:     if (($uri eq '') || 
                   8683: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8684: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8685:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8686: 	return undef;
                   8687:     }
                   8688:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8689: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8690: 	return undef;
1.288     albertel 8691:     }
1.73      www      8692:     my $filename=$uri;
                   8693:     $uri=~s/\.meta$//;
1.172     www      8694: #
                   8695: # Is the metadata already cached?
1.177     www      8696: # Look at timestamp of caching
1.172     www      8697: # Everything is cached by the main uri, libraries are never directly cached
                   8698: #
1.428     albertel 8699:     if (!defined($liburi)) {
1.599     albertel 8700: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8701: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8702:     }
                   8703:     {
1.1069    www      8704: # Imported parts would go here
1.1070    www      8705:         my %importedids=();
                   8706:         my @origfileimportpartids=();
1.1069    www      8707:         my $importedparts=0;
1.172     www      8708: #
                   8709: # Is this a recursive call for a library?
                   8710: #
1.599     albertel 8711: #	if (! exists($metacache{$uri})) {
                   8712: #	    $metacache{$uri}={};
                   8713: #	}
1.924     albertel 8714: 	my $cachetime = 60*60;
1.171     www      8715:         if ($liburi) {
                   8716: 	    $liburi=&declutter($liburi);
                   8717:             $filename=$liburi;
1.401     bowersj2 8718:         } else {
1.599     albertel 8719: 	    &devalidate_cache_new('meta',$uri);
                   8720: 	    undef(%metaentry);
1.401     bowersj2 8721: 	}
1.140     www      8722:         my %metathesekeys=();
1.73      www      8723:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8724: 	my $metastring;
1.924     albertel 8725: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8726: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8727: 	    $metastring = 
1.929     albertel 8728: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8729: 					  ('grade_target' => 'meta'));
                   8730: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8731: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8732:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8733: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8734: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8735: 	    $metastring=&getfile($file);
1.489     albertel 8736: 	}
1.208     albertel 8737:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8738:         my $token;
1.140     www      8739:         undef %metathesekeys;
1.71      www      8740:         while ($token=$parser->get_token) {
1.339     albertel 8741: 	    if ($token->[0] eq 'S') {
                   8742: 		if (defined($token->[2]->{'package'})) {
1.172     www      8743: #
                   8744: # This is a package - get package info
                   8745: #
1.339     albertel 8746: 		    my $package=$token->[2]->{'package'};
                   8747: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8748: 		    if (defined($token->[2]->{'id'})) { 
                   8749: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8750: 		    }
1.599     albertel 8751: 		    if ($metaentry{':packages'}) {
                   8752: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8753: 		    } else {
1.599     albertel 8754: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8755: 		    }
1.736     albertel 8756: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8757: 			my $part=$keyroot;
                   8758: 			$part=~s/^\_//;
1.736     albertel 8759: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8760: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8761: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8762: 			    # ignore package.tab specified default values
                   8763:                             # here &package_tab_default() will fetch those
                   8764: 			    if ($subp eq 'default') { next; }
1.736     albertel 8765: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8766: 			    my $unikey;
                   8767: 			    if ($pack =~ /_0$/) {
                   8768: 				$unikey='parameter_0_'.$name;
                   8769: 				$part=0;
                   8770: 			    } else {
                   8771: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8772: 			    }
1.339     albertel 8773: 			    if ($subp eq 'display') {
                   8774: 				$value.=' [Part: '.$part.']';
                   8775: 			    }
1.599     albertel 8776: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8777: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8778: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8779: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8780: 			    }
1.599     albertel 8781: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8782: 				$metaentry{':'.$unikey}=
                   8783: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8784: 			    }
1.339     albertel 8785: 			}
                   8786: 		    }
                   8787: 		} else {
1.172     www      8788: #
                   8789: # This is not a package - some other kind of start tag
1.339     albertel 8790: #
                   8791: 		    my $entry=$token->[1];
1.1068    www      8792: 		    my $unikey='';
1.175     www      8793: 
1.339     albertel 8794: 		    if ($entry eq 'import') {
1.175     www      8795: #
                   8796: # Importing a library here
1.339     albertel 8797: #
1.1067    www      8798:                         my $location=$parser->get_text('/import');
                   8799:                         my $dir=$filename;
                   8800:                         $dir=~s|[^/]*$||;
                   8801:                         $location=&filelocation($dir,$location);
1.1069    www      8802:                        
1.1068    www      8803:                         my $importmode=$token->[2]->{'importmode'};
                   8804:                         if ($importmode eq 'problem') {
1.1069    www      8805: # Import as problem/response
1.1068    www      8806:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8807:                         } elsif ($importmode eq 'part') {
                   8808: # Import as part(s)
1.1069    www      8809:                            $importedparts=1;
                   8810: # We need to get the original file and the imported file to get the part order correct
                   8811: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8812: # Load and inspect original file
1.1070    www      8813:                            if ($#origfileimportpartids<0) {
                   8814:                               undef(%importedpartids);
                   8815:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8816:                               my $origfile=&getfile($origfilelocation);
                   8817:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8818:                            }
                   8819: 
1.1069    www      8820: # Load and inspect imported file
                   8821:                            my $impfile=&getfile($location);
                   8822:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8823:                            if ($#impfilepartids>=0) {
                   8824: # This problem had parts
1.1070    www      8825:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8826:                            } else {
                   8827: # Importing by turning a single problem into a problem part
                   8828: # It gets the import-tags ID as part-ID
                   8829:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8830:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8831:                            }
1.1068    www      8832:                         } else {
                   8833: # Normal import
                   8834:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8835:                            if (defined($token->[2]->{'id'})) {
                   8836:                               $unikey.='_'.$token->[2]->{'id'};
                   8837:                            }
1.1067    www      8838:                         }
                   8839: 
1.339     albertel 8840: 			if ($depthcount<20) {
1.736     albertel 8841: 			    my $metadata = 
                   8842: 				&metadata($uri,'keys', $location,$unikey,
                   8843: 					  $depthcount+1);
                   8844: 			    foreach my $meta (split(',',$metadata)) {
                   8845: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8846: 				$metathesekeys{$meta}=1;
1.339     albertel 8847: 			    }
1.1068    www      8848: 			
                   8849:                         }
1.1067    www      8850: 		    } else {
                   8851: #
                   8852: # Not importing, some other kind of non-package, non-library start tag
                   8853: # 
                   8854:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8855:                         if (defined($token->[2]->{'id'})) {
                   8856:                             $unikey.='_'.$token->[2]->{'id'};
                   8857:                         }
1.339     albertel 8858: 			if (defined($token->[2]->{'name'})) { 
                   8859: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8860: 			}
                   8861: 			$metathesekeys{$unikey}=1;
1.736     albertel 8862: 			foreach my $param (@{$token->[3]}) {
                   8863: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8864: 				$token->[2]->{$param};
1.339     albertel 8865: 			}
                   8866: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8867: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8868: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8869: 		 # only ws inside the tag, and not in default, so use default
                   8870: 		 # as value
1.599     albertel 8871: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8872: 			} elsif ( $internaltext =~ /\S/ ) {
                   8873: 		  # something interesting inside the tag
                   8874: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8875: 			} else {
1.908     albertel 8876: 		  # no interesting values, don't set a default
1.339     albertel 8877: 			}
1.172     www      8878: # end of not-a-package not-a-library import
1.339     albertel 8879: 		    }
1.172     www      8880: # end of not-a-package start tag
1.339     albertel 8881: 		}
1.172     www      8882: # the next is the end of "start tag"
1.339     albertel 8883: 	    }
                   8884: 	}
1.483     albertel 8885: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8886: 	$extension = lc($extension);
                   8887: 	if ($extension eq 'htm') { $extension='html'; }
                   8888: 
1.737     albertel 8889: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8890: 	    #no specific packages #how's our extension
                   8891: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8892: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8893: 					 \%metathesekeys);
                   8894: 	}
1.883     albertel 8895: 
                   8896: 	if (!exists($metaentry{':packages'})
                   8897: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8898: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8899: 		#no specific packages well let's get default then
                   8900: 		if ($key!~/^default&/) { next; }
1.488     albertel 8901: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8902: 					     \%metathesekeys);
                   8903: 	    }
                   8904: 	}
1.338     www      8905: # are there custom rights to evaluate
1.599     albertel 8906: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8907: 
1.338     www      8908:     #
                   8909:     # Importing a rights file here
1.339     albertel 8910:     #
                   8911: 	    unless ($depthcount) {
1.599     albertel 8912: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8913: 		my $dir=$filename;
                   8914: 		$dir=~s|[^/]*$||;
                   8915: 		$location=&filelocation($dir,$location);
1.736     albertel 8916: 		my $rights_metadata =
                   8917: 		    &metadata($uri,'keys',$location,'_rights',
                   8918: 			      $depthcount+1);
                   8919: 		foreach my $rights (split(',',$rights_metadata)) {
                   8920: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8921: 		    $metathesekeys{$rights}=1;
1.339     albertel 8922: 		}
                   8923: 	    }
                   8924: 	}
1.737     albertel 8925: 	# uniqifiy package listing
                   8926: 	my %seen;
                   8927: 	my @uniq_packages =
                   8928: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8929: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8930: 
1.1070    www      8931:         if ($importedparts) {
                   8932: # We had imported parts and need to rebuild partorder
                   8933:            $metaentry{':partorder'}='';
                   8934:            $metathesekeys{'partorder'}=1;
                   8935:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8936:                if ($origfileimportpartids[$index] eq 'part') {
                   8937: # original part, part of the problem
                   8938:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8939:                } else {
                   8940: # we have imported parts at this position
                   8941:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8942:                }
                   8943:            }
                   8944:            $metaentry{':partorder'}=~s/^\,//;
                   8945:         }
                   8946: 
1.737     albertel 8947: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8948: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8949: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8950: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8951: # this is the end of "was not already recently cached
1.71      www      8952:     }
1.599     albertel 8953:     return $metaentry{':'.$what};
1.261     albertel 8954: }
                   8955: 
1.488     albertel 8956: sub metadata_create_package_def {
1.483     albertel 8957:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8958:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8959:     if ($subp eq 'default') { next; }
                   8960:     
1.599     albertel 8961:     if (defined($metaentry{':packages'})) {
                   8962: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8963:     } else {
1.599     albertel 8964: 	$metaentry{':packages'}=$package;
1.483     albertel 8965:     }
                   8966:     my $value=$packagetab{$key};
                   8967:     my $unikey;
                   8968:     $unikey='parameter_0_'.$name;
1.599     albertel 8969:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8970:     $$metathesekeys{$unikey}=1;
1.599     albertel 8971:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8972: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8973:     }
1.599     albertel 8974:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8975: 	$metaentry{':'.$unikey}=
                   8976: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8977:     }
                   8978: }
                   8979: 
1.261     albertel 8980: sub metadata_generate_part0 {
                   8981:     my ($metadata,$metacache,$uri) = @_;
                   8982:     my %allnames;
1.737     albertel 8983:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8984: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8985: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8986: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8987: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8988: 	    $allnames{$name}=$part;
                   8989: 	  }
                   8990: 	}
                   8991:     }
                   8992:     foreach my $name (keys(%allnames)) {
                   8993:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8994:       my $key=":parameter_0_$name";
1.261     albertel 8995:       $$metacache{"$key.part"}='0';
                   8996:       $$metacache{"$key.name"}=$name;
1.428     albertel 8997:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8998: 					   $allnames{$name}.'_'.$name.
                   8999: 					   '.type'};
1.428     albertel 9000:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9001: 			     '.display'};
1.644     www      9002:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9003:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9004:       $$metacache{"$key.display"}=$olddis;
                   9005:     }
1.71      www      9006: }
                   9007: 
1.764     albertel 9008: # ------------------------------------------------------ Devalidate title cache
                   9009: 
                   9010: sub devalidate_title_cache {
                   9011:     my ($url)=@_;
                   9012:     if (!$env{'request.course.id'}) { return; }
                   9013:     my $symb=&symbread($url);
                   9014:     if (!$symb) { return; }
                   9015:     my $key=$env{'request.course.id'}."\0".$symb;
                   9016:     &devalidate_cache_new('title',$key);
                   9017: }
                   9018: 
1.1014    droeschl 9019: # ------------------------------------------------- Get the title of a course
                   9020: 
                   9021: sub current_course_title {
                   9022:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9023: }
1.301     www      9024: # ------------------------------------------------- Get the title of a resource
                   9025: 
                   9026: sub gettitle {
                   9027:     my $urlsymb=shift;
                   9028:     my $symb=&symbread($urlsymb);
1.534     albertel 9029:     if ($symb) {
1.620     albertel 9030: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9031: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9032: 	if (defined($cached)) { 
                   9033: 	    return $result;
                   9034: 	}
1.534     albertel 9035: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9036: 	my $title='';
1.907     albertel 9037: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9038: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9039: 	} else {
                   9040: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9041: 		    &GDBM_READER(),0640)) {
                   9042: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9043: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9044: 		untie(%bighash);
                   9045: 	    }
1.534     albertel 9046: 	}
                   9047: 	$title=~s/\&colon\;/\:/gs;
                   9048: 	if ($title) {
1.599     albertel 9049: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9050: 	}
                   9051: 	$urlsymb=$url;
                   9052:     }
                   9053:     my $title=&metadata($urlsymb,'title');
                   9054:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9055:     return $title;
1.301     www      9056: }
1.613     albertel 9057: 
1.614     albertel 9058: sub get_slot {
                   9059:     my ($which,$cnum,$cdom)=@_;
                   9060:     if (!$cnum || !$cdom) {
1.790     albertel 9061: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9062: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9063: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9064:     }
1.703     albertel 9065:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9066:     my %slotinfo;
                   9067:     if (exists($remembered{$key})) {
                   9068: 	$slotinfo{$which} = $remembered{$key};
                   9069:     } else {
                   9070: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9071: 	&Apache::lonhomework::showhash(%slotinfo);
                   9072: 	my ($tmp)=keys(%slotinfo);
                   9073: 	if ($tmp=~/^error:/) { return (); }
                   9074: 	$remembered{$key} = $slotinfo{$which};
                   9075:     }
1.616     albertel 9076:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9077: 	return %{$slotinfo{$which}};
                   9078:     }
                   9079:     return $slotinfo{$which};
1.614     albertel 9080: }
1.31      www      9081: # ------------------------------------------------- Update symbolic store links
                   9082: 
                   9083: sub symblist {
                   9084:     my ($mapname,%newhash)=@_;
1.438     www      9085:     $mapname=&deversion(&declutter($mapname));
1.31      www      9086:     my %hash;
1.620     albertel 9087:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9088:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9089:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9090: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9091: 		next if ($url eq 'last_known'
                   9092: 			 && $env{'form.no_update_last_known'});
                   9093: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9094: 						    $newhash{$url}->[1],
                   9095: 						    $newhash{$url}->[0]);
1.191     harris41 9096:             }
1.31      www      9097:             if (untie(%hash)) {
                   9098: 		return 'ok';
                   9099:             }
                   9100:         }
                   9101:     }
                   9102:     return 'error';
1.212     www      9103: }
                   9104: 
                   9105: # --------------------------------------------------------------- Verify a symb
                   9106: 
                   9107: sub symbverify {
1.510     www      9108:     my ($symb,$thisurl)=@_;
                   9109:     my $thisfn=$thisurl;
1.439     www      9110:     $thisfn=&declutter($thisfn);
1.215     www      9111: # direct jump to resource in page or to a sequence - will construct own symbs
                   9112:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9113: # check URL part
1.409     www      9114:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9115: 
1.431     www      9116:     unless ($url eq $thisfn) { return 0; }
1.213     www      9117: 
1.216     www      9118:     $symb=&symbclean($symb);
1.510     www      9119:     $thisurl=&deversion($thisurl);
1.439     www      9120:     $thisfn=&deversion($thisfn);
1.213     www      9121: 
                   9122:     my %bighash;
                   9123:     my $okay=0;
1.431     www      9124: 
1.620     albertel 9125:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9126:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9127:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9128:             $thisurl =~ s/\?.+$//;
                   9129:         }
1.510     www      9130:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9131:         unless ($ids) {
                   9132:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9133:             $ids=$bighash{$idkey};
1.216     www      9134:         }
                   9135:         if ($ids) {
                   9136: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9137: 	    foreach my $id (split(/\,/,$ids)) {
                   9138: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9139:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9140:                    $symb =~ s/\?.+$//;
                   9141:                }
1.216     www      9142:                if (
                   9143:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9144:    eq $symb) { 
1.620     albertel 9145: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9146: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9147:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9148: 		       $okay=1; 
                   9149: 		   }
                   9150: 	       }
1.216     www      9151: 	   }
                   9152:         }
1.213     www      9153: 	untie(%bighash);
                   9154:     }
                   9155:     return $okay;
1.31      www      9156: }
                   9157: 
1.210     www      9158: # --------------------------------------------------------------- Clean-up symb
                   9159: 
                   9160: sub symbclean {
                   9161:     my $symb=shift;
1.568     albertel 9162:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9163: # remove version from map
                   9164:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9165: 
1.210     www      9166: # remove version from URL
                   9167:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9168: 
1.507     www      9169: # remove wrapper
                   9170: 
1.510     www      9171:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9172:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9173:     return $symb;
1.409     www      9174: }
                   9175: 
                   9176: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9177: 
                   9178: sub encode_symb {
                   9179:     my ($map,$resid,$url)=@_;
                   9180:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9181: }
1.409     www      9182: 
                   9183: sub decode_symb {
1.568     albertel 9184:     my $symb=shift;
                   9185:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9186:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9187:     return (&fixversion($map),$resid,&fixversion($url));
                   9188: }
                   9189: 
                   9190: sub fixversion {
                   9191:     my $fn=shift;
1.609     banghart 9192:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9193:     my %bighash;
                   9194:     my $uri=&clutter($fn);
1.620     albertel 9195:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9196: # is this cached?
1.599     albertel 9197:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9198:     if (defined($cached)) { return $result; }
                   9199: # unfortunately not cached, or expired
1.620     albertel 9200:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9201: 	    &GDBM_READER(),0640)) {
                   9202:  	if ($bighash{'version_'.$uri}) {
                   9203:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9204:  	    unless (($version eq 'mostrecent') || 
                   9205: 		    ($version==&getversion($uri))) {
1.440     www      9206:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9207:  	    }
                   9208:  	}
                   9209:  	untie %bighash;
1.413     www      9210:     }
1.599     albertel 9211:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9212: }
                   9213: 
                   9214: sub deversion {
                   9215:     my $url=shift;
                   9216:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9217:     return $url;
1.210     www      9218: }
                   9219: 
1.31      www      9220: # ------------------------------------------------------ Return symb list entry
                   9221: 
                   9222: sub symbread {
1.249     www      9223:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9224:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9225:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9226: # no filename provided? try from environment
1.44      www      9227:     unless ($thisfn) {
1.620     albertel 9228:         if ($env{'request.symb'}) {
                   9229: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9230: 	}
1.620     albertel 9231: 	$thisfn=$env{'request.filename'};
1.44      www      9232:     }
1.569     albertel 9233:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9234: # is that filename actually a symb? Verify, clean, and return
                   9235:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9236: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9237: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9238: 	}
1.242     www      9239:     }
1.44      www      9240:     $thisfn=declutter($thisfn);
1.31      www      9241:     my %hash;
1.37      www      9242:     my %bighash;
                   9243:     my $syval='';
1.620     albertel 9244:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9245:         my $targetfn = $thisfn;
1.609     banghart 9246:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9247:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9248:         }
1.687     albertel 9249: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9250: 	    $targetfn=$1;
                   9251: 	}
1.620     albertel 9252:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9253:                       &GDBM_READER(),0640)) {
1.481     raeburn  9254: 	    $syval=$hash{$targetfn};
1.37      www      9255:             untie(%hash);
                   9256:         }
                   9257: # ---------------------------------------------------------- There was an entry
                   9258:         if ($syval) {
1.601     albertel 9259: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9260: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9261: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9262: 		    #return $env{$cache_str}='';
1.601     albertel 9263: 		#}    
                   9264: 		#$syval.=$1;
                   9265: 	    #}
1.37      www      9266:         } else {
                   9267: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9268:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9269:                             &GDBM_READER(),0640)) {
1.37      www      9270: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9271:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9272:               unless ($ids) { 
                   9273:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9274:               }
                   9275:               unless ($ids) {
                   9276: # alias?
                   9277: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9278:               }
1.37      www      9279:               if ($ids) {
                   9280: # ------------------------------------------------------------------- Has ID(s)
                   9281:                  my @possibilities=split(/\,/,$ids);
1.39      www      9282:                  if ($#possibilities==0) {
                   9283: # ----------------------------------------------- There is only one possibility
1.37      www      9284: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9285: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9286: 						    $resid,$thisfn);
1.249     www      9287:                  } elsif (!$donotrecurse) {
1.39      www      9288: # ------------------------------------------ There is more than one possibility
                   9289:                      my $realpossible=0;
1.800     albertel 9290:                      foreach my $id (@possibilities) {
                   9291: 			 my $file=$bighash{'src_'.$id};
1.39      www      9292:                          if (&allowed('bre',$file)) {
1.800     albertel 9293:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9294:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9295: 				$realpossible++;
1.626     albertel 9296:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9297: 						    $resid,$thisfn);
1.39      www      9298:                             }
                   9299: 			 }
1.191     harris41 9300:                      }
1.39      www      9301: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9302:                  } else {
                   9303:                      $syval='';
1.37      www      9304:                  }
                   9305: 	      }
                   9306:               untie(%bighash)
1.481     raeburn  9307:            }
1.31      www      9308:         }
1.62      www      9309:         if ($syval) {
1.620     albertel 9310: 	    return $env{$cache_str}=$syval;
1.62      www      9311:         }
1.31      www      9312:     }
1.949     raeburn  9313:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9314:     return $env{$cache_str}='';
1.31      www      9315: }
                   9316: 
                   9317: # ---------------------------------------------------------- Return random seed
                   9318: 
1.32      www      9319: sub numval {
                   9320:     my $txt=shift;
                   9321:     $txt=~tr/A-J/0-9/;
                   9322:     $txt=~tr/a-j/0-9/;
                   9323:     $txt=~tr/K-T/0-9/;
                   9324:     $txt=~tr/k-t/0-9/;
                   9325:     $txt=~tr/U-Z/0-5/;
                   9326:     $txt=~tr/u-z/0-5/;
                   9327:     $txt=~s/\D//g;
1.564     albertel 9328:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9329:     return int($txt);
1.368     albertel 9330: }
                   9331: 
1.484     albertel 9332: sub numval2 {
                   9333:     my $txt=shift;
                   9334:     $txt=~tr/A-J/0-9/;
                   9335:     $txt=~tr/a-j/0-9/;
                   9336:     $txt=~tr/K-T/0-9/;
                   9337:     $txt=~tr/k-t/0-9/;
                   9338:     $txt=~tr/U-Z/0-5/;
                   9339:     $txt=~tr/u-z/0-5/;
                   9340:     $txt=~s/\D//g;
                   9341:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9342:     my $total;
                   9343:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9344:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9345:     return int($total);
                   9346: }
                   9347: 
1.575     albertel 9348: sub numval3 {
                   9349:     use integer;
                   9350:     my $txt=shift;
                   9351:     $txt=~tr/A-J/0-9/;
                   9352:     $txt=~tr/a-j/0-9/;
                   9353:     $txt=~tr/K-T/0-9/;
                   9354:     $txt=~tr/k-t/0-9/;
                   9355:     $txt=~tr/U-Z/0-5/;
                   9356:     $txt=~tr/u-z/0-5/;
                   9357:     $txt=~s/\D//g;
                   9358:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9359:     my $total;
                   9360:     foreach my $val (@txts) { $total+=$val; }
                   9361:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9362:     return $total;
                   9363: }
                   9364: 
1.675     albertel 9365: sub digest {
                   9366:     my ($data)=@_;
                   9367:     my $digest=&Digest::MD5::md5($data);
                   9368:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9369:     my ($e,$f);
                   9370:     {
                   9371:         use integer;
                   9372:         $e=($a+$b);
                   9373:         $f=($c+$d);
                   9374:         if ($_64bit) {
                   9375:             $e=(($e<<32)>>32);
                   9376:             $f=(($f<<32)>>32);
                   9377:         }
                   9378:     }
                   9379:     if (wantarray) {
                   9380: 	return ($e,$f);
                   9381:     } else {
                   9382: 	my $g;
                   9383: 	{
                   9384: 	    use integer;
                   9385: 	    $g=($e+$f);
                   9386: 	    if ($_64bit) {
                   9387: 		$g=(($g<<32)>>32);
                   9388: 	    }
                   9389: 	}
                   9390: 	return $g;
                   9391:     }
                   9392: }
                   9393: 
1.368     albertel 9394: sub latest_rnd_algorithm_id {
1.675     albertel 9395:     return '64bit5';
1.366     albertel 9396: }
1.32      www      9397: 
1.503     albertel 9398: sub get_rand_alg {
                   9399:     my ($courseid)=@_;
1.790     albertel 9400:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9401:     if ($courseid) {
1.620     albertel 9402: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9403:     }
                   9404:     return &latest_rnd_algorithm_id();
                   9405: }
                   9406: 
1.562     albertel 9407: sub validCODE {
                   9408:     my ($CODE)=@_;
                   9409:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9410:     return 0;
                   9411: }
                   9412: 
1.491     albertel 9413: sub getCODE {
1.620     albertel 9414:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9415:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9416: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9417: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9418: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9419:     }
                   9420:     return undef;
                   9421: }
                   9422: 
1.31      www      9423: sub rndseed {
1.155     albertel 9424:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9425:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9426:     if (!defined($symb)) {
1.366     albertel 9427: 	unless ($symb=$wsymb) { return time; }
                   9428:     }
                   9429:     if (!$courseid) { $courseid=$wcourseid; }
                   9430:     if (!$domain) { $domain=$wdomain; }
                   9431:     if (!$username) { $username=$wusername }
1.503     albertel 9432:     my $which=&get_rand_alg();
1.1110    www      9433: 
1.491     albertel 9434:     if (defined(&getCODE())) {
1.675     albertel 9435: 	if ($which eq '64bit5') {
                   9436: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9437: 	} elsif ($which eq '64bit4') {
1.575     albertel 9438: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9439: 	} else {
                   9440: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9441: 	}
1.675     albertel 9442:     } elsif ($which eq '64bit5') {
                   9443: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9444:     } elsif ($which eq '64bit4') {
                   9445: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9446:     } elsif ($which eq '64bit3') {
                   9447: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9448:     } elsif ($which eq '64bit2') {
                   9449: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9450:     } elsif ($which eq '64bit') {
                   9451: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9452:     }
                   9453:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9454: }
                   9455: 
                   9456: sub rndseed_32bit {
                   9457:     my ($symb,$courseid,$domain,$username)=@_;
                   9458:     {
                   9459: 	use integer;
                   9460: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9461: 	my $symbseed=numval($symb) << 22;
                   9462: 	my $namechck=unpack("%32C*",$username) << 17;
                   9463: 	my $nameseed=numval($username) << 12;
                   9464: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9465: 	my $courseseed=unpack("%32C*",$courseid);
                   9466: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9467: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9468: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9469: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9470: 	return $num;
                   9471:     }
                   9472: }
                   9473: 
                   9474: sub rndseed_64bit {
                   9475:     my ($symb,$courseid,$domain,$username)=@_;
                   9476:     {
                   9477: 	use integer;
                   9478: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9479: 	my $symbseed=numval($symb) << 10;
                   9480: 	my $namechck=unpack("%32S*",$username);
                   9481: 	
                   9482: 	my $nameseed=numval($username) << 21;
                   9483: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9484: 	my $courseseed=unpack("%32S*",$courseid);
                   9485: 	
                   9486: 	my $num1=$symbchck+$symbseed+$namechck;
                   9487: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9488: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9489: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9490: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9491: 	return "$num1,$num2";
1.155     albertel 9492:     }
1.366     albertel 9493: }
                   9494: 
1.443     albertel 9495: sub rndseed_64bit2 {
                   9496:     my ($symb,$courseid,$domain,$username)=@_;
                   9497:     {
                   9498: 	use integer;
                   9499: 	# strings need to be an even # of cahracters long, it it is odd the
                   9500:         # last characters gets thrown away
                   9501: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9502: 	my $symbseed=numval($symb) << 10;
                   9503: 	my $namechck=unpack("%32S*",$username.' ');
                   9504: 	
                   9505: 	my $nameseed=numval($username) << 21;
1.501     albertel 9506: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9507: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9508: 	
                   9509: 	my $num1=$symbchck+$symbseed+$namechck;
                   9510: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9511: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9512: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9513: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9514: 	return "$num1,$num2";
                   9515:     }
                   9516: }
                   9517: 
                   9518: sub rndseed_64bit3 {
                   9519:     my ($symb,$courseid,$domain,$username)=@_;
                   9520:     {
                   9521: 	use integer;
                   9522: 	# strings need to be an even # of cahracters long, it it is odd the
                   9523:         # last characters gets thrown away
                   9524: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9525: 	my $symbseed=numval2($symb) << 10;
                   9526: 	my $namechck=unpack("%32S*",$username.' ');
                   9527: 	
                   9528: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9529: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9530: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9531: 	
                   9532: 	my $num1=$symbchck+$symbseed+$namechck;
                   9533: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9534: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9535: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9536: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9537: 	
1.503     albertel 9538: 	return "$num1:$num2";
1.443     albertel 9539:     }
                   9540: }
                   9541: 
1.575     albertel 9542: sub rndseed_64bit4 {
                   9543:     my ($symb,$courseid,$domain,$username)=@_;
                   9544:     {
                   9545: 	use integer;
                   9546: 	# strings need to be an even # of cahracters long, it it is odd the
                   9547:         # last characters gets thrown away
                   9548: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9549: 	my $symbseed=numval3($symb) << 10;
                   9550: 	my $namechck=unpack("%32S*",$username.' ');
                   9551: 	
                   9552: 	my $nameseed=numval3($username) << 21;
                   9553: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9554: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9555: 	
                   9556: 	my $num1=$symbchck+$symbseed+$namechck;
                   9557: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9558: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9559: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9560: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9561: 	
1.575     albertel 9562: 	return "$num1:$num2";
                   9563:     }
                   9564: }
                   9565: 
1.675     albertel 9566: sub rndseed_64bit5 {
                   9567:     my ($symb,$courseid,$domain,$username)=@_;
                   9568:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9569:     return "$num1:$num2";
                   9570: }
                   9571: 
1.366     albertel 9572: sub rndseed_CODE_64bit {
                   9573:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9574:     {
1.366     albertel 9575: 	use integer;
1.443     albertel 9576: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9577: 	my $symbseed=numval2($symb);
1.491     albertel 9578: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9579: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9580: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9581: 	my $num1=$symbseed+$CODEchck;
                   9582: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9583: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9584: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9585: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9586: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9587: 	return "$num1:$num2";
1.366     albertel 9588:     }
                   9589: }
                   9590: 
1.575     albertel 9591: sub rndseed_CODE_64bit4 {
                   9592:     my ($symb,$courseid,$domain,$username)=@_;
                   9593:     {
                   9594: 	use integer;
                   9595: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9596: 	my $symbseed=numval3($symb);
                   9597: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9598: 	my $CODEseed=numval3(&getCODE());
                   9599: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9600: 	my $num1=$symbseed+$CODEchck;
                   9601: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9602: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9603: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9604: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9605: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9606: 	return "$num1:$num2";
                   9607:     }
                   9608: }
                   9609: 
1.675     albertel 9610: sub rndseed_CODE_64bit5 {
                   9611:     my ($symb,$courseid,$domain,$username)=@_;
                   9612:     my $code = &getCODE();
                   9613:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9614:     return "$num1:$num2";
                   9615: }
                   9616: 
1.366     albertel 9617: sub setup_random_from_rndseed {
                   9618:     my ($rndseed)=@_;
1.503     albertel 9619:     if ($rndseed =~/([,:])/) {
                   9620: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9621: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9622:     } else {
                   9623: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9624:     }
1.36      albertel 9625: }
                   9626: 
1.474     albertel 9627: sub latest_receipt_algorithm_id {
1.835     albertel 9628:     return 'receipt3';
1.474     albertel 9629: }
                   9630: 
1.480     www      9631: sub recunique {
                   9632:     my $fucourseid=shift;
                   9633:     my $unique;
1.835     albertel 9634:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9635: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9636: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9637:     } else {
                   9638: 	$unique=$perlvar{'lonReceipt'};
                   9639:     }
                   9640:     return unpack("%32C*",$unique);
                   9641: }
                   9642: 
                   9643: sub recprefix {
                   9644:     my $fucourseid=shift;
                   9645:     my $prefix;
1.835     albertel 9646:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9647: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9648: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9649:     } else {
                   9650: 	$prefix=$perlvar{'lonHostID'};
                   9651:     }
                   9652:     return unpack("%32C*",$prefix);
                   9653: }
                   9654: 
1.76      www      9655: sub ireceipt {
1.474     albertel 9656:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9657: 
                   9658:     my $return =&recprefix($fucourseid).'-';
                   9659: 
                   9660:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9661: 	$env{'request.state'} eq 'construct') {
                   9662: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9663: 	return $return;
                   9664:     }
                   9665: 
1.76      www      9666:     my $cuname=unpack("%32C*",$funame);
                   9667:     my $cudom=unpack("%32C*",$fudom);
                   9668:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9669:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9670:     my $cunique=&recunique($fucourseid);
1.474     albertel 9671:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9672:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9673: 
1.790     albertel 9674: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9675: 			       
                   9676: 	$return.= ($cunique%$cuname+
                   9677: 		   $cunique%$cudom+
                   9678: 		   $cusymb%$cuname+
                   9679: 		   $cusymb%$cudom+
                   9680: 		   $cucourseid%$cuname+
                   9681: 		   $cucourseid%$cudom+
                   9682: 		   $cpart%$cuname+
                   9683: 		   $cpart%$cudom);
                   9684:     } else {
                   9685: 	$return.= ($cunique%$cuname+
                   9686: 		   $cunique%$cudom+
                   9687: 		   $cusymb%$cuname+
                   9688: 		   $cusymb%$cudom+
                   9689: 		   $cucourseid%$cuname+
                   9690: 		   $cucourseid%$cudom);
                   9691:     }
                   9692:     return $return;
1.76      www      9693: }
                   9694: 
                   9695: sub receipt {
1.474     albertel 9696:     my ($part)=@_;
1.790     albertel 9697:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9698:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9699: }
1.260     ng       9700: 
1.790     albertel 9701: sub whichuser {
                   9702:     my ($passedsymb)=@_;
                   9703:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9704:     if (defined($env{'form.grade_symb'})) {
                   9705: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9706: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9707: 	if (!$allowed &&
                   9708: 	    exists($env{'request.course.sec'}) &&
                   9709: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9710: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9711: 			      '/'.$env{'request.course.sec'});
                   9712: 	}
                   9713: 	if ($allowed) {
                   9714: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9715: 	    $courseid=$tmp_courseid;
                   9716: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9717: 	    ($name)=&get_env_multiple('form.grade_username');
                   9718: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9719: 	}
                   9720:     }
                   9721:     if (!$passedsymb) {
                   9722: 	$symb=&symbread();
                   9723:     } else {
                   9724: 	$symb=$passedsymb;
                   9725:     }
                   9726:     $courseid=$env{'request.course.id'};
                   9727:     $domain=$env{'user.domain'};
                   9728:     $name=$env{'user.name'};
                   9729:     if ($name eq 'public' && $domain eq 'public') {
                   9730: 	if (!defined($env{'form.username'})) {
                   9731: 	    $env{'form.username'}.=time.rand(10000000);
                   9732: 	}
                   9733: 	$name.=$env{'form.username'};
                   9734:     }
                   9735:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9736: 
                   9737: }
                   9738: 
1.36      albertel 9739: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9740: # returns either the contents of the file or 
                   9741: # -1 if the file doesn't exist
1.481     raeburn  9742: #
                   9743: # if the target is a file that was uploaded via DOCS, 
                   9744: # a check will be made to see if a current copy exists on the local server,
                   9745: # if it does this will be served, otherwise a copy will be retrieved from
                   9746: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9747: # the local server.   
1.472     albertel 9748: 
1.36      albertel 9749: sub getfile {
1.538     albertel 9750:     my ($file) = @_;
1.609     banghart 9751:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9752:     &repcopy($file);
                   9753:     return &readfile($file);
                   9754: }
                   9755: 
                   9756: sub repcopy_userfile {
                   9757:     my ($file)=@_;
1.609     banghart 9758:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9759:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9760:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9761: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9762:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9763:     if (-e "$file") {
1.828     www      9764: # we already have a local copy, check it out
1.538     albertel 9765: 	my @fileinfo = stat($file);
1.828     www      9766: 	my $rtncode;
                   9767: 	my $info;
1.538     albertel 9768: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9769: 	if ($lwpresp ne 'ok') {
1.828     www      9770: # there is no such file anymore, even though we had a local copy
1.482     albertel 9771: 	    if ($rtncode eq '404') {
1.538     albertel 9772: 		unlink($file);
1.482     albertel 9773: 	    }
                   9774: 	    return -1;
                   9775: 	}
                   9776: 	if ($info < $fileinfo[9]) {
1.828     www      9777: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9778: 	    return 'ok';
1.828     www      9779: 	} else {
                   9780: # the file is outdated, get rid of it
                   9781: 	    unlink($file);
1.482     albertel 9782: 	}
1.828     www      9783:     }
                   9784: # one way or the other, at this point, we don't have the file
                   9785: # construct the correct path for the file
                   9786:     my @parts = ($cdom,$cnum); 
                   9787:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9788: 	push @parts, split(/\//,$1);
                   9789:     }
                   9790:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9791:     foreach my $part (@parts) {
                   9792: 	$path .= '/'.$part;
                   9793: 	if (!-e $path) {
                   9794: 	    mkdir($path,0770);
1.482     albertel 9795: 	}
                   9796:     }
1.828     www      9797: # now the path exists for sure
                   9798: # get a user agent
                   9799:     my $ua=new LWP::UserAgent;
                   9800:     my $transferfile=$file.'.in.transfer';
                   9801: # FIXME: this should flock
                   9802:     if (-e $transferfile) { return 'ok'; }
                   9803:     my $request;
                   9804:     $uri=~s/^\///;
1.980     raeburn  9805:     my $homeserver = &homeserver($cnum,$cdom);
                   9806:     my $protocol = $protocol{$homeserver};
                   9807:     $protocol = 'http' if ($protocol ne 'https');
                   9808:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9809:     my $response=$ua->request($request,$transferfile);
                   9810: # did it work?
                   9811:     if ($response->is_error()) {
                   9812: 	unlink($transferfile);
                   9813: 	&logthis("Userfile repcopy failed for $uri");
                   9814: 	return -1;
                   9815:     }
                   9816: # worked, rename the transfer file
                   9817:     rename($transferfile,$file);
1.607     raeburn  9818:     return 'ok';
1.481     raeburn  9819: }
                   9820: 
1.517     albertel 9821: sub tokenwrapper {
                   9822:     my $uri=shift;
1.980     raeburn  9823:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9824:     $uri=~s|^/||;
1.620     albertel 9825:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9826:     my $token=$1;
1.552     albertel 9827:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9828:     if ($udom && $uname && $file) {
                   9829: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9830:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9831:         my $homeserver = &homeserver($uname,$udom);
                   9832:         my $protocol = $protocol{$homeserver};
                   9833:         $protocol = 'http' if ($protocol ne 'https');
                   9834:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9835:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9836:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9837:     } else {
                   9838:         return '/adm/notfound.html';
                   9839:     }
                   9840: }
                   9841: 
1.828     www      9842: # call with reqtype HEAD: get last modification time
                   9843: # call with reqtype GET: get the file contents
                   9844: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9845: #
1.481     raeburn  9846: sub getuploaded {
                   9847:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9848:     $uri=~s/^\///;
1.980     raeburn  9849:     my $homeserver = &homeserver($cnum,$cdom);
                   9850:     my $protocol = $protocol{$homeserver};
                   9851:     $protocol = 'http' if ($protocol ne 'https');
                   9852:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9853:     my $ua=new LWP::UserAgent;
                   9854:     my $request=new HTTP::Request($reqtype,$uri);
                   9855:     my $response=$ua->request($request);
                   9856:     $$rtncode = $response->code;
1.482     albertel 9857:     if (! $response->is_success()) {
                   9858: 	return 'failed';
                   9859:     }      
                   9860:     if ($reqtype eq 'HEAD') {
1.486     www      9861: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9862:     } elsif ($reqtype eq 'GET') {
                   9863: 	$$info = $response->content;
1.472     albertel 9864:     }
1.482     albertel 9865:     return 'ok';
1.36      albertel 9866: }
                   9867: 
1.481     raeburn  9868: sub readfile {
                   9869:     my $file = shift;
                   9870:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9871:     my $fh;
                   9872:     open($fh,"<$file");
                   9873:     my $a='';
1.800     albertel 9874:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9875:     return $a;
                   9876: }
                   9877: 
1.36      albertel 9878: sub filelocation {
1.590     banghart 9879:     my ($dir,$file) = @_;
                   9880:     my $location;
                   9881:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9882: 
                   9883:     if ($file =~ m-^/adm/-) {
                   9884: 	$file=~s-^/adm/wrapper/-/-;
                   9885: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9886:     }
1.882     albertel 9887: 
1.590     banghart 9888:     if ($file=~m:^/~:) { # is a contruction space reference
                   9889:         $location = $file;
                   9890:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9891:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9892: 	# is a correct contruction space reference
                   9893:         $location = $file;
1.956     raeburn  9894:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9895:         $location = $file;
1.609     banghart 9896:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9897:         my ($udom,$uname,$filename)=
1.811     albertel 9898:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9899:         my $home=&homeserver($uname,$udom);
                   9900:         my $is_me=0;
                   9901:         my @ids=&current_machine_ids();
                   9902:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9903:         if ($is_me) {
1.1117    foxr     9904:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9905:         } else {
                   9906:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9907:   	      $udom.'/'.$uname.'/'.$filename;
                   9908:         }
1.882     albertel 9909:     } elsif ($file =~ m-^/adm/-) {
                   9910: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9911:     } else {
                   9912:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9913:         $file=~s:^/res/:/:;
                   9914:         if ( !( $file =~ m:^/:) ) {
                   9915:             $location = $dir. '/'.$file;
                   9916:         } else {
                   9917:             $location = '/home/httpd/html/res'.$file;
                   9918:         }
1.59      albertel 9919:     }
1.590     banghart 9920:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9921:     while ($location=~m{/\.\./}) {
                   9922: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9923: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9924: 	} else {
                   9925: 	    $location=~ s{/\.\./}{/}g;
                   9926: 	}
                   9927:     } #remove dir/..
1.590     banghart 9928:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9929:     return $location;
1.46      www      9930: }
1.36      albertel 9931: 
1.46      www      9932: sub hreflocation {
                   9933:     my ($dir,$file)=@_;
1.980     raeburn  9934:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9935: 	$file=filelocation($dir,$file);
1.700     albertel 9936:     } elsif ($file=~m-^/adm/-) {
                   9937: 	$file=~s-^/adm/wrapper/-/-;
                   9938: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9939:     }
                   9940:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9941: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9942:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9943: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9944:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9945: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9946: 	    -/uploaded/$1/$2/-x;
1.46      www      9947:     }
1.913     albertel 9948:     if ($file=~ m{^/userfiles/}) {
                   9949: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9950:     }
1.462     albertel 9951:     return $file;
1.465     albertel 9952: }
                   9953: 
                   9954: sub current_machine_domains {
1.853     albertel 9955:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9956: }
                   9957: 
                   9958: sub machine_domains {
                   9959:     my ($hostname) = @_;
1.465     albertel 9960:     my @domains;
1.838     albertel 9961:     my %hostname = &all_hostnames();
1.465     albertel 9962:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9963: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9964: 	if ($hostname eq $name) {
1.844     albertel 9965: 	    push(@domains,&host_domain($id));
1.465     albertel 9966: 	}
                   9967:     }
                   9968:     return @domains;
                   9969: }
                   9970: 
                   9971: sub current_machine_ids {
1.853     albertel 9972:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9973: }
                   9974: 
                   9975: sub machine_ids {
                   9976:     my ($hostname) = @_;
                   9977:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9978:     my @ids;
1.888     albertel 9979:     my %name_to_host = &all_names();
1.889     albertel 9980:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9981: 	return @{ $name_to_host{$hostname} };
                   9982:     }
                   9983:     return;
1.31      www      9984: }
                   9985: 
1.824     raeburn  9986: sub additional_machine_domains {
                   9987:     my @domains;
                   9988:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9989:     while( my $line = <$fh>) {
                   9990:         $line =~ s/\s//g;
                   9991:         push(@domains,$line);
                   9992:     }
                   9993:     return @domains;
                   9994: }
                   9995: 
                   9996: sub default_login_domain {
                   9997:     my $domain = $perlvar{'lonDefDomain'};
                   9998:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9999:     foreach my $posdom (&current_machine_domains(),
                   10000:                         &additional_machine_domains()) {
                   10001:         if (lc($posdom) eq lc($testdomain)) {
                   10002:             $domain=$posdom;
                   10003:             last;
                   10004:         }
                   10005:     }
                   10006:     return $domain;
                   10007: }
                   10008: 
1.31      www      10009: # ------------------------------------------------------------- Declutters URLs
                   10010: 
                   10011: sub declutter {
                   10012:     my $thisfn=shift;
1.569     albertel 10013:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10014:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10015:     $thisfn=~s/^\///;
1.697     albertel 10016:     $thisfn=~s|^adm/wrapper/||;
                   10017:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10018:     $thisfn=~s/^res\///;
1.1032    raeburn  10019:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10020:         $thisfn=~s/\?.+$//;
                   10021:     }
1.268     www      10022:     return $thisfn;
                   10023: }
                   10024: 
                   10025: # ------------------------------------------------------------- Clutter up URLs
                   10026: 
                   10027: sub clutter {
                   10028:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10029:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10030: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10031:        $thisfn='/res'.$thisfn; 
                   10032:     }
1.1031    raeburn  10033:     if ($thisfn !~m|^/adm|) {
                   10034: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10035: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10036: 	} else {
                   10037: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10038: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10039: 	    if ($embstyle eq 'ssi'
                   10040: 		|| ($embstyle eq 'hdn')
                   10041: 		|| ($embstyle eq 'rat')
                   10042: 		|| ($embstyle eq 'prv')
                   10043: 		|| ($embstyle eq 'ign')) {
                   10044: 		#do nothing with these
                   10045: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10046: 		|| ($embstyle eq 'emb')
                   10047: 		|| ($embstyle eq 'wrp')) {
                   10048: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10049: 	    } elsif ($embstyle eq 'unk'
                   10050: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10051: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10052: 	    } else {
1.718     www      10053: #		&logthis("Got a blank emb style");
1.695     albertel 10054: 	    }
1.694     albertel 10055: 	}
                   10056:     }
1.31      www      10057:     return $thisfn;
1.12      www      10058: }
                   10059: 
1.787     albertel 10060: sub clutter_with_no_wrapper {
                   10061:     my $uri = &clutter(shift);
                   10062:     if ($uri =~ m-^/adm/-) {
                   10063: 	$uri =~ s-^/adm/wrapper/-/-;
                   10064: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10065:     }
                   10066:     return $uri;
                   10067: }
                   10068: 
1.557     albertel 10069: sub freeze_escape {
                   10070:     my ($value)=@_;
                   10071:     if (ref($value)) {
                   10072: 	$value=&nfreeze($value);
                   10073: 	return '__FROZEN__'.&escape($value);
                   10074:     }
                   10075:     return &escape($value);
                   10076: }
                   10077: 
1.11      www      10078: 
1.557     albertel 10079: sub thaw_unescape {
                   10080:     my ($value)=@_;
                   10081:     if ($value =~ /^__FROZEN__/) {
                   10082: 	substr($value,0,10,undef);
                   10083: 	$value=&unescape($value);
                   10084: 	return &thaw($value);
                   10085:     }
                   10086:     return &unescape($value);
                   10087: }
                   10088: 
1.436     albertel 10089: sub correct_line_ends {
                   10090:     my ($result)=@_;
                   10091:     $$result =~s/\r\n/\n/mg;
                   10092:     $$result =~s/\r/\n/mg;
1.415     albertel 10093: }
1.1       albertel 10094: # ================================================================ Main Program
                   10095: 
1.184     www      10096: sub goodbye {
1.204     albertel 10097:    &logthis("Starting Shut down");
1.443     albertel 10098: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10099:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10100: #converted
1.599     albertel 10101: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10102:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10103: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10104: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10105: #1.1 only
1.870     albertel 10106: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10107: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10108: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10109: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10110:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10111:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10112:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10113:    &flushcourselogs();
                   10114:    &logthis("Shutting down");
                   10115: }
                   10116: 
1.852     albertel 10117: sub get_dns {
1.869     albertel 10118:     my ($url,$func,$ignore_cache) = @_;
                   10119:     if (!$ignore_cache) {
                   10120: 	my ($content,$cached)=
                   10121: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10122: 	if ($cached) {
                   10123: 	    &$func($content);
                   10124: 	    return;
                   10125: 	}
                   10126:     }
                   10127: 
                   10128:     my %alldns;
1.852     albertel 10129:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10130:     foreach my $dns (<$config>) {
                   10131: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10132:         my $line = $1;
                   10133:         my ($host,$protocol) = split(/:/,$line);
                   10134:         if ($protocol ne 'https') {
                   10135:             $protocol = 'http';
                   10136:         }
                   10137: 	$alldns{$host} = $protocol;
1.869     albertel 10138:     }
                   10139:     while (%alldns) {
                   10140: 	my ($dns) = keys(%alldns);
1.852     albertel 10141: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10142: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10143: 	my $response=$ua->request($request);
1.979     raeburn  10144:         delete($alldns{$dns});
1.852     albertel 10145: 	next if ($response->is_error());
                   10146: 	my @content = split("\n",$response->content);
1.869     albertel 10147: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10148: 	&$func(\@content);
1.869     albertel 10149: 	return;
1.852     albertel 10150:     }
                   10151:     close($config);
1.871     albertel 10152:     my $which = (split('/',$url))[3];
                   10153:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10154:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10155:     my @content = <$config>;
                   10156:     &$func(\@content);
                   10157:     return;
1.852     albertel 10158: }
1.327     albertel 10159: # ------------------------------------------------------------ Read domain file
                   10160: {
1.852     albertel 10161:     my $loaded;
1.846     albertel 10162:     my %domain;
                   10163: 
1.852     albertel 10164:     sub parse_domain_tab {
                   10165: 	my ($lines) = @_;
                   10166: 	foreach my $line (@$lines) {
                   10167: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10168: 
1.846     albertel 10169: 	    chomp($line);
1.852     albertel 10170: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10171: 	    my %this_domain;
                   10172: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10173: 			       'lang_def', 'city', 'longi', 'lati',
                   10174: 			       'primary') {
                   10175: 		$this_domain{$field} = shift(@elements);
                   10176: 	    }
                   10177: 	    $domain{$name} = \%this_domain;
1.852     albertel 10178: 	}
                   10179:     }
1.864     albertel 10180: 
                   10181:     sub reset_domain_info {
                   10182: 	undef($loaded);
                   10183: 	undef(%domain);
                   10184:     }
                   10185: 
1.852     albertel 10186:     sub load_domain_tab {
1.869     albertel 10187: 	my ($ignore_cache) = @_;
                   10188: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10189: 	my $fh;
                   10190: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10191: 	    my @lines = <$fh>;
                   10192: 	    &parse_domain_tab(\@lines);
1.448     albertel 10193: 	}
1.852     albertel 10194: 	close($fh);
                   10195: 	$loaded = 1;
1.327     albertel 10196:     }
1.846     albertel 10197: 
                   10198:     sub domain {
1.852     albertel 10199: 	&load_domain_tab() if (!$loaded);
                   10200: 
1.846     albertel 10201: 	my ($name,$what) = @_;
                   10202: 	return if ( !exists($domain{$name}) );
                   10203: 
                   10204: 	if (!$what) {
                   10205: 	    return $domain{$name}{'description'};
                   10206: 	}
                   10207: 	return $domain{$name}{$what};
                   10208:     }
1.974     raeburn  10209: 
                   10210:     sub domain_info {
                   10211:         &load_domain_tab() if (!$loaded);
                   10212:         return %domain;
                   10213:     }
                   10214: 
1.327     albertel 10215: }
                   10216: 
                   10217: 
1.1       albertel 10218: # ------------------------------------------------------------- Read hosts file
                   10219: {
1.838     albertel 10220:     my %hostname;
1.844     albertel 10221:     my %hostdom;
1.845     albertel 10222:     my %libserv;
1.852     albertel 10223:     my $loaded;
1.888     albertel 10224:     my %name_to_host;
1.1074    raeburn  10225:     my %internetdom;
1.1107    raeburn  10226:     my %LC_dns_serv;
1.852     albertel 10227: 
                   10228:     sub parse_hosts_tab {
                   10229: 	my ($file) = @_;
                   10230: 	foreach my $configline (@$file) {
                   10231: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10232:             chomp($configline);
                   10233: 	    if ($configline =~ /^\^/) {
                   10234:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10235:                     $LC_dns_serv{$1} = 1;
                   10236:                 }
                   10237:                 next;
                   10238:             }
1.1074    raeburn  10239: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10240: 	    $name=~s/\s//g;
                   10241: 	    if ($id && $domain && $role && $name) {
                   10242: 		$hostname{$id}=$name;
1.888     albertel 10243: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10244: 		$hostdom{$id}=$domain;
                   10245: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10246:                 if (defined($protocol)) {
                   10247:                     if ($protocol eq 'https') {
                   10248:                         $protocol{$id} = $protocol;
                   10249:                     } else {
                   10250:                         $protocol{$id} = 'http'; 
                   10251:                     }
1.968     raeburn  10252:                 } else {
1.969     raeburn  10253:                     $protocol{$id} = 'http';
1.968     raeburn  10254:                 }
1.1074    raeburn  10255:                 if (defined($intdom)) {
                   10256:                     $internetdom{$id} = $intdom;
                   10257:                 }
1.852     albertel 10258: 	    }
                   10259: 	}
                   10260:     }
1.864     albertel 10261:     
                   10262:     sub reset_hosts_info {
1.897     albertel 10263: 	&purge_remembered();
1.864     albertel 10264: 	&reset_domain_info();
                   10265: 	&reset_hosts_ip_info();
1.892     albertel 10266: 	undef(%name_to_host);
1.864     albertel 10267: 	undef(%hostname);
                   10268: 	undef(%hostdom);
                   10269: 	undef(%libserv);
                   10270: 	undef($loaded);
                   10271:     }
1.1       albertel 10272: 
1.852     albertel 10273:     sub load_hosts_tab {
1.869     albertel 10274: 	my ($ignore_cache) = @_;
                   10275: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10276: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10277: 	my @config = <$config>;
                   10278: 	&parse_hosts_tab(\@config);
                   10279: 	close($config);
                   10280: 	$loaded=1;
1.1       albertel 10281:     }
1.852     albertel 10282: 
1.838     albertel 10283:     sub hostname {
1.852     albertel 10284: 	&load_hosts_tab() if (!$loaded);
                   10285: 
1.838     albertel 10286: 	my ($lonid) = @_;
                   10287: 	return $hostname{$lonid};
                   10288:     }
1.845     albertel 10289: 
1.838     albertel 10290:     sub all_hostnames {
1.852     albertel 10291: 	&load_hosts_tab() if (!$loaded);
                   10292: 
1.838     albertel 10293: 	return %hostname;
                   10294:     }
1.845     albertel 10295: 
1.888     albertel 10296:     sub all_names {
                   10297: 	&load_hosts_tab() if (!$loaded);
                   10298: 
                   10299: 	return %name_to_host;
                   10300:     }
                   10301: 
1.974     raeburn  10302:     sub all_host_domain {
                   10303:         &load_hosts_tab() if (!$loaded);
                   10304:         return %hostdom;
                   10305:     }
                   10306: 
1.845     albertel 10307:     sub is_library {
1.852     albertel 10308: 	&load_hosts_tab() if (!$loaded);
                   10309: 
1.845     albertel 10310: 	return exists($libserv{$_[0]});
                   10311:     }
                   10312: 
                   10313:     sub all_library {
1.852     albertel 10314: 	&load_hosts_tab() if (!$loaded);
                   10315: 
1.845     albertel 10316: 	return %libserv;
                   10317:     }
                   10318: 
1.1062    droeschl 10319:     sub unique_library {
                   10320: 	#2x reverse removes all hostnames that appear more than once
                   10321:         my %unique = reverse &all_library();
                   10322:         return reverse %unique;
                   10323:     }
                   10324: 
1.841     albertel 10325:     sub get_servers {
1.852     albertel 10326: 	&load_hosts_tab() if (!$loaded);
                   10327: 
1.841     albertel 10328: 	my ($domain,$type) = @_;
                   10329: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10330: 	                                          : %hostname;
                   10331: 	my %result;
1.842     albertel 10332: 	if (ref($domain) eq 'ARRAY') {
                   10333: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10334: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10335: 		    $result{$host} = $hostname;
                   10336: 		}
                   10337: 	    }
                   10338: 	} else {
                   10339: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10340: 		if ($hostdom{$host} eq $domain) {
                   10341: 		    $result{$host} = $hostname;
                   10342: 		}
1.841     albertel 10343: 	    }
                   10344: 	}
                   10345: 	return %result;
                   10346:     }
1.845     albertel 10347: 
1.1062    droeschl 10348:     sub get_unique_servers {
                   10349:         my %unique = reverse &get_servers(@_);
                   10350: 	return reverse %unique;
                   10351:     }
                   10352: 
1.844     albertel 10353:     sub host_domain {
1.852     albertel 10354: 	&load_hosts_tab() if (!$loaded);
                   10355: 
1.844     albertel 10356: 	my ($lonid) = @_;
                   10357: 	return $hostdom{$lonid};
                   10358:     }
                   10359: 
1.841     albertel 10360:     sub all_domains {
1.852     albertel 10361: 	&load_hosts_tab() if (!$loaded);
                   10362: 
1.841     albertel 10363: 	my %seen;
                   10364: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10365: 	return @uniq;
                   10366:     }
1.1074    raeburn  10367: 
                   10368:     sub internet_dom {
                   10369:         &load_hosts_tab() if (!$loaded);
                   10370: 
                   10371:         my ($lonid) = @_;
                   10372:         return $internetdom{$lonid};
                   10373:     }
1.1107    raeburn  10374: 
                   10375:     sub is_LC_dns {
                   10376:         &load_hosts_tab() if (!$loaded);
                   10377: 
                   10378:         my ($hostname) = @_;
                   10379:         return exists($LC_dns_serv{$hostname});
                   10380:     }
                   10381: 
1.1       albertel 10382: }
                   10383: 
1.847     albertel 10384: { 
                   10385:     my %iphost;
1.856     albertel 10386:     my %name_to_ip;
                   10387:     my %lonid_to_ip;
1.869     albertel 10388: 
1.847     albertel 10389:     sub get_hosts_from_ip {
                   10390: 	my ($ip) = @_;
                   10391: 	my %iphosts = &get_iphost();
                   10392: 	if (ref($iphosts{$ip})) {
                   10393: 	    return @{$iphosts{$ip}};
                   10394: 	}
                   10395: 	return;
1.839     albertel 10396:     }
1.864     albertel 10397:     
                   10398:     sub reset_hosts_ip_info {
                   10399: 	undef(%iphost);
                   10400: 	undef(%name_to_ip);
                   10401: 	undef(%lonid_to_ip);
                   10402:     }
1.856     albertel 10403: 
                   10404:     sub get_host_ip {
                   10405: 	my ($lonid) = @_;
                   10406: 	if (exists($lonid_to_ip{$lonid})) {
                   10407: 	    return $lonid_to_ip{$lonid};
                   10408: 	}
                   10409: 	my $name=&hostname($lonid);
                   10410:    	my $ip = gethostbyname($name);
                   10411: 	return if (!$ip || length($ip) ne 4);
                   10412: 	$ip=inet_ntoa($ip);
                   10413: 	$name_to_ip{$name}   = $ip;
                   10414: 	$lonid_to_ip{$lonid} = $ip;
                   10415: 	return $ip;
                   10416:     }
1.847     albertel 10417:     
                   10418:     sub get_iphost {
1.869     albertel 10419: 	my ($ignore_cache) = @_;
1.894     albertel 10420: 
1.869     albertel 10421: 	if (!$ignore_cache) {
                   10422: 	    if (%iphost) {
                   10423: 		return %iphost;
                   10424: 	    }
                   10425: 	    my ($ip_info,$cached)=
                   10426: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10427: 	    if ($cached) {
                   10428: 		%iphost      = %{$ip_info->[0]};
                   10429: 		%name_to_ip  = %{$ip_info->[1]};
                   10430: 		%lonid_to_ip = %{$ip_info->[2]};
                   10431: 		return %iphost;
                   10432: 	    }
                   10433: 	}
1.894     albertel 10434: 
                   10435: 	# get yesterday's info for fallback
                   10436: 	my %old_name_to_ip;
                   10437: 	my ($ip_info,$cached)=
                   10438: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10439: 	if ($cached) {
                   10440: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10441: 	}
                   10442: 
1.888     albertel 10443: 	my %name_to_host = &all_names();
                   10444: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10445: 	    my $ip;
                   10446: 	    if (!exists($name_to_ip{$name})) {
                   10447: 		$ip = gethostbyname($name);
                   10448: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10449: 		    if (defined($old_name_to_ip{$name})) {
                   10450: 			$ip = $old_name_to_ip{$name};
                   10451: 			&logthis("Can't find $name defaulting to old $ip");
                   10452: 		    } else {
                   10453: 			&logthis("Name $name no IP found");
                   10454: 			next;
                   10455: 		    }
                   10456: 		} else {
                   10457: 		    $ip=inet_ntoa($ip);
1.847     albertel 10458: 		}
                   10459: 		$name_to_ip{$name} = $ip;
                   10460: 	    } else {
                   10461: 		$ip = $name_to_ip{$name};
1.653     albertel 10462: 	    }
1.888     albertel 10463: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10464: 		$lonid_to_ip{$id} = $ip;
                   10465: 	    }
                   10466: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10467: 	}
1.869     albertel 10468: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10469: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10470: 				      48*60*60);
1.869     albertel 10471: 
1.847     albertel 10472: 	return %iphost;
1.598     albertel 10473:     }
                   10474: 
1.992     raeburn  10475:     #
                   10476:     #  Given a DNS returns the loncapa host name for that DNS 
                   10477:     # 
                   10478:     sub host_from_dns {
                   10479:         my ($dns) = @_;
                   10480:         my @hosts;
                   10481:         my $ip;
                   10482: 
1.993     raeburn  10483:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10484:             $ip = $name_to_ip{$dns};
                   10485:         }
                   10486:         if (!$ip) {
                   10487:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10488:             if (length($ip) == 4) { 
                   10489: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10490:             }
                   10491:         }
                   10492:         if ($ip) {
                   10493: 	    @hosts = get_hosts_from_ip($ip);
                   10494: 	    return $hosts[0];
                   10495:         }
                   10496:         return undef;
1.986     foxr     10497:     }
1.992     raeburn  10498: 
1.1074    raeburn  10499:     sub get_internet_names {
                   10500:         my ($lonid) = @_;
                   10501:         return if ($lonid eq '');
                   10502:         my ($idnref,$cached)=
                   10503:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10504:         if ($cached) {
                   10505:             return $idnref;
                   10506:         }
                   10507:         my $ip = &get_host_ip($lonid);
                   10508:         my @hosts = &get_hosts_from_ip($ip);
                   10509:         my %iphost = &get_iphost();
                   10510:         my (@idns,%seen);
                   10511:         foreach my $id (@hosts) {
                   10512:             my $dom = &host_domain($id);
                   10513:             my $prim_id = &domain($dom,'primary');
                   10514:             my $prim_ip = &get_host_ip($prim_id);
                   10515:             next if ($seen{$prim_ip});
                   10516:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10517:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10518:                     my $intdom = &internet_dom($id);
                   10519:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10520:                         push(@idns,$intdom);
                   10521:                     }
                   10522:                 }
                   10523:             }
                   10524:             $seen{$prim_ip} = 1;
                   10525:         }
                   10526:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10527:     }
                   10528: 
1.986     foxr     10529: }
                   10530: 
1.1079    raeburn  10531: sub all_loncaparevs {
                   10532:     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);
                   10533: }
                   10534: 
1.862     albertel 10535: BEGIN {
                   10536: 
                   10537: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10538:     unless ($readit) {
                   10539: {
                   10540:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10541:     %perlvar = (%perlvar,%{$configvars});
                   10542: }
                   10543: 
                   10544: 
1.1       albertel 10545: # ------------------------------------------------------ Read spare server file
                   10546: {
1.448     albertel 10547:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10548: 
                   10549:     while (my $configline=<$config>) {
                   10550:        chomp($configline);
1.284     matthew  10551:        if ($configline) {
1.784     albertel 10552: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10553: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10554: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10555:        }
                   10556:     }
1.448     albertel 10557:     close($config);
1.1       albertel 10558: }
1.11      www      10559: # ------------------------------------------------------------ Read permissions
                   10560: {
1.448     albertel 10561:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10562: 
                   10563:     while (my $configline=<$config>) {
1.448     albertel 10564: 	chomp($configline);
                   10565: 	if ($configline) {
                   10566: 	    my ($role,$perm)=split(/ /,$configline);
                   10567: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10568: 	}
1.11      www      10569:     }
1.448     albertel 10570:     close($config);
1.11      www      10571: }
                   10572: 
                   10573: # -------------------------------------------- Read plain texts for permissions
                   10574: {
1.448     albertel 10575:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10576: 
                   10577:     while (my $configline=<$config>) {
1.448     albertel 10578: 	chomp($configline);
                   10579: 	if ($configline) {
1.742     raeburn  10580: 	    my ($short,@plain)=split(/:/,$configline);
                   10581:             %{$prp{$short}} = ();
                   10582: 	    if (@plain > 0) {
                   10583:                 $prp{$short}{'std'} = $plain[0];
                   10584:                 for (my $i=1; $i<@plain; $i++) {
                   10585:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10586:                 }
                   10587:             }
1.448     albertel 10588: 	}
1.135     www      10589:     }
1.448     albertel 10590:     close($config);
1.135     www      10591: }
                   10592: 
                   10593: # ---------------------------------------------------------- Read package table
                   10594: {
1.448     albertel 10595:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10596: 
                   10597:     while (my $configline=<$config>) {
1.483     albertel 10598: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10599: 	chomp($configline);
                   10600: 	my ($short,$plain)=split(/:/,$configline);
                   10601: 	my ($pack,$name)=split(/\&/,$short);
                   10602: 	if ($plain ne '') {
                   10603: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10604: 	    $packagetab{$short}=$plain; 
                   10605: 	}
1.11      www      10606:     }
1.448     albertel 10607:     close($config);
1.329     matthew  10608: }
                   10609: 
1.1073    raeburn  10610: # ---------------------------------------------------------- Read loncaparev table
                   10611: {
                   10612:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10613:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10614:             while (my $configline=<$config>) {
                   10615:                 chomp($configline);
                   10616:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10617:                 $loncaparevs{$hostid}=$loncaparev;
                   10618:             }
                   10619:             close($config);
                   10620:         }
                   10621:     }
                   10622: }
                   10623: 
1.1074    raeburn  10624: # ---------------------------------------------------------- Read serverhostID table
                   10625: {
                   10626:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10627:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10628:             while (my $configline=<$config>) {
                   10629:                 chomp($configline);
                   10630:                 my ($name,$id)=split(/:/,$configline);
                   10631:                 $serverhomeIDs{$name}=$id;
                   10632:             }
                   10633:             close($config);
                   10634:         }
                   10635:     }
                   10636: }
                   10637: 
1.1079    raeburn  10638: {
                   10639:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10640:     if (-e $file) {
                   10641:         my $parser = HTML::LCParser->new($file);
                   10642:         while (my $token = $parser->get_token()) {
                   10643:             if ($token->[0] eq 'S') {
                   10644:                 my $item = $token->[1];
                   10645:                 my $name = $token->[2]{'name'};
                   10646:                 my $value = $token->[2]{'value'};
                   10647:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10648:                     my $release = $parser->get_text();
                   10649:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10650:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10651:                 }
                   10652:             }
                   10653:         }
                   10654:     }
1.1073    raeburn  10655: }
                   10656: 
1.329     matthew  10657: # ------------- set up temporary directory
                   10658: {
1.1117    foxr     10659:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10660: 
1.11      www      10661: }
                   10662: 
1.794     albertel 10663: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10664: 				'compress_threshold'=> 20_000,
                   10665:  			        });
1.185     www      10666: 
1.281     www      10667: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10668: $dumpcount=0;
1.958     www      10669: $locknum=0;
1.22      www      10670: 
1.163     harris41 10671: &logtouch();
1.672     albertel 10672: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10673: $readit=1;
1.564     albertel 10674:     {
                   10675: 	use integer;
                   10676: 	my $test=(2**32)+1;
1.568     albertel 10677: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10678: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10679:     }
1.195     www      10680: }
1.1       albertel 10681: }
1.179     www      10682: 
1.1       albertel 10683: 1;
1.191     harris41 10684: __END__
                   10685: 
1.243     albertel 10686: =pod
                   10687: 
1.191     harris41 10688: =head1 NAME
                   10689: 
1.243     albertel 10690: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10691: 
                   10692: =head1 SYNOPSIS
                   10693: 
1.243     albertel 10694: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10695: 
                   10696:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10697: 
1.243     albertel 10698: Common parameters:
                   10699: 
                   10700: =over 4
                   10701: 
                   10702: =item *
                   10703: 
                   10704: $uname : an internal username (if $cname expecting a course Id specifically)
                   10705: 
                   10706: =item *
                   10707: 
                   10708: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10709: 
                   10710: =item *
                   10711: 
                   10712: $symb : a resource instance identifier
                   10713: 
                   10714: =item *
                   10715: 
                   10716: $namespace : the name of a .db file that contains the data needed or
                   10717: being set.
                   10718: 
                   10719: =back
                   10720: 
1.394     bowersj2 10721: =head1 OVERVIEW
1.191     harris41 10722: 
1.394     bowersj2 10723: lonnet provides subroutines which interact with the
                   10724: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10725: about classes, users, and resources.
1.243     albertel 10726: 
                   10727: For many of these objects you can also use this to store data about
                   10728: them or modify them in various ways.
1.191     harris41 10729: 
1.394     bowersj2 10730: =head2 Symbs
1.191     harris41 10731: 
1.394     bowersj2 10732: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10733: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10734: map, the resource number of the resource in the map, and the URL of
                   10735: the resource itself. The latter is somewhat redundant, but might help
                   10736: if maps change.
                   10737: 
                   10738: An example is
                   10739: 
                   10740:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10741: 
                   10742: The respective map entry is
                   10743: 
                   10744:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10745:   title="Problem 2">
                   10746:  </resource>
                   10747: 
                   10748: Symbs are used by the random number generator, as well as to store and
                   10749: restore data specific to a certain instance of for example a problem.
                   10750: 
                   10751: =head2 Storing And Retrieving Data
                   10752: 
                   10753: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10754: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10755: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10756: is is the non-critical message twin of cstore. These functions are for
                   10757: handlers to store a perl hash to a user's permanent data space in an
                   10758: easy manner, and to retrieve it again on another call. It is expected
                   10759: that a handler would use this once at the beginning to retrieve data,
                   10760: and then again once at the end to send only the new data back.
                   10761: 
                   10762: The data is stored in the user's data directory on the user's
                   10763: homeserver under the ID of the course.
                   10764: 
                   10765: The hash that is returned by restore will have all of the previous
                   10766: value for all of the elements of the hash.
                   10767: 
                   10768: Example:
                   10769: 
                   10770:  #creating a hash
                   10771:  my %hash;
                   10772:  $hash{'foo'}='bar';
                   10773: 
                   10774:  #storing it
                   10775:  &Apache::lonnet::cstore(\%hash);
                   10776: 
                   10777:  #changing a value
                   10778:  $hash{'foo'}='notbar';
                   10779: 
                   10780:  #adding a new value
                   10781:  $hash{'bar'}='foo';
                   10782:  &Apache::lonnet::cstore(\%hash);
                   10783: 
                   10784:  #retrieving the hash
                   10785:  my %history=&Apache::lonnet::restore();
                   10786: 
                   10787:  #print the hash
                   10788:  foreach my $key (sort(keys(%history))) {
                   10789:    print("\%history{$key} = $history{$key}");
                   10790:  }
                   10791: 
                   10792: Will print out:
1.191     harris41 10793: 
1.394     bowersj2 10794:  %history{1:foo} = bar
                   10795:  %history{1:keys} = foo:timestamp
                   10796:  %history{1:timestamp} = 990455579
                   10797:  %history{2:bar} = foo
                   10798:  %history{2:foo} = notbar
                   10799:  %history{2:keys} = foo:bar:timestamp
                   10800:  %history{2:timestamp} = 990455580
                   10801:  %history{bar} = foo
                   10802:  %history{foo} = notbar
                   10803:  %history{timestamp} = 990455580
                   10804:  %history{version} = 2
                   10805: 
                   10806: Note that the special hash entries C<keys>, C<version> and
                   10807: C<timestamp> were added to the hash. C<version> will be equal to the
                   10808: total number of versions of the data that have been stored. The
                   10809: C<timestamp> attribute will be the UNIX time the hash was
                   10810: stored. C<keys> is available in every historical section to list which
                   10811: keys were added or changed at a specific historical revision of a
                   10812: hash.
                   10813: 
                   10814: B<Warning>: do not store the hash that restore returns directly. This
                   10815: will cause a mess since it will restore the historical keys as if the
                   10816: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10817: 
1.394     bowersj2 10818: Calling convention:
1.191     harris41 10819: 
1.394     bowersj2 10820:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10821:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10822: 
1.394     bowersj2 10823: For more detailed information, see lonnet specific documentation.
1.191     harris41 10824: 
1.394     bowersj2 10825: =head1 RETURN MESSAGES
1.191     harris41 10826: 
1.394     bowersj2 10827: =over 4
1.191     harris41 10828: 
1.394     bowersj2 10829: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10830: 
1.394     bowersj2 10831: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10832: when the connection is brought back up
1.191     harris41 10833: 
1.394     bowersj2 10834: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10835: for later delivery
1.191     harris41 10836: 
1.967     bisitz   10837: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10838: 
1.394     bowersj2 10839: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10840: that was requested
1.191     harris41 10841: 
1.243     albertel 10842: =back
1.191     harris41 10843: 
1.243     albertel 10844: =head1 PUBLIC SUBROUTINES
1.191     harris41 10845: 
1.243     albertel 10846: =head2 Session Environment Functions
1.191     harris41 10847: 
1.243     albertel 10848: =over 4
1.191     harris41 10849: 
1.394     bowersj2 10850: =item * 
                   10851: X<appenv()>
1.949     raeburn  10852: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10853: the user envirnoment file, and will be restored for each access this
1.620     albertel 10854: user makes during this session, also modifies the %env for the current
1.949     raeburn  10855: process. Optional rolesarrayref - if defined contains a reference to an array
                   10856: of roles which are exempt from the restriction on modifying user.role entries 
                   10857: in the user's environment.db and in %env.    
1.191     harris41 10858: 
                   10859: =item *
1.394     bowersj2 10860: X<delenv()>
1.987     raeburn  10861: B<delenv($delthis,$regexp)>: removes all items from the session
                   10862: environment file that begin with $delthis. If the 
                   10863: optional second arg - $regexp - is true, $delthis is treated as a 
                   10864: regular expression, otherwise \Q$delthis\E is used. 
                   10865: The values are also deleted from the current processes %env.
1.191     harris41 10866: 
1.795     albertel 10867: =item * get_env_multiple($name) 
                   10868: 
                   10869: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10870: values may be defined and end up as an array ref.
                   10871: 
                   10872: returns an array of values
                   10873: 
1.243     albertel 10874: =back
                   10875: 
                   10876: =head2 User Information
1.191     harris41 10877: 
1.243     albertel 10878: =over 4
1.191     harris41 10879: 
                   10880: =item *
1.394     bowersj2 10881: X<queryauthenticate()>
                   10882: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10883: authentication scheme
                   10884: 
                   10885: =item *
1.394     bowersj2 10886: X<authenticate()>
1.1073    raeburn  10887: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10888: authenticate user from domain's lib servers (first use the current
                   10889: one). C<$upass> should be the users password.
1.1073    raeburn  10890: $checkdefauth is optional (value is 1 if a check should be made to
                   10891:    authenticate user using default authentication method, and allow
                   10892:    account creation if username does not have account in the domain).
                   10893: $clientcancheckhost is optional (value is 1 if checking whether the
                   10894:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10895: 
                   10896: =item *
1.394     bowersj2 10897: X<homeserver()>
                   10898: B<homeserver($uname,$udom)>: find the server which has
                   10899: the user's directory and files (there must be only one), this caches
                   10900: the answer, and also caches if there is a borken connection.
1.191     harris41 10901: 
                   10902: =item *
1.394     bowersj2 10903: X<idget()>
                   10904: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10905: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10906: username, and only 1 username per ID in a specific domain) (returns
                   10907: hash: id=>name,id=>name)
1.191     harris41 10908: 
                   10909: =item *
1.394     bowersj2 10910: X<idrget()>
                   10911: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10912: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10913: 
                   10914: =item *
1.394     bowersj2 10915: X<idput()>
                   10916: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10917: 
                   10918: =item *
1.394     bowersj2 10919: X<rolesinit()>
                   10920: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10921: 
                   10922: =item *
1.551     albertel 10923: X<getsection()>
                   10924: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10925: course $cname, return section name/number or '' for "not in course"
                   10926: and '-1' for "no section"
                   10927: 
                   10928: =item *
1.394     bowersj2 10929: X<userenvironment()>
                   10930: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10931: passed in @what from the requested user's environment, returns a hash
                   10932: 
1.858     raeburn  10933: =item * 
                   10934: X<userlog_query()>
1.859     albertel 10935: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10936: activity.log file. %filters defines filters applied when parsing the
                   10937: log file. These can be start or end timestamps, or the type of action
                   10938: - log to look for Login or Logout events, check for Checkin or
                   10939: Checkout, role for role selection. The response is in the form
                   10940: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10941: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10942: 
1.243     albertel 10943: =back
                   10944: 
                   10945: =head2 User Roles
                   10946: 
                   10947: =over 4
                   10948: 
                   10949: =item *
                   10950: 
1.810     raeburn  10951: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10952:  F: full access
                   10953:  U,I,K: authentication modes (cxx only)
                   10954:  '': forbidden
                   10955:  1: user needs to choose course
                   10956:  2: browse allowed
1.766     albertel 10957:  A: passphrase authentication needed
1.243     albertel 10958: 
                   10959: =item *
                   10960: 
                   10961: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10962: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10963: and course level
                   10964: 
                   10965: =item *
                   10966: 
1.988     raeburn  10967: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10968: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10969: $type is Course (default) or Community.
1.988     raeburn  10970: If $forcedefault evaluates to true, text returned will be default 
                   10971: text for $type. Otherwise, if this is a course, the text returned 
                   10972: will be a custom name for the role (if defined in the course's 
                   10973: environment).  If no custom name is defined the default is returned.
                   10974:    
1.832     raeburn  10975: =item *
                   10976: 
1.935     raeburn  10977: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10978: All arguments are optional. Returns a hash of a roles, either for
                   10979: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10980: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10981: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10982: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10983: For each key, value is set to colon-separated start and end times for
                   10984: the role.  If no username and domain are specified, will default to
1.934     raeburn  10985: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10986: of role statuses (active, future or previous), roles 
                   10987: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10988: to restrict the list of roles reported. If no array ref is 
                   10989: provided for types, will default to return only active roles.
1.834     albertel 10990: 
1.243     albertel 10991: =back
                   10992: 
                   10993: =head2 User Modification
                   10994: 
                   10995: =over 4
                   10996: 
                   10997: =item *
                   10998: 
1.957     raeburn  10999: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11000: user for the level given by URL.  Optional start and end dates (leave empty
                   11001: string or zero for "no date")
1.191     harris41 11002: 
                   11003: =item *
                   11004: 
1.243     albertel 11005: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11006: change a users, password, possible return values are: ok,
                   11007: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11008: refused
1.191     harris41 11009: 
                   11010: =item *
                   11011: 
1.243     albertel 11012: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11013: 
                   11014: =item *
                   11015: 
1.1058    raeburn  11016: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11017:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11018: 
                   11019: will update user information (firstname,middlename,lastname,generation,
                   11020: permanentemail), and if forceid is true, student/employee ID also.
                   11021: A user's institutional affiliation(s) can also be updated.
                   11022: User information fields will not be overwritten with empty entries 
                   11023: unless the field is included in the $candelete array reference.
                   11024: This array is included when a single user is modified via "Manage Users",
                   11025: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11026: 
                   11027: =item *
                   11028: 
1.286     matthew  11029: modifystudent
                   11030: 
1.957     raeburn  11031: modify a student's enrollment and identification information.
1.286     matthew  11032: The course id is resolved based on the current users environment.  
                   11033: This means the envoking user must be a course coordinator or otherwise
                   11034: associated with a course.
                   11035: 
1.297     matthew  11036: This call is essentially a wrapper for lonnet::modifyuser and
                   11037: lonnet::modify_student_enrollment
1.286     matthew  11038: 
                   11039: Inputs: 
                   11040: 
                   11041: =over 4
                   11042: 
1.957     raeburn  11043: =item B<$udom> Student's loncapa domain
1.286     matthew  11044: 
1.957     raeburn  11045: =item B<$uname> Student's loncapa login name
1.286     matthew  11046: 
1.964     bisitz   11047: =item B<$uid> Student/Employee ID
1.286     matthew  11048: 
1.957     raeburn  11049: =item B<$umode> Student's authentication mode
1.286     matthew  11050: 
1.957     raeburn  11051: =item B<$upass> Student's password
1.286     matthew  11052: 
1.957     raeburn  11053: =item B<$first> Student's first name
1.286     matthew  11054: 
1.957     raeburn  11055: =item B<$middle> Student's middle name
1.286     matthew  11056: 
1.957     raeburn  11057: =item B<$last> Student's last name
1.286     matthew  11058: 
1.957     raeburn  11059: =item B<$gene> Student's generation
1.286     matthew  11060: 
1.957     raeburn  11061: =item B<$usec> Student's section in course
1.286     matthew  11062: 
                   11063: =item B<$end> Unix time of the roles expiration
                   11064: 
                   11065: =item B<$start> Unix time of the roles start date
                   11066: 
                   11067: =item B<$forceid> If defined, allow $uid to be changed
                   11068: 
                   11069: =item B<$desiredhome> server to use as home server for student
                   11070: 
1.957     raeburn  11071: =item B<$email> Student's permanent e-mail address
                   11072: 
                   11073: =item B<$type> Type of enrollment (auto or manual)
                   11074: 
1.963     raeburn  11075: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11076: 
                   11077: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11078: 
1.963     raeburn  11079: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11080: 
1.963     raeburn  11081: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11082: 
1.963     raeburn  11083: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11084: 
1.286     matthew  11085: =back
1.297     matthew  11086: 
                   11087: =item *
                   11088: 
                   11089: modify_student_enrollment
                   11090: 
                   11091: Change a students enrollment status in a class.  The environment variable
                   11092: 'role.request.course' must be defined for this function to proceed.
                   11093: 
                   11094: Inputs:
                   11095: 
                   11096: =over 4
                   11097: 
                   11098: =item $udom, students domain
                   11099: 
                   11100: =item $uname, students name
                   11101: 
                   11102: =item $uid, students user id
                   11103: 
                   11104: =item $first, students first name
                   11105: 
                   11106: =item $middle
                   11107: 
                   11108: =item $last
                   11109: 
                   11110: =item $gene
                   11111: 
                   11112: =item $usec
                   11113: 
                   11114: =item $end
                   11115: 
                   11116: =item $start
                   11117: 
1.957     raeburn  11118: =item $type
                   11119: 
                   11120: =item $locktype
                   11121: 
                   11122: =item $cid
                   11123: 
                   11124: =item $selfenroll
                   11125: 
                   11126: =item $context
                   11127: 
1.297     matthew  11128: =back
                   11129: 
1.191     harris41 11130: 
                   11131: =item *
                   11132: 
1.243     albertel 11133: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11134: custom role; give a custom role to a user for the level given by URL.  Specify
                   11135: name and domain of role author, and role name
1.191     harris41 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11140: 
                   11141: =item *
                   11142: 
1.243     albertel 11143: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11144: 
                   11145: =back
                   11146: 
                   11147: =head2 Course Infomation
                   11148: 
                   11149: =over 4
1.191     harris41 11150: 
                   11151: =item *
                   11152: 
1.1118    foxr     11153: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11154: specified course id, including all environment settings for the
                   11155: course, the description of the course will be in the hash under the
                   11156: key 'description'
1.191     harris41 11157: 
1.1118    foxr     11158: $options is an optional parameter that if supplied is a hash reference that controls
                   11159: what how this function works.  It has the following key/values:
                   11160: 
                   11161: =over 4
                   11162: 
                   11163: =item freshen_cache
                   11164: 
                   11165: If defined, and the environment cache for the course is valid, it is 
                   11166: returned in the returned hash.
                   11167: 
                   11168: =item one_time
                   11169: 
                   11170: If defined, the last cache time is set to _now_
                   11171: 
                   11172: =item user
                   11173: 
                   11174: If defined, the supplied username is used instead of the current user.
                   11175: 
                   11176: 
                   11177: =back
                   11178: 
1.191     harris41 11179: =item *
                   11180: 
1.624     albertel 11181: resdata($name,$domain,$type,@which) : request for current parameter
                   11182: setting for a specific $type, where $type is either 'course' or 'user',
                   11183: @what should be a list of parameters to ask about. This routine caches
                   11184: answers for 5 minutes.
1.243     albertel 11185: 
1.877     foxr     11186: =item *
                   11187: 
                   11188: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11189: data base, returning a hash that is keyed by the resource name and has
                   11190: values that are the resource value.  I believe that the timestamps and
                   11191: versions are also returned.
                   11192: 
                   11193: 
1.243     albertel 11194: =back
                   11195: 
                   11196: =head2 Course Modification
                   11197: 
                   11198: =over 4
1.191     harris41 11199: 
                   11200: =item *
                   11201: 
1.243     albertel 11202: writecoursepref($courseid,%prefs) : write preferences (environment
                   11203: database) for a course
1.191     harris41 11204: 
                   11205: =item *
                   11206: 
1.1011    raeburn  11207: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11208: 
                   11209: =item *
                   11210: 
1.1038    raeburn  11211: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11212: 
                   11213: =back
                   11214: 
                   11215: =head2 Resource Subroutines
                   11216: 
                   11217: =over 4
1.191     harris41 11218: 
                   11219: =item *
                   11220: 
1.243     albertel 11221: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11222: 
                   11223: =item *
                   11224: 
1.243     albertel 11225: repcopy($filename) : subscribes to the requested file, and attempts to
                   11226: replicate from the owning library server, Might return
1.607     raeburn  11227: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11228: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11229: resource. Expects the local filesystem pathname
                   11230: (/home/httpd/html/res/....)
                   11231: 
                   11232: =back
                   11233: 
                   11234: =head2 Resource Information
                   11235: 
                   11236: =over 4
1.191     harris41 11237: 
                   11238: =item *
                   11239: 
1.243     albertel 11240: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11241: a vairety of different possible values, $varname should be a request
                   11242: string, and the other parameters can be used to specify who and what
                   11243: one is asking about.
                   11244: 
                   11245: Possible values for $varname are environment.lastname (or other item
                   11246: from the envirnment hash), user.name (or someother aspect about the
                   11247: user), resource.0.maxtries (or some other part and parameter of a
                   11248: resource)
1.204     albertel 11249: 
                   11250: =item *
                   11251: 
1.243     albertel 11252: directcondval($number) : get current value of a condition; reads from a state
                   11253: string
1.204     albertel 11254: 
                   11255: =item *
                   11256: 
1.243     albertel 11257: condval($condidx) : value of condition index based on state
1.204     albertel 11258: 
                   11259: =item *
                   11260: 
1.243     albertel 11261: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11262: resource's metadata, $what should be either a specific key, or either
                   11263: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11264: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11265: 
                   11266: this function automatically caches all requests
1.191     harris41 11267: 
                   11268: =item *
                   11269: 
1.243     albertel 11270: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11271: network of library servers; returns file handle of where SQL and regex results
                   11272: will be stored for query
1.191     harris41 11273: 
                   11274: =item *
                   11275: 
1.243     albertel 11276: symbread($filename) : return symbolic list entry (filename argument optional);
                   11277: returns the data handle
1.191     harris41 11278: 
                   11279: =item *
                   11280: 
1.243     albertel 11281: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11282: a possible symb for the URL in $thisfn, and if is an encryypted
                   11283: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11284: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11285: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11286: 
1.191     harris41 11287: 
                   11288: =item *
                   11289: 
1.243     albertel 11290: symbclean($symb) : removes versions numbers from a symb, returns the
                   11291: cleaned symb
1.191     harris41 11292: 
                   11293: =item *
                   11294: 
1.243     albertel 11295: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11296: course map, user must be in a course for it to work.
1.191     harris41 11297: 
                   11298: =item *
                   11299: 
1.243     albertel 11300: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11301: 
                   11302: =item *
                   11303: 
1.243     albertel 11304: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11305: a random seed, all arguments are optional, if they aren't sent it uses the
                   11306: environment to derive them. Note: if symb isn't sent and it can't get one
                   11307: from &symbread it will use the current time as its return value
1.191     harris41 11308: 
                   11309: =item *
                   11310: 
1.243     albertel 11311: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11312: unfakeable, receipt
1.191     harris41 11313: 
                   11314: =item *
                   11315: 
1.620     albertel 11316: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11317: 
                   11318: =item *
                   11319: 
1.243     albertel 11320: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11321: 
                   11322: =item *
                   11323: 
1.243     albertel 11324: 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 11325: 
                   11326: =item *
                   11327: 
1.243     albertel 11328: 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 11329: 
                   11330: =item *
                   11331: 
1.243     albertel 11332: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11333: 
                   11334: =item *
                   11335: 
1.243     albertel 11336: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11337: forcing spreadsheet to reevaluate the resource scores next time.
                   11338: 
                   11339: =back
                   11340: 
                   11341: =head2 Storing/Retreiving Data
                   11342: 
                   11343: =over 4
1.191     harris41 11344: 
                   11345: =item *
                   11346: 
1.243     albertel 11347: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11348: for this url; hashref needs to be given and should be a \%hashname; the
                   11349: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11350: be derived from the env
1.191     harris41 11351: 
                   11352: =item *
                   11353: 
1.243     albertel 11354: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11355: uses critical subroutine
1.191     harris41 11356: 
                   11357: =item *
                   11358: 
1.243     albertel 11359: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11360: all args are optional
1.191     harris41 11361: 
                   11362: =item *
                   11363: 
1.717     albertel 11364: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11365: dumps the complete (or key matching regexp) namespace into a hash
                   11366: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11367: normally &store()ed into
                   11368: 
                   11369: $range should be either an integer '100' (give me the first 100
                   11370:                                            matching records)
                   11371:               or be  two integers sperated by a - with no spaces
                   11372:                  '30-50' (give me the 30th through the 50th matching
                   11373:                           records)
                   11374: 
                   11375: 
                   11376: =item *
                   11377: 
                   11378: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11379: replaces a &store() version of data with a replacement set of data
                   11380: for a particular resource in a namespace passed in the $storehash hash 
                   11381: reference
                   11382: 
                   11383: =item *
                   11384: 
1.243     albertel 11385: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11386: works very similar to store/cstore, but all data is stored in a
                   11387: temporary location and can be reset using tmpreset, $storehash should
                   11388: be a hash reference, returns nothing on success
1.191     harris41 11389: 
                   11390: =item *
                   11391: 
1.243     albertel 11392: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11393: similar to restore, but all data is stored in a temporary location and
                   11394: can be reset using tmpreset. Returns a hash of values on success,
                   11395: error string otherwise.
1.191     harris41 11396: 
                   11397: =item *
                   11398: 
1.243     albertel 11399: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11400: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11401: 
                   11402: =item *
                   11403: 
1.243     albertel 11404: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11405: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11406: 
                   11407: =item *
                   11408: 
1.243     albertel 11409: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11410: namesp ($udom and $uname are optional)
1.191     harris41 11411: 
                   11412: =item *
                   11413: 
1.702     albertel 11414: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11415: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11416: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11417: 
1.702     albertel 11418: $range should be either an integer '100' (give me the first 100
                   11419:                                            matching records)
                   11420:               or be  two integers sperated by a - with no spaces
                   11421:                  '30-50' (give me the 30th through the 50th matching
                   11422:                           records)
1.449     matthew  11423: =item *
                   11424: 
                   11425: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11426: $store can be a scalar, an array reference, or if the amount to be 
                   11427: incremented is > 1, a hash reference.
                   11428: 
                   11429: ($udom and $uname are optional)
1.191     harris41 11430: 
                   11431: =item *
                   11432: 
1.243     albertel 11433: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11434: ($udom and $uname are optional)
1.191     harris41 11435: 
                   11436: =item *
                   11437: 
1.243     albertel 11438: cput($namespace,$storehash,$udom,$uname) : critical put
                   11439: ($udom and $uname are optional)
1.191     harris41 11440: 
                   11441: =item *
                   11442: 
1.748     albertel 11443: newput($namespace,$storehash,$udom,$uname) :
                   11444: 
                   11445: Attempts to store the items in the $storehash, but only if they don't
                   11446: currently exist, if this succeeds you can be certain that you have 
                   11447: successfully created a new key value pair in the $namespace db.
                   11448: 
                   11449: 
                   11450: Args:
                   11451:  $namespace: name of database to store values to
                   11452:  $storehash: hashref to store to the db
                   11453:  $udom: (optional) domain of user containing the db
                   11454:  $uname: (optional) name of user caontaining the db
                   11455: 
                   11456: Returns:
                   11457:  'ok' -> succeeded in storing all keys of $storehash
                   11458:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11459:                         least <key> already existed in the db (other
                   11460:                         requested keys may also already exist)
1.967     bisitz   11461:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11462:  'con_lost' -> unable to contact request server
                   11463:  'refused' -> action was not allowed by remote machine
                   11464: 
                   11465: 
                   11466: =item *
                   11467: 
1.243     albertel 11468: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11469: reference filled in from namesp (encrypts the return communication)
                   11470: ($udom and $uname are optional)
1.191     harris41 11471: 
                   11472: =item *
                   11473: 
1.243     albertel 11474: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11475: critical subroutine
                   11476: 
1.806     raeburn  11477: =item *
                   11478: 
1.860     raeburn  11479: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11480: array reference filled in from namespace found in domain level on either
                   11481: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11482: 
                   11483: =item *
                   11484: 
1.860     raeburn  11485: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11486: domain level either on specified domain server ($uhome) or primary domain 
                   11487: server ($udom and $uhome are optional)
1.806     raeburn  11488: 
1.943     raeburn  11489: =item * 
                   11490: 
                   11491: get_domain_defaults($target_domain) : returns hash with defaults for
                   11492: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11493: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11494: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11495: Values are retrieved from cache (if current), or from domain's configuration.db
                   11496: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11497: or lonTabs/domain.tab. 
                   11498: 
                   11499: %domdefaults = &get_auth_defaults($target_domain);
                   11500: 
1.243     albertel 11501: =back
                   11502: 
                   11503: =head2 Network Status Functions
                   11504: 
                   11505: =over 4
1.191     harris41 11506: 
                   11507: =item *
                   11508: 
                   11509: dirlist($uri) : return directory list based on URI
                   11510: 
                   11511: =item *
                   11512: 
1.243     albertel 11513: spareserver() : find server with least workload from spare.tab
                   11514: 
1.986     foxr     11515: 
                   11516: =item *
                   11517: 
                   11518: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11519: if there is no corresponding loncapa host.
                   11520: 
1.243     albertel 11521: =back
                   11522: 
1.986     foxr     11523: 
1.243     albertel 11524: =head2 Apache Request
                   11525: 
                   11526: =over 4
1.191     harris41 11527: 
                   11528: =item *
                   11529: 
1.243     albertel 11530: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11531: localhost, posts hash
                   11532: 
                   11533: =back
                   11534: 
                   11535: =head2 Data to String to Data
                   11536: 
                   11537: =over 4
1.191     harris41 11538: 
                   11539: =item *
                   11540: 
1.243     albertel 11541: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11542: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11543: 
                   11544: =item *
                   11545: 
1.243     albertel 11546: hashref2str($hashref) : convert a hashref into a string complete with
                   11547: escaping and '=' and '&' separators, supports elements that are
                   11548: arrayrefs and hashrefs
1.191     harris41 11549: 
                   11550: =item *
                   11551: 
1.243     albertel 11552: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11553: with escaping and '&' separators, supports elements that are arrayrefs
                   11554: and hashrefs
1.191     harris41 11555: 
                   11556: =item *
                   11557: 
1.243     albertel 11558: str2hash($string) : convert string to hash using unescaping and
                   11559: splitting on '=' and '&', supports elements that are arrayrefs and
                   11560: hashrefs
1.191     harris41 11561: 
                   11562: =item *
                   11563: 
1.243     albertel 11564: str2array($string) : convert string to hash using unescaping and
                   11565: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11566: 
                   11567: =back
                   11568: 
                   11569: =head2 Logging Routines
                   11570: 
                   11571: 
                   11572: These routines allow one to make log messages in the lonnet.log and
                   11573: lonnet.perm logfiles.
1.191     harris41 11574: 
1.1119    foxr     11575: =over 4
                   11576: 
1.191     harris41 11577: =item *
                   11578: 
1.243     albertel 11579: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11580: 
                   11581: =item *
                   11582: 
1.243     albertel 11583: logthis() : append message to the normal lonnet.log file, it gets
                   11584: preiodically rolled over and deleted.
1.191     harris41 11585: 
                   11586: =item *
                   11587: 
1.243     albertel 11588: logperm() : append a permanent message to lonnet.perm.log, this log
                   11589: file never gets deleted by any automated portion of the system, only
                   11590: messages of critical importance should go in here.
                   11591: 
1.1119    foxr     11592: 
1.243     albertel 11593: =back
                   11594: 
                   11595: =head2 General File Helper Routines
                   11596: 
                   11597: =over 4
1.191     harris41 11598: 
                   11599: =item *
                   11600: 
1.481     raeburn  11601: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11602: (a) files in /uploaded
                   11603:   (i) If a local copy of the file exists - 
                   11604:       compares modification date of local copy with last-modified date for 
                   11605:       definitive version stored on home server for course. If local copy is 
                   11606:       stale, requests a new version from the home server and stores it. 
                   11607:       If the original has been removed from the home server, then local copy 
                   11608:       is unlinked.
                   11609:   (ii) If local copy does not exist -
                   11610:       requests the file from the home server and stores it. 
                   11611:   
                   11612:   If $caller is 'uploadrep':  
                   11613:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11614:     for request for files originally uploaded via DOCS. 
                   11615:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11616:   
                   11617:   Otherwise:
                   11618:      This indicates a call from the content generation phase of the request.
                   11619:      -  returns the entire contents of the file or -1.
                   11620:      
                   11621: (b) files in /res
                   11622:    - returns the entire contents of a file or -1; 
                   11623:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11624: 
1.712     albertel 11625: 
                   11626: =item *
                   11627: 
                   11628: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11629:                   reference
                   11630: 
                   11631: returns either a stat() list of data about the file or an empty list
                   11632: if the file doesn't exist or couldn't find out about it (connection
                   11633: problems or user unknown)
                   11634: 
1.191     harris41 11635: =item *
                   11636: 
1.243     albertel 11637: filelocation($dir,$file) : returns file system location of a file
                   11638: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11639: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11640: and a file of ../bob will become /a/bob)
1.191     harris41 11641: 
                   11642: =item *
                   11643: 
                   11644: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11645: filelocation except for hrefs
                   11646: 
                   11647: =item *
                   11648: 
                   11649: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11650: 
1.243     albertel 11651: =back
                   11652: 
1.608     albertel 11653: =head2 Usererfile file routines (/uploaded*)
                   11654: 
                   11655: =over 4
                   11656: 
                   11657: =item *
                   11658: 
                   11659: userfileupload(): main rotine for putting a file in a user or course's
                   11660:                   filespace, arguments are,
                   11661: 
1.620     albertel 11662:  formname - required - this is the name of the element in $env where the
1.608     albertel 11663:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11664:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11665:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11666:  context - if coursedoc, store the file in the course of the active role
                   11667:              of the current user; 
                   11668:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11669:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11670:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11671:          if undefined, it will be placed in "unknown"
                   11672: 
                   11673:  (This routine calls clean_filename() to remove any dangerous
                   11674:  characters from the filename, and then calls finuserfileupload() to
                   11675:  complete the transaction)
                   11676: 
                   11677:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11678:  and /adm/notfound.html if unsuccessful
                   11679: 
                   11680: =item *
                   11681: 
                   11682: clean_filename(): routine for cleaing a filename up for storage in
                   11683:                  userfile space, argument is:
                   11684: 
                   11685:  filename - proposed filename
                   11686: 
                   11687: returns: the new clean filename
                   11688: 
                   11689: =item *
                   11690: 
1.1090    raeburn  11691: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11692: userspace, probably shouldn't be called directly
                   11693: 
                   11694:   docuname: username or courseid of destination for the file
                   11695:   docudom: domain of user/course of destination for the file
                   11696:   formname: same as for userfileupload()
1.1090    raeburn  11697:   fname: filename (including subdirectories) for the file
                   11698:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11699:   allfiles: reference to hash used to store objects found by parser
                   11700:   codebase: reference to hash used for codebases of java objects found by parser
                   11701:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11702:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11703:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11704:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11705:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11706:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11707:   mimetype: reference to scalar to accommodate mime type determined
                   11708:             from File::MMagic if $parser = parse.
1.608     albertel 11709: 
                   11710:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11711:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11712:  was 'overwrite').
                   11713:  
1.608     albertel 11714: 
                   11715: =item *
                   11716: 
                   11717: renameuserfile(): renames an existing userfile to a new name
                   11718: 
                   11719:   Args:
                   11720:    docuname: username or courseid of destination for the file
                   11721:    docudom: domain of user/course of destination for the file
                   11722:    old: current file name (including any subdirs under userfiles)
                   11723:    new: desired file name (including any subdirs under userfiles)
                   11724: 
                   11725: =item *
                   11726: 
                   11727: mkdiruserfile(): creates a directory is a userfiles dir
                   11728: 
                   11729:   Args:
                   11730:    docuname: username or courseid of destination for the file
                   11731:    docudom: domain of user/course of destination for the file
                   11732:    dir: dir to create (including any subdirs under userfiles)
                   11733: 
                   11734: =item *
                   11735: 
                   11736: removeuserfile(): removes a file that exists in userfiles
                   11737: 
                   11738:   Args:
                   11739:    docuname: username or courseid of destination for the file
                   11740:    docudom: domain of user/course of destination for the file
                   11741:    fname: filname to delete (including any subdirs under userfiles)
                   11742: 
                   11743: =item *
                   11744: 
                   11745: removeuploadedurl(): convience function for removeuserfile()
                   11746: 
                   11747:   Args:
                   11748:    url:  a full /uploaded/... url to delete
                   11749: 
1.747     albertel 11750: =item * 
                   11751: 
                   11752: get_portfile_permissions():
                   11753:   Args:
                   11754:     domain: domain of user or course contain the portfolio files
                   11755:     user: name of user or num of course contain the portfolio files
                   11756:   Returns:
                   11757:     hashref of a dump of the proper file_permissions.db
                   11758:    
                   11759: 
                   11760: =item * 
                   11761: 
                   11762: get_access_controls():
                   11763: 
                   11764: Args:
                   11765:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11766:   group: (optional) the group you want the files associated with
                   11767:   file: (optional) the file you want access info on
                   11768: 
                   11769: Returns:
1.749     raeburn  11770:     a hash (keys are file names) of hashes containing
                   11771:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11772:         values are XML containing access control settings (see below) 
1.747     albertel 11773: 
                   11774: Internal notes:
                   11775: 
1.749     raeburn  11776:  access controls are stored in file_permissions.db as key=value pairs.
                   11777:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11778:         where scope -> public,guest,course,group,domains or users.
                   11779:               end -> UNIX time for end of access (0 -> no end date)
                   11780:               start -> UNIX time for start of access
                   11781: 
                   11782:     value -> XML description of access control
                   11783:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11784:             <start></start>
                   11785:             <end></end>
                   11786: 
                   11787:             <password></password>  for scope type = guest
                   11788: 
                   11789:             <domain></domain>     for scope type = course or group
                   11790:             <number></number>
                   11791:             <roles id="">
                   11792:              <role></role>
                   11793:              <access></access>
                   11794:              <section></section>
                   11795:              <group></group>
                   11796:             </roles>
                   11797: 
                   11798:             <dom></dom>         for scope type = domains
                   11799: 
                   11800:             <users>             for scope type = users
                   11801:              <user>
                   11802:               <uname></uname>
                   11803:               <udom></udom>
                   11804:              </user>
                   11805:             </users>
                   11806:            </scope> 
                   11807:               
                   11808:  Access data is also aggregated for each file in an additional key=value pair:
                   11809:  key -> path to file/file_name\0accesscontrol 
                   11810:  value -> reference to hash
                   11811:           hash contains key = value pairs
                   11812:           where key = uniqueID:scope_end_start
                   11813:                 value = UNIX time record was last updated
                   11814: 
                   11815:           Used to improve speed of look-ups of access controls for each file.  
                   11816:  
                   11817:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11818: 
                   11819: modify_access_controls():
                   11820: 
                   11821: Modifies access controls for a portfolio file
                   11822: Args
                   11823: 1. file name
                   11824: 2. reference to hash of required changes,
                   11825: 3. domain
                   11826: 4. username
                   11827:   where domain,username are the domain of the portfolio owner 
                   11828:   (either a user or a course) 
                   11829: 
                   11830: Returns:
                   11831: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11832: 2. result of deletions ('ok' or 'error', with error message).
                   11833: 3. reference to hash of any new or updated access controls.
                   11834: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11835:    key = integer (inbound ID)
                   11836:    value = uniqueID  
1.747     albertel 11837: 
1.608     albertel 11838: =back
                   11839: 
1.243     albertel 11840: =head2 HTTP Helper Routines
                   11841: 
                   11842: =over 4
                   11843: 
1.191     harris41 11844: =item *
                   11845: 
                   11846: escape() : unpack non-word characters into CGI-compatible hex codes
                   11847: 
                   11848: =item *
                   11849: 
                   11850: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11851: 
1.243     albertel 11852: =back
                   11853: 
                   11854: =head1 PRIVATE SUBROUTINES
                   11855: 
                   11856: =head2 Underlying communication routines (Shouldn't call)
                   11857: 
                   11858: =over 4
                   11859: 
                   11860: =item *
                   11861: 
                   11862: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11863: 
                   11864: =item *
                   11865: 
                   11866: reply() : uses subreply to send a message to remote machine, logs all failures
                   11867: 
                   11868: =item *
                   11869: 
                   11870: critical() : passes a critical message to another server; if cannot
                   11871: get through then place message in connection buffer directory and
                   11872: returns con_delayed, if incapable of saving message, returns
                   11873: con_failed
                   11874: 
                   11875: =item *
                   11876: 
                   11877: reconlonc() : tries to reconnect lonc client processes.
                   11878: 
                   11879: =back
                   11880: 
                   11881: =head2 Resource Access Logging
                   11882: 
                   11883: =over 4
                   11884: 
                   11885: =item *
                   11886: 
                   11887: flushcourselogs() : flush (save) buffer logs and access logs
                   11888: 
                   11889: =item *
                   11890: 
                   11891: courselog($what) : save message for course in hash
                   11892: 
                   11893: =item *
                   11894: 
                   11895: courseacclog($what) : save message for course using &courselog().  Perform
                   11896: special processing for specific resource types (problems, exams, quizzes, etc).
                   11897: 
1.191     harris41 11898: =item *
                   11899: 
                   11900: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11901: as a PerlChildExitHandler
1.243     albertel 11902: 
                   11903: =back
                   11904: 
                   11905: =head2 Other
                   11906: 
                   11907: =over 4
                   11908: 
                   11909: =item *
                   11910: 
                   11911: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11912: 
                   11913: =back
                   11914: 
                   11915: =cut
1.877     foxr     11916: 

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