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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1120  ! raeburn     4: # $Id: lonnet.pm,v 1.1119 2011/07/18 10:32:48 foxr 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.1       albertel  309: # -------------------------------------------------- Non-critical communication
                    310: sub subreply {
                    311:     my ($cmd,$server)=@_;
1.838     albertel  312:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      313:     #
                    314:     #  With loncnew process trimming, there's a timing hole between lonc server
                    315:     #  process exit and the master server picking up the listen on the AF_UNIX
                    316:     #  socket.  In that time interval, a lock file will exist:
                    317: 
                    318:     my $lockfile=$peerfile.".lock";
                    319:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    320: 	sleep(1);
                    321:     }
                    322:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      323:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      324:     #
1.550     foxr      325:     #   We'll give the connection a few tries before abandoning it.  If
                    326:     #   connection is not possible, we'll con_lost back to the client.
                    327:     #   
                    328:     my $client;
                    329:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    330: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    331: 				      Type    => SOCK_STREAM,
                    332: 				      Timeout => 10);
1.869     albertel  333: 	if ($client) {
1.550     foxr      334: 	    last;		# Connected!
1.850     albertel  335: 	} else {
1.853     albertel  336: 	    &create_connection(&hostname($server),$server);
1.550     foxr      337: 	}
1.850     albertel  338:         sleep(1);		# Try again later if failed connection.
1.550     foxr      339:     }
                    340:     my $answer;
                    341:     if ($client) {
1.704     albertel  342: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      343: 	$answer=<$client>;
                    344: 	if (!$answer) { $answer="con_lost"; }
                    345: 	chomp($answer);
                    346:     } else {
                    347: 	$answer = 'con_lost';	# Failed connection.
                    348:     }
1.1       albertel  349:     return $answer;
                    350: }
                    351: 
                    352: sub reply {
                    353:     my ($cmd,$server)=@_;
1.838     albertel  354:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  355:     my $answer=subreply($cmd,$server);
1.65      www       356:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  357:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       358:                 " $cmd to $server returned $answer</font>");
                    359:     }
1.1       albertel  360:     return $answer;
                    361: }
                    362: 
                    363: # ----------------------------------------------------------- Send USR1 to lonc
                    364: 
                    365: sub reconlonc {
1.891     albertel  366:     my ($lonid) = @_;
                    367:     my $hostname = &hostname($lonid);
                    368:     if ($lonid) {
                    369: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    370: 	if ($hostname && -e $peerfile) {
                    371: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    372: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    373: 					     Type    => SOCK_STREAM,
                    374: 					     Timeout => 10);
                    375: 	    if ($client) {
                    376: 		print $client ("reset_retries\n");
                    377: 		my $answer=<$client>;
                    378: 		#reset just this one.
                    379: 	    }
                    380: 	}
                    381: 	return;
                    382:     }
                    383: 
1.836     www       384:     &logthis("Trying to reconnect lonc");
1.1       albertel  385:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  386:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  387: 	my $loncpid=<$fh>;
                    388:         chomp($loncpid);
                    389:         if (kill 0 => $loncpid) {
                    390: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    391:             kill USR1 => $loncpid;
                    392:             sleep 1;
1.836     www       393:          } else {
1.12      www       394: 	    &logthis(
1.672     albertel  395:                "<font color=\"blue\">WARNING:".
1.12      www       396:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  397:         }
                    398:     } else {
1.836     www       399: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  400:     }
                    401: }
                    402: 
                    403: # ------------------------------------------------------ Critical communication
1.12      www       404: 
1.1       albertel  405: sub critical {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (&hostname($server)) {
1.672     albertel  408:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       409:                " Critical message to unknown server ($server)</font>");
                    410:         return 'no_such_host';
                    411:     }
1.1       albertel  412:     my $answer=reply($cmd,$server);
                    413:     if ($answer eq 'con_lost') {
                    414: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  415: 	my $answer=reply($cmd,$server);
1.1       albertel  416:         if ($answer eq 'con_lost') {
                    417:             my $now=time;
                    418:             my $middlename=$cmd;
1.5       www       419:             $middlename=substr($middlename,0,16);
1.1       albertel  420:             $middlename=~s/\W//g;
                    421:             my $dfilename=
1.305     www       422:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    423:             $dumpcount++;
1.1       albertel  424:             {
1.448     albertel  425: 		my $dfh;
                    426: 		if (open($dfh,">$dfilename")) {
                    427: 		    print $dfh "$cmd\n"; 
                    428: 		    close($dfh);
                    429: 		}
1.1       albertel  430:             }
                    431:             sleep 2;
                    432:             my $wcmd='';
                    433:             {
1.448     albertel  434: 		my $dfh;
                    435: 		if (open($dfh,"<$dfilename")) {
                    436: 		    $wcmd=<$dfh>; 
                    437: 		    close($dfh);
                    438: 		}
1.1       albertel  439:             }
                    440:             chomp($wcmd);
1.7       www       441:             if ($wcmd eq $cmd) {
1.672     albertel  442: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       443:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  444:                 &logperm("D:$server:$cmd");
                    445: 	        return 'con_delayed';
                    446:             } else {
1.672     albertel  447:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       448:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  449:                 &logperm("F:$server:$cmd");
                    450:                 return 'con_failed';
                    451:             }
                    452:         }
                    453:     }
                    454:     return $answer;
1.405     albertel  455: }
                    456: 
1.755     albertel  457: # ------------------------------------------- check if return value is an error
                    458: 
                    459: sub error {
                    460:     my ($result) = @_;
1.756     albertel  461:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  462: 	if ($2 == 2) { return undef; }
                    463: 	return $1;
                    464:     }
                    465:     return undef;
                    466: }
                    467: 
1.783     albertel  468: sub convert_and_load_session_env {
                    469:     my ($lonidsdir,$handle)=@_;
                    470:     my @profile;
                    471:     {
1.917     albertel  472: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    473: 	if (!$opened) {
1.915     albertel  474: 	    return 0;
                    475: 	}
1.783     albertel  476: 	flock($idf,LOCK_SH);
                    477: 	@profile=<$idf>;
                    478: 	close($idf);
                    479:     }
                    480:     my %temp_env;
                    481:     foreach my $line (@profile) {
1.786     albertel  482: 	if ($line !~ m/=/) {
                    483: 	    return 0;
                    484: 	}
1.783     albertel  485: 	chomp($line);
                    486: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    487: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    488:     }
                    489:     unlink("$lonidsdir/$handle.id");
                    490:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    491: 	    0640)) {
                    492: 	%disk_env = %temp_env;
                    493: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    494: 	untie(%disk_env);
                    495:     }
1.786     albertel  496:     return 1;
1.783     albertel  497: }
                    498: 
1.374     www       499: # ------------------------------------------- Transfer profile into environment
1.780     albertel  500: my $env_loaded;
                    501: sub transfer_profile_to_env {
1.788     albertel  502:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    503:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       504: 
1.720     albertel  505:     if (!defined($lonidsdir)) {
                    506: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    507:     }
                    508:     if (!defined($handle)) {
                    509:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    510:     }
                    511: 
1.786     albertel  512:     my $convert;
                    513:     {
1.917     albertel  514:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    515: 	if (!$opened) {
1.915     albertel  516: 	    return;
                    517: 	}
1.786     albertel  518: 	flock($idf,LOCK_SH);
                    519: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    520: 		&GDBM_READER(),0640)) {
                    521: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    522: 	    untie(%disk_env);
                    523: 	} else {
                    524: 	    $convert = 1;
                    525: 	}
                    526:     }
                    527:     if ($convert) {
                    528: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    529: 	    &logthis("Failed to load session, or convert session.");
                    530: 	}
1.374     www       531:     }
1.783     albertel  532: 
1.786     albertel  533:     my %remove;
1.783     albertel  534:     while ( my $envname = each(%env) ) {
1.433     matthew   535:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    536:             if ($time < time-300) {
1.783     albertel  537:                 $remove{$key}++;
1.433     matthew   538:             }
                    539:         }
                    540:     }
1.783     albertel  541: 
1.619     albertel  542:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  543:     $env_loaded=1;
1.783     albertel  544:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   545:         &delenv($expired_key);
1.374     www       546:     }
1.1       albertel  547: }
                    548: 
1.916     albertel  549: # ---------------------------------------------------- Check for valid session 
                    550: sub check_for_valid_session {
                    551:     my ($r) = @_;
                    552:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    553:     my $lonid=$cookies{'lonID'};
                    554:     return undef if (!$lonid);
                    555: 
                    556:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    557:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    558:     return undef if (!-e "$lonidsdir/$handle.id");
                    559: 
1.917     albertel  560:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561:     return undef if (!$opened);
1.916     albertel  562: 
                    563:     flock($idf,LOCK_SH);
                    564:     my %disk_env;
                    565:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 	    &GDBM_READER(),0640)) {
                    567: 	return undef;	
                    568:     }
                    569: 
                    570:     if (!defined($disk_env{'user.name'})
                    571: 	|| !defined($disk_env{'user.domain'})) {
                    572: 	return undef;
                    573:     }
                    574:     return $handle;
                    575: }
                    576: 
1.830     albertel  577: sub timed_flock {
                    578:     my ($file,$lock_type) = @_;
                    579:     my $failed=0;
                    580:     eval {
                    581: 	local $SIG{__DIE__}='DEFAULT';
                    582: 	local $SIG{ALRM}=sub {
                    583: 	    $failed=1;
                    584: 	    die("failed lock");
                    585: 	};
                    586: 	alarm(13);
                    587: 	flock($file,$lock_type);
                    588: 	alarm(0);
                    589:     };
                    590:     if ($failed) {
                    591: 	return undef;
                    592:     } else {
                    593: 	return 1;
                    594:     }
                    595: }
                    596: 
1.5       www       597: # ---------------------------------------------------------- Append Environment
                    598: 
                    599: sub appenv {
1.949     raeburn   600:     my ($newenv,$roles) = @_;
                    601:     if (ref($newenv) eq 'HASH') {
                    602:         foreach my $key (keys(%{$newenv})) {
                    603:             my $refused = 0;
                    604: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    605:                 $refused = 1;
                    606:                 if (ref($roles) eq 'ARRAY') {
                    607:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    608:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    609:                         $refused = 0;
                    610:                     }
                    611:                 }
                    612:             }
                    613:             if ($refused) {
                    614:                 &logthis("<font color=\"blue\">WARNING: ".
                    615:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    616:                          .'</font>');
                    617: 	        delete($newenv->{$key});
                    618:             } else {
                    619:                 $env{$key}=$newenv->{$key};
                    620:             }
                    621:         }
                    622:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    623:         if ($opened
                    624: 	    && &timed_flock($env_file,LOCK_EX)
                    625: 	    &&
                    626: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    627: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    628: 	    while (my ($key,$value) = each(%{$newenv})) {
                    629: 	        $disk_env{$key} = $value;
                    630: 	    }
                    631: 	    untie(%disk_env);
1.35      www       632:         }
1.191     harris41  633:     }
1.56      www       634:     return 'ok';
                    635: }
                    636: # ----------------------------------------------------- Delete from Environment
                    637: 
                    638: sub delenv {
1.1104    raeburn   639:     my ($delthis,$regexp,$roles) = @_;
                    640:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    641:         my $refused = 1;
                    642:         if (ref($roles) eq 'ARRAY') {
                    643:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    644:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    645:                 $refused = 0;
                    646:             }
                    647:         }
                    648:         if ($refused) {
                    649:             &logthis("<font color=\"blue\">WARNING: ".
                    650:                      "Attempt to delete from environment ".$delthis);
                    651:             return 'error';
                    652:         }
1.56      www       653:     }
1.917     albertel  654:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    655:     if ($opened
1.915     albertel  656: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  657: 	&&
                    658: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    659: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  660: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   661: 	    if ($regexp) {
                    662:                 if ($key=~/^$delthis/) {
                    663:                     delete($env{$key});
                    664:                     delete($disk_env{$key});
                    665:                 } 
                    666:             } else {
                    667:                 if ($key=~/^\Q$delthis\E/) {
                    668: 		    delete($env{$key});
                    669: 		    delete($disk_env{$key});
                    670: 	        }
                    671:             }
1.448     albertel  672: 	}
1.783     albertel  673: 	untie(%disk_env);
1.5       www       674:     }
                    675:     return 'ok';
1.369     albertel  676: }
                    677: 
1.790     albertel  678: sub get_env_multiple {
                    679:     my ($name) = @_;
                    680:     my @values;
                    681:     if (defined($env{$name})) {
                    682:         # exists is it an array
                    683:         if (ref($env{$name})) {
                    684:             @values=@{ $env{$name} };
                    685:         } else {
                    686:             $values[0]=$env{$name};
                    687:         }
                    688:     }
                    689:     return(@values);
                    690: }
                    691: 
1.958     www       692: # ------------------------------------------------------------------- Locking
                    693: 
                    694: sub set_lock {
                    695:     my ($text)=@_;
                    696:     $locknum++;
                    697:     my $id=$$.'-'.$locknum;
                    698:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    699:              'session.lock.'.$id => $text});
                    700:     return $id;
                    701: }
                    702: 
                    703: sub get_locks {
                    704:     my $num=0;
                    705:     my %texts=();
                    706:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    707:        if ($lock=~/\w/) {
                    708:           $num++;
                    709:           $texts{$lock}=$env{'session.lock.'.$lock};
                    710:        }
                    711:    }
                    712:    return ($num,%texts);
                    713: }
                    714: 
                    715: sub remove_lock {
                    716:     my ($id)=@_;
                    717:     my $newlocks='';
                    718:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    719:        if (($lock=~/\w/) && ($lock ne $id)) {
                    720:           $newlocks.=','.$lock;
                    721:        }
                    722:     }
                    723:     &appenv({'session.locks' => $newlocks});
                    724:     &delenv('session.lock.'.$id);
                    725: }
                    726: 
                    727: sub remove_all_locks {
                    728:     my $activelocks=$env{'session.locks'};
                    729:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    730:        if ($lock=~/\w/) {
                    731:           &remove_lock($lock);
                    732:        }
                    733:     }
                    734: }
                    735: 
                    736: 
1.369     albertel  737: # ------------------------------------------ Find out current server userload
                    738: sub userload {
                    739:     my $numusers=0;
                    740:     {
                    741: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    742: 	my $filename;
                    743: 	my $curtime=time;
                    744: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  745: 	    next if ($filename eq '.' || $filename eq '..');
                    746: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  747: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  748: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  749: 	}
                    750: 	closedir(LONIDS);
                    751:     }
                    752:     my $userloadpercent=0;
                    753:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    754:     if ($maxuserload) {
1.371     albertel  755: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  756:     }
1.372     albertel  757:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  758:     return $userloadpercent;
1.283     www       759: }
                    760: 
1.1       albertel  761: # ------------------------------ Find server with least workload from spare.tab
1.11      www       762: 
1.1       albertel  763: sub spareserver {
1.1083    raeburn   764:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  765:     my $spare_server;
1.370     albertel  766:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  767:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    768:                                                      :  $userloadpercent;
1.1083    raeburn   769:     my ($uint_dom,$remotesessions);
                    770:     if (($udom ne '') && (&domain($udom) ne '')) {
                    771:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    772:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    773:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    774:         $remotesessions = $udomdefaults{'remotesessions'};
                    775:     }
1.784     albertel  776:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   777:         if ($uint_dom) {
                    778:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    779:                                           $try_server));
                    780:         }
1.784     albertel  781: 	($spare_server, $lowest_load) =
                    782: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    783:     }
                    784: 
                    785:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    786: 
                    787:     if (!$found_server) {
                    788: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   789:             if ($uint_dom) {
                    790:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    791:                                              $try_server));
                    792:             }
1.784     albertel  793: 	    ($spare_server, $lowest_load) =
                    794: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    795: 	}
                    796:     }
                    797: 
                    798:     if (!$want_server_name) {
1.968     raeburn   799:         my $protocol = 'http';
                    800:         if ($protocol{$spare_server} eq 'https') {
                    801:             $protocol = $protocol{$spare_server};
                    802:         }
1.1001    raeburn   803:         if (defined($spare_server)) {
                    804:             my $hostname = &hostname($spare_server);
1.1083    raeburn   805:             if (defined($hostname)) {
1.1001    raeburn   806: 	        $spare_server = $protocol.'://'.$hostname;
                    807:             }
                    808:         }
1.784     albertel  809:     }
                    810:     return $spare_server;
                    811: }
                    812: 
                    813: sub compare_server_load {
                    814:     my ($try_server, $spare_server, $lowest_load) = @_;
                    815: 
                    816:     my $loadans     = &reply('load',    $try_server);
                    817:     my $userloadans = &reply('userload',$try_server);
                    818: 
                    819:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   820: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  821:     }
                    822: 
                    823:     my $load;
                    824:     if ($loadans =~ /\d/) {
                    825: 	if ($userloadans =~ /\d/) {
                    826: 	    #both are numbers, pick the bigger one
                    827: 	    $load = ($loadans > $userloadans) ? $loadans 
                    828: 		                              : $userloadans;
1.411     albertel  829: 	} else {
1.784     albertel  830: 	    $load = $loadans;
1.411     albertel  831: 	}
1.784     albertel  832:     } else {
                    833: 	$load = $userloadans;
                    834:     }
                    835: 
                    836:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    837: 	$spare_server = $try_server;
                    838: 	$lowest_load  = $load;
1.370     albertel  839:     }
1.784     albertel  840:     return ($spare_server,$lowest_load);
1.202     matthew   841: }
1.914     albertel  842: 
                    843: # --------------------------- ask offload servers if user already has a session
                    844: sub find_existing_session {
                    845:     my ($udom,$uname) = @_;
                    846:     foreach my $try_server (@{ $spareid{'primary'} },
                    847: 			    @{ $spareid{'default'} }) {
                    848: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    849:     }
                    850:     return;
                    851: }
                    852: 
                    853: # -------------------------------- ask if server already has a session for user
                    854: sub has_user_session {
                    855:     my ($lonid,$udom,$uname) = @_;
                    856:     my $result = &reply(join(':','userhassession',
                    857: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    858:     return 1 if ($result eq 'ok');
                    859: 
                    860:     return 0;
                    861: }
                    862: 
1.1076    raeburn   863: # --------- determine least loaded server in a user's domain which allows login
                    864: 
                    865: sub choose_server {
1.1115    raeburn   866:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   867:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   868:     my %servers = &get_servers($udom);
1.1076    raeburn   869:     my $lowest_load = 30000;
1.1116    raeburn   870:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   871:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   872:         my $loginvia;
                    873:         if ($checkloginvia) {
                    874:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   875:             if ($loginvia) {
                    876:                 my ($server,$path) = split(/:/,$loginvia);
                    877:                 ($login_host, $lowest_load) =
                    878:                     &compare_server_load($server, $login_host, $lowest_load);
                    879:                 if ($login_host eq $server) {
                    880:                     $portal_path = $path;
                    881:                 }
                    882:             } else {
                    883:                 ($login_host, $lowest_load) =
                    884:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    885:                 if ($login_host eq $lonhost) {
                    886:                     $portal_path = '';
                    887:                 }
                    888:             }
                    889:         } else {
1.1076    raeburn   890:             ($login_host, $lowest_load) =
1.1116    raeburn   891:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   892:         }
                    893:     }
                    894:     if ($login_host ne '') {
1.1116    raeburn   895:         $hostname = &hostname($login_host);
1.1076    raeburn   896:     }
1.1116    raeburn   897:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   898: }
                    899: 
1.202     matthew   900: # --------------------------------------------- Try to change a user's password
                    901: 
                    902: sub changepass {
1.799     raeburn   903:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   904:     $currentpass = &escape($currentpass);
                    905:     $newpass     = &escape($newpass);
1.1030    raeburn   906:     my $lonhost = $perlvar{'lonHostID'};
                    907:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   908: 		       $server);
                    909:     if (! $answer) {
                    910: 	&logthis("No reply on password change request to $server ".
                    911: 		 "by $uname in domain $udom.");
                    912:     } elsif ($answer =~ "^ok") {
                    913:         &logthis("$uname in $udom successfully changed their password ".
                    914: 		 "on $server.");
                    915:     } elsif ($answer =~ "^pwchange_failure") {
                    916: 	&logthis("$uname in $udom was unable to change their password ".
                    917: 		 "on $server.  The action was blocked by either lcpasswd ".
                    918: 		 "or pwchange");
                    919:     } elsif ($answer =~ "^non_authorized") {
                    920:         &logthis("$uname in $udom did not get their password correct when ".
                    921: 		 "attempting to change it on $server.");
                    922:     } elsif ($answer =~ "^auth_mode_error") {
                    923:         &logthis("$uname in $udom attempted to change their password despite ".
                    924: 		 "not being locally or internally authenticated on $server.");
                    925:     } elsif ($answer =~ "^unknown_user") {
                    926:         &logthis("$uname in $udom attempted to change their password ".
                    927: 		 "on $server but were unable to because $server is not ".
                    928: 		 "their home server.");
                    929:     } elsif ($answer =~ "^refused") {
                    930: 	&logthis("$server refused to change $uname in $udom password because ".
                    931: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   932:     } elsif ($answer =~ "invalid_client") {
                    933:         &logthis("$server refused to change $uname in $udom password because ".
                    934:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   935:     }
                    936:     return $answer;
1.1       albertel  937: }
                    938: 
1.169     harris41  939: # ----------------------- Try to determine user's current authentication scheme
                    940: 
                    941: sub queryauthenticate {
                    942:     my ($uname,$udom)=@_;
1.456     albertel  943:     my $uhome=&homeserver($uname,$udom);
                    944:     if (!$uhome) {
                    945: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    946: 	return 'no_host';
                    947:     }
                    948:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    949:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    950: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  951:     }
1.456     albertel  952:     return $answer;
1.169     harris41  953: }
                    954: 
1.1       albertel  955: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       956: 
1.1       albertel  957: sub authenticate {
1.1073    raeburn   958:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  959:     $upass=&escape($upass);
                    960:     $uname= &LONCAPA::clean_username($uname);
1.836     www       961:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   962:     my $newhome;
1.836     www       963:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    964: # Maybe the machine was offline and only re-appeared again recently?
                    965:         &reconlonc();
                    966: # One more
1.952     raeburn   967: 	$uhome=&homeserver($uname,$udom,1);
                    968:         if (($uhome eq 'no_host') && $checkdefauth) {
                    969:             if (defined(&domain($udom,'primary'))) {
                    970:                 $newhome=&domain($udom,'primary');
                    971:             }
                    972:             if ($newhome ne '') {
                    973:                 $uhome = $newhome;
                    974:             }
                    975:         }
1.836     www       976: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    977: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   978: 	    return 'no_host';
                    979:         }
1.1       albertel  980:     }
1.1073    raeburn   981:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  982:     if ($answer eq 'authorized') {
1.952     raeburn   983:         if ($newhome) {
                    984:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    985:             return 'no_account_on_host'; 
                    986:         } else {
                    987:             &logthis("User $uname at $udom authorized by $uhome");
                    988:             return $uhome;
                    989:         }
1.471     albertel  990:     }
                    991:     if ($answer eq 'non_authorized') {
                    992: 	&logthis("User $uname at $udom rejected by $uhome");
                    993: 	return 'no_host'; 
1.9       www       994:     }
1.471     albertel  995:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  996:     return 'no_host';
                    997: }
                    998: 
1.1073    raeburn   999: sub can_host_session {
1.1074    raeburn  1000:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1001:     my $canhost = 1;
1.1074    raeburn  1002:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1003:     if (ref($remotesessions) eq 'HASH') {
                   1004:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1005:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1006:                 $canhost = 0;
                   1007:             } else {
                   1008:                 $canhost = 1;
                   1009:             }
                   1010:         }
                   1011:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1012:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1013:                 $canhost = 1;
                   1014:             } else {
                   1015:                 $canhost = 0;
                   1016:             }
                   1017:         }
                   1018:         if ($canhost) {
                   1019:             if ($remotesessions->{'version'} ne '') {
                   1020:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1021:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1022:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1023:                         my $major = $1;
                   1024:                         my $minor = $2;
                   1025:                         if (($major < $reqmajor ) ||
                   1026:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1027:                             $canhost = 0;
                   1028:                         }
                   1029:                     } else {
                   1030:                         $canhost = 0;
                   1031:                     }
                   1032:                 }
                   1033:             }
                   1034:         }
                   1035:     }
                   1036:     if ($canhost) {
                   1037:         if (ref($hostedsessions) eq 'HASH') {
1.1120  ! raeburn  1038:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
        !          1039:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1040:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120  ! raeburn  1041:                 if (($uint_dom ne '') && 
        !          1042:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1043:                     $canhost = 0;
                   1044:                 } else {
                   1045:                     $canhost = 1;
                   1046:                 }
                   1047:             }
                   1048:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120  ! raeburn  1049:                 if (($uint_dom ne '') && 
        !          1050:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1051:                     $canhost = 1;
                   1052:                 } else {
                   1053:                     $canhost = 0;
                   1054:                 }
                   1055:             }
                   1056:         }
                   1057:     }
                   1058:     return $canhost;
                   1059: }
                   1060: 
1.1083    raeburn  1061: sub spare_can_host {
                   1062:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1063:     my $canhost=1;
                   1064:     my @intdoms;
                   1065:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1066:     if (ref($internet_names) eq 'ARRAY') {
                   1067:         @intdoms = @{$internet_names};
                   1068:     }
                   1069:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1070:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1071:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1072:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1073:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1074:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1075:                                      $remotesessions,
                   1076:                                      $defdomdefaults{'hostedsessions'});
                   1077:     }
                   1078:     return $canhost;
                   1079: }
                   1080: 
1.1       albertel 1081: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1082: 
1.599     albertel 1083: my %homecache;
1.1       albertel 1084: sub homeserver {
1.230     stredwic 1085:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1086:     my $index="$uname:$udom";
1.426     albertel 1087: 
1.599     albertel 1088:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1089: 
                   1090:     my %servers = &get_servers($udom,'library');
                   1091:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1092:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1093: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1094: 
                   1095: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1096: 	if ($answer eq 'found') {
                   1097: 	    delete($badServerCache{$tryserver}); 
                   1098: 	    return $homecache{$index}=$tryserver;
                   1099: 	} elsif ($answer eq 'no_host') {
                   1100: 	    $badServerCache{$tryserver}=1;
                   1101: 	}
1.1       albertel 1102:     }    
                   1103:     return 'no_host';
1.70      www      1104: }
                   1105: 
                   1106: # ------------------------------------- Find the usernames behind a list of IDs
                   1107: 
                   1108: sub idget {
                   1109:     my ($udom,@ids)=@_;
                   1110:     my %returnhash=();
                   1111:     
1.841     albertel 1112:     my %servers = &get_servers($udom,'library');
                   1113:     foreach my $tryserver (keys(%servers)) {
                   1114: 	my $idlist=join('&',@ids);
                   1115: 	$idlist=~tr/A-Z/a-z/; 
                   1116: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1117: 	my @answer=();
                   1118: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1119: 	    @answer=split(/\&/,$reply);
                   1120: 	}                    ;
                   1121: 	my $i;
                   1122: 	for ($i=0;$i<=$#ids;$i++) {
                   1123: 	    if ($answer[$i]) {
                   1124: 		$returnhash{$ids[$i]}=$answer[$i];
                   1125: 	    } 
                   1126: 	}
                   1127:     } 
1.70      www      1128:     return %returnhash;
                   1129: }
                   1130: 
                   1131: # ------------------------------------- Find the IDs behind a list of usernames
                   1132: 
                   1133: sub idrget {
                   1134:     my ($udom,@unames)=@_;
                   1135:     my %returnhash=();
1.800     albertel 1136:     foreach my $uname (@unames) {
                   1137:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1138:     }
1.70      www      1139:     return %returnhash;
                   1140: }
                   1141: 
                   1142: # ------------------------------- Store away a list of names and associated IDs
                   1143: 
                   1144: sub idput {
                   1145:     my ($udom,%ids)=@_;
                   1146:     my %servers=();
1.800     albertel 1147:     foreach my $uname (keys(%ids)) {
                   1148: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1149:         my $uhom=&homeserver($uname,$udom);
1.70      www      1150:         if ($uhom ne 'no_host') {
1.800     albertel 1151:             my $id=&escape($ids{$uname});
1.70      www      1152:             $id=~tr/A-Z/a-z/;
1.800     albertel 1153:             my $esc_unam=&escape($uname);
1.70      www      1154: 	    if ($servers{$uhom}) {
1.800     albertel 1155: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1156:             } else {
1.800     albertel 1157:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1158:             }
                   1159:         }
1.191     harris41 1160:     }
1.800     albertel 1161:     foreach my $server (keys(%servers)) {
                   1162:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1163:     }
1.344     www      1164: }
                   1165: 
1.1023    raeburn  1166: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1167: sub dump_dom {
1.1023    raeburn  1168:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1169:     if (!$udom) {
                   1170:         $udom=$env{'user.domain'};
                   1171:     }
                   1172:     my %returnhash;
1.1023    raeburn  1173:     if ($udom) {
                   1174:         my $uname = &get_domainconfiguser($udom);
                   1175:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1176:     }
                   1177:     return %returnhash;
                   1178: }
                   1179: 
1.1023    raeburn  1180: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1181: 
                   1182: sub get_dom {
1.860     raeburn  1183:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1184:     my $items='';
                   1185:     foreach my $item (@$storearr) {
                   1186:         $items.=&escape($item).'&';
                   1187:     }
                   1188:     $items=~s/\&$//;
1.860     raeburn  1189:     if (!$udom) {
                   1190:         $udom=$env{'user.domain'};
                   1191:         if (defined(&domain($udom,'primary'))) {
                   1192:             $uhome=&domain($udom,'primary');
                   1193:         } else {
1.874     albertel 1194:             undef($uhome);
1.860     raeburn  1195:         }
                   1196:     } else {
                   1197:         if (!$uhome) {
                   1198:             if (defined(&domain($udom,'primary'))) {
                   1199:                 $uhome=&domain($udom,'primary');
                   1200:             }
                   1201:         }
                   1202:     }
                   1203:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1204:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1205:         my %returnhash;
1.875     albertel 1206:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1207:             return %returnhash;
                   1208:         }
1.806     raeburn  1209:         my @pairs=split(/\&/,$rep);
                   1210:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1211:             return @pairs;
                   1212:         }
                   1213:         my $i=0;
                   1214:         foreach my $item (@$storearr) {
                   1215:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1216:             $i++;
                   1217:         }
                   1218:         return %returnhash;
                   1219:     } else {
1.880     banghart 1220:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1221:     }
                   1222: }
                   1223: 
                   1224: # -------------------------------------------- put items in domain db files 
                   1225: 
                   1226: sub put_dom {
1.860     raeburn  1227:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1228:     if (!$udom) {
                   1229:         $udom=$env{'user.domain'};
                   1230:         if (defined(&domain($udom,'primary'))) {
                   1231:             $uhome=&domain($udom,'primary');
                   1232:         } else {
1.874     albertel 1233:             undef($uhome);
1.860     raeburn  1234:         }
                   1235:     } else {
                   1236:         if (!$uhome) {
                   1237:             if (defined(&domain($udom,'primary'))) {
                   1238:                 $uhome=&domain($udom,'primary');
                   1239:             }
                   1240:         }
                   1241:     } 
                   1242:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1243:         my $items='';
                   1244:         foreach my $item (keys(%$storehash)) {
                   1245:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1246:         }
                   1247:         $items=~s/\&$//;
                   1248:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1249:     } else {
1.860     raeburn  1250:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1251:     }
                   1252: }
                   1253: 
1.1023    raeburn  1254: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1255: sub newput_dom {
1.1023    raeburn  1256:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1257:     my $result;
                   1258:     if (!$udom) {
                   1259:         $udom=$env{'user.domain'};
                   1260:     }
1.1023    raeburn  1261:     if ($udom) {
                   1262:         my $uname = &get_domainconfiguser($udom);
                   1263:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1264:     }
                   1265:     return $result;
                   1266: }
                   1267: 
1.1023    raeburn  1268: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1269: sub del_dom {
1.1023    raeburn  1270:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1271:     if (ref($storearr) eq 'ARRAY') {
                   1272:         if (!$udom) {
                   1273:             $udom=$env{'user.domain'};
                   1274:         }
1.1023    raeburn  1275:         if ($udom) {
                   1276:             my $uname = &get_domainconfiguser($udom); 
                   1277:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1278:         }
                   1279:     }
                   1280: }
                   1281: 
1.1023    raeburn  1282: # ----------------------------------construct domainconfig user for a domain 
                   1283: sub get_domainconfiguser {
                   1284:     my ($udom) = @_;
                   1285:     return $udom.'-domainconfig';
                   1286: }
                   1287: 
1.837     raeburn  1288: sub retrieve_inst_usertypes {
                   1289:     my ($udom) = @_;
                   1290:     my (%returnhash,@order);
1.989     raeburn  1291:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1292:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1293:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1294:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1295:         @order = @{$domdefs{'inststatusorder'}};
                   1296:     } else {
                   1297:         if (defined(&domain($udom,'primary'))) {
                   1298:             my $uhome=&domain($udom,'primary');
                   1299:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1300:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1301:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1302:                 return (\%returnhash,\@order);
                   1303:             }
                   1304:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1305:             my @pairs=split(/\&/,$hashitems);
                   1306:             foreach my $item (@pairs) {
                   1307:                 my ($key,$value)=split(/=/,$item,2);
                   1308:                 $key = &unescape($key);
                   1309:                 next if ($key =~ /^error: 2 /);
                   1310:                 $returnhash{$key}=&thaw_unescape($value);
                   1311:             }
                   1312:             my @esc_order = split(/\&/,$orderitems);
                   1313:             foreach my $item (@esc_order) {
                   1314:                 push(@order,&unescape($item));
                   1315:             }
                   1316:         } else {
                   1317:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1318:         }
                   1319:     }
                   1320:     return (\%returnhash,\@order);
                   1321: }
                   1322: 
1.868     raeburn  1323: sub is_domainimage {
                   1324:     my ($url) = @_;
                   1325:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1326:         if (&domain($1) ne '') {
                   1327:             return '1';
                   1328:         }
                   1329:     }
                   1330:     return;
                   1331: }
                   1332: 
1.899     raeburn  1333: sub inst_directory_query {
                   1334:     my ($srch) = @_;
                   1335:     my $udom = $srch->{'srchdomain'};
                   1336:     my %results;
                   1337:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1338:     my $outcome;
1.899     raeburn  1339:     if ($homeserver ne '') {
1.904     albertel 1340: 	my $queryid=&reply("querysend:instdirsearch:".
                   1341: 			   &escape($srch->{'srchby'}).':'.
                   1342: 			   &escape($srch->{'srchterm'}).':'.
                   1343: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1344: 	my $host=&hostname($homeserver);
                   1345: 	if ($queryid !~/^\Q$host\E\_/) {
                   1346: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1347: 	    return;
                   1348: 	}
                   1349: 	my $response = &get_query_reply($queryid);
                   1350: 	my $maxtries = 5;
                   1351: 	my $tries = 1;
                   1352: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1353: 	    $response = &get_query_reply($queryid);
                   1354: 	    $tries ++;
                   1355: 	}
                   1356: 
                   1357:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1358:             if ($response eq 'unavailable') {
                   1359:                 $outcome = $response;
                   1360:             } else {
                   1361:                 $outcome = 'ok';
                   1362:                 my @matches = split(/\n/,$response);
                   1363:                 foreach my $match (@matches) {
                   1364:                     my ($key,$value) = split(/=/,$match);
                   1365:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1366:                 }
1.899     raeburn  1367:             }
                   1368:         }
                   1369:     }
1.909     raeburn  1370:     return ($outcome,%results);
1.899     raeburn  1371: }
                   1372: 
                   1373: sub usersearch {
                   1374:     my ($srch) = @_;
                   1375:     my $dom = $srch->{'srchdomain'};
                   1376:     my %results;
                   1377:     my %libserv = &all_library();
                   1378:     my $query = 'usersearch';
                   1379:     foreach my $tryserver (keys(%libserv)) {
                   1380:         if (&host_domain($tryserver) eq $dom) {
                   1381:             my $host=&hostname($tryserver);
                   1382:             my $queryid=
1.911     raeburn  1383:                 &reply("querysend:".&escape($query).':'.
                   1384:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1385:                        &escape($srch->{'srchtype'}).':'.
                   1386:                        &escape($srch->{'srchterm'}),$tryserver);
                   1387:             if ($queryid !~/^\Q$host\E\_/) {
                   1388:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1389:                 next;
1.899     raeburn  1390:             }
                   1391:             my $reply = &get_query_reply($queryid);
                   1392:             my $maxtries = 1;
                   1393:             my $tries = 1;
                   1394:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1395:                 $reply = &get_query_reply($queryid);
                   1396:                 $tries ++;
                   1397:             }
                   1398:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1399:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1400:             } else {
1.911     raeburn  1401:                 my @matches;
                   1402:                 if ($reply =~ /\n/) {
                   1403:                     @matches = split(/\n/,$reply);
                   1404:                 } else {
                   1405:                     @matches = split(/\&/,$reply);
                   1406:                 }
1.899     raeburn  1407:                 foreach my $match (@matches) {
                   1408:                     my ($uname,$udom,%userhash);
1.911     raeburn  1409:                     foreach my $entry (split(/:/,$match)) {
                   1410:                         my ($key,$value) =
                   1411:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1412:                         $userhash{$key} = $value;
                   1413:                         if ($key eq 'username') {
                   1414:                             $uname = $value;
                   1415:                         } elsif ($key eq 'domain') {
                   1416:                             $udom = $value;
1.911     raeburn  1417:                         }
1.899     raeburn  1418:                     }
                   1419:                     $results{$uname.':'.$udom} = \%userhash;
                   1420:                 }
                   1421:             }
                   1422:         }
                   1423:     }
                   1424:     return %results;
                   1425: }
                   1426: 
1.912     raeburn  1427: sub get_instuser {
                   1428:     my ($udom,$uname,$id) = @_;
                   1429:     my $homeserver = &domain($udom,'primary');
                   1430:     my ($outcome,%results);
                   1431:     if ($homeserver ne '') {
                   1432:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1433:                            &escape($id).':'.&escape($udom),$homeserver);
                   1434:         my $host=&hostname($homeserver);
                   1435:         if ($queryid !~/^\Q$host\E\_/) {
                   1436:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1437:             return;
                   1438:         }
                   1439:         my $response = &get_query_reply($queryid);
                   1440:         my $maxtries = 5;
                   1441:         my $tries = 1;
                   1442:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1443:             $response = &get_query_reply($queryid);
                   1444:             $tries ++;
                   1445:         }
                   1446:         if (!&error($response) && $response ne 'refused') {
                   1447:             if ($response eq 'unavailable') {
                   1448:                 $outcome = $response;
                   1449:             } else {
                   1450:                 $outcome = 'ok';
                   1451:                 my @matches = split(/\n/,$response);
                   1452:                 foreach my $match (@matches) {
                   1453:                     my ($key,$value) = split(/=/,$match);
                   1454:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1455:                 }
                   1456:             }
                   1457:         }
                   1458:     }
                   1459:     my %userinfo;
                   1460:     if (ref($results{$uname}) eq 'HASH') {
                   1461:         %userinfo = %{$results{$uname}};
                   1462:     } 
                   1463:     return ($outcome,%userinfo);
                   1464: }
                   1465: 
                   1466: sub inst_rulecheck {
1.923     raeburn  1467:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1468:     my %returnhash;
                   1469:     if ($udom ne '') {
                   1470:         if (ref($rules) eq 'ARRAY') {
                   1471:             @{$rules} = map {&escape($_);} (@{$rules});
                   1472:             my $rulestr = join(':',@{$rules});
                   1473:             my $homeserver=&domain($udom,'primary');
                   1474:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1475:                 my $response;
                   1476:                 if ($item eq 'username') {                
                   1477:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1478:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1479:                                               $homeserver));
1.923     raeburn  1480:                 } elsif ($item eq 'id') {
                   1481:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1482:                                               ':'.&escape($id).':'.$rulestr,
                   1483:                                               $homeserver));
1.945     raeburn  1484:                 } elsif ($item eq 'selfcreate') {
                   1485:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1486:                                                &escape($udom).':'.&escape($uname).
                   1487:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1488:                 }
1.912     raeburn  1489:                 if ($response ne 'refused') {
                   1490:                     my @pairs=split(/\&/,$response);
                   1491:                     foreach my $item (@pairs) {
                   1492:                         my ($key,$value)=split(/=/,$item,2);
                   1493:                         $key = &unescape($key);
                   1494:                         next if ($key =~ /^error: 2 /);
                   1495:                         $returnhash{$key}=&thaw_unescape($value);
                   1496:                     }
                   1497:                 }
                   1498:             }
                   1499:         }
                   1500:     }
                   1501:     return %returnhash;
                   1502: }
                   1503: 
                   1504: sub inst_userrules {
1.923     raeburn  1505:     my ($udom,$check) = @_;
1.912     raeburn  1506:     my (%ruleshash,@ruleorder);
                   1507:     if ($udom ne '') {
                   1508:         my $homeserver=&domain($udom,'primary');
                   1509:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1510:             my $response;
                   1511:             if ($check eq 'id') {
                   1512:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1513:                                  $homeserver);
1.943     raeburn  1514:             } elsif ($check eq 'email') {
                   1515:                 $response=&reply('instemailrules:'.&escape($udom),
                   1516:                                  $homeserver);
1.923     raeburn  1517:             } else {
                   1518:                 $response=&reply('instuserrules:'.&escape($udom),
                   1519:                                  $homeserver);
                   1520:             }
1.912     raeburn  1521:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1522:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1523:                 ($response ne 'no_such_host')) {
                   1524:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1525:                 my @pairs=split(/\&/,$hashitems);
                   1526:                 foreach my $item (@pairs) {
                   1527:                     my ($key,$value)=split(/=/,$item,2);
                   1528:                     $key = &unescape($key);
                   1529:                     next if ($key =~ /^error: 2 /);
                   1530:                     $ruleshash{$key}=&thaw_unescape($value);
                   1531:                 }
                   1532:                 my @esc_order = split(/\&/,$orderitems);
                   1533:                 foreach my $item (@esc_order) {
                   1534:                     push(@ruleorder,&unescape($item));
                   1535:                 }
                   1536:             }
                   1537:         }
                   1538:     }
                   1539:     return (\%ruleshash,\@ruleorder);
                   1540: }
                   1541: 
1.976     raeburn  1542: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1543: 
                   1544: sub get_domain_defaults {
                   1545:     my ($domain) = @_;
                   1546:     my $cachetime = 60*60*24;
                   1547:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1548:     if (defined($cached)) {
                   1549:         if (ref($result) eq 'HASH') {
                   1550:             return %{$result};
                   1551:         }
                   1552:     }
                   1553:     my %domdefaults;
                   1554:     my %domconfig =
1.989     raeburn  1555:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1556:                                   'requestcourses','inststatus',
1.1073    raeburn  1557:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1558:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1559:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1560:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1561:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1562:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1563:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1564:     } else {
                   1565:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1566:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1567:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1568:     }
1.976     raeburn  1569:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1570:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1571:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1572:         } else {
                   1573:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1574:         } 
                   1575:         my @usertools = ('aboutme','blog','portfolio');
                   1576:         foreach my $item (@usertools) {
                   1577:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1578:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1579:             }
                   1580:         }
                   1581:     }
1.985     raeburn  1582:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1583:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1584:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1585:         }
                   1586:     }
1.989     raeburn  1587:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1588:         foreach my $item ('inststatustypes','inststatusorder') {
                   1589:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1590:         }
                   1591:     }
1.1047    raeburn  1592:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1593:         foreach my $item ('canuse_pdfforms') {
                   1594:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1595:         }
                   1596:     }
1.1073    raeburn  1597:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1598:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1599:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1600:         }
                   1601:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1602:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1603:         }
                   1604:     }
1.943     raeburn  1605:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1606:                                   $cachetime);
                   1607:     return %domdefaults;
                   1608: }
                   1609: 
1.344     www      1610: # --------------------------------------------------- Assign a key to a student
                   1611: 
                   1612: sub assign_access_key {
1.364     www      1613: #
                   1614: # a valid key looks like uname:udom#comments
                   1615: # comments are being appended
                   1616: #
1.498     www      1617:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1618:     $kdom=
1.620     albertel 1619:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1620:     $knum=
1.620     albertel 1621:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1622:     $cdom=
1.620     albertel 1623:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1624:     $cnum=
1.620     albertel 1625:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1626:     $udom=$env{'user.name'} unless (defined($udom));
                   1627:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1628:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1629:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1630:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1631:                                                   # assigned to this person
                   1632:                                                   # - this should not happen,
1.345     www      1633:                                                   # unless something went wrong
                   1634:                                                   # the first time around
                   1635: # ready to assign
1.364     www      1636:         $logentry=$1.'; '.$logentry;
1.496     www      1637:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1638:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1639: # key now belongs to user
1.346     www      1640: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1641:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1642:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1643:                 return 'ok';
                   1644:             } else {
                   1645:                 return 
                   1646:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1647: 	    }
                   1648:         } else {
                   1649:             return 'error: Could not assign key, try again later.';
                   1650:         }
1.364     www      1651:     } elsif (!$existing{$ckey}) {
1.345     www      1652: # the key does not exist
                   1653: 	return 'error: The key does not exist';
                   1654:     } else {
                   1655: # the key is somebody else's
                   1656: 	return 'error: The key is already in use';
                   1657:     }
1.344     www      1658: }
                   1659: 
1.364     www      1660: # ------------------------------------------ put an additional comment on a key
                   1661: 
                   1662: sub comment_access_key {
                   1663: #
                   1664: # a valid key looks like uname:udom#comments
                   1665: # comments are being appended
                   1666: #
                   1667:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1668:     $cdom=
1.620     albertel 1669:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1670:     $cnum=
1.620     albertel 1671:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1672:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1673:     if ($existing{$ckey}) {
                   1674:         $existing{$ckey}.='; '.$logentry;
                   1675: # ready to assign
1.367     www      1676:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1677:                                                  $cdom,$cnum) eq 'ok') {
                   1678: 	    return 'ok';
                   1679:         } else {
                   1680: 	    return 'error: Count not store comment.';
                   1681:         }
                   1682:     } else {
                   1683: # the key does not exist
                   1684: 	return 'error: The key does not exist';
                   1685:     }
                   1686: }
                   1687: 
1.344     www      1688: # ------------------------------------------------------ Generate a set of keys
                   1689: 
                   1690: sub generate_access_keys {
1.364     www      1691:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1692:     $cdom=
1.620     albertel 1693:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1694:     $cnum=
1.620     albertel 1695:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1696:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1697:     unless (($cdom) && ($cnum)) { return 0; }
                   1698:     if ($number>10000) { return 0; }
                   1699:     sleep(2); # make sure don't get same seed twice
                   1700:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1701:     my $total=0;
                   1702:     for (my $i=1;$i<=$number;$i++) {
                   1703:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1704:                   sprintf("%lx",int(100000*rand)).'-'.
                   1705:                   sprintf("%lx",int(100000*rand));
                   1706:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1707:        $newkey=~s/0/h/g; # and also 0 and O
                   1708:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1709:        if ($existing{$newkey}) {
                   1710:            $i--;
                   1711:        } else {
1.364     www      1712: 	  if (&put('accesskeys',
                   1713:               { $newkey => '# generated '.localtime().
1.620     albertel 1714:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1715:                            '; '.$logentry },
                   1716: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1717:               $total++;
                   1718: 	  }
                   1719:        }
                   1720:     }
1.620     albertel 1721:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1722:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1723:     return $total;
                   1724: }
                   1725: 
                   1726: # ------------------------------------------------------- Validate an accesskey
                   1727: 
                   1728: sub validate_access_key {
                   1729:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1730:     $cdom=
1.620     albertel 1731:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1732:     $cnum=
1.620     albertel 1733:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1734:     $udom=$env{'user.domain'} unless (defined($udom));
                   1735:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1736:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1737:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1738: }
                   1739: 
                   1740: # ------------------------------------- Find the section of student in a course
1.652     albertel 1741: sub devalidate_getsection_cache {
                   1742:     my ($udom,$unam,$courseid)=@_;
                   1743:     my $hashid="$udom:$unam:$courseid";
                   1744:     &devalidate_cache_new('getsection',$hashid);
                   1745: }
1.298     matthew  1746: 
1.815     albertel 1747: sub courseid_to_courseurl {
                   1748:     my ($courseid) = @_;
                   1749:     #already url style courseid
                   1750:     return $courseid if ($courseid =~ m{^/});
                   1751: 
                   1752:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1753: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1754: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1755: 	return "/$cdom/$cnum";
                   1756:     }
                   1757: 
                   1758:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1759:     if (exists($courseinfo{'num'})) {
                   1760: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1761:     }
                   1762: 
                   1763:     return undef;
                   1764: }
                   1765: 
1.298     matthew  1766: sub getsection {
                   1767:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1768:     my $cachetime=1800;
1.551     albertel 1769: 
                   1770:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1771:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1772:     if (defined($cached)) { return $result; }
                   1773: 
1.298     matthew  1774:     my %Pending; 
                   1775:     my %Expired;
                   1776:     #
                   1777:     # Each role can either have not started yet (pending), be active, 
                   1778:     #    or have expired.
                   1779:     #
                   1780:     # If there is an active role, we are done.
                   1781:     #
                   1782:     # If there is more than one role which has not started yet, 
                   1783:     #     choose the one which will start sooner
                   1784:     # If there is one role which has not started yet, return it.
                   1785:     #
                   1786:     # If there is more than one expired role, choose the one which ended last.
                   1787:     # If there is a role which has expired, return it.
                   1788:     #
1.815     albertel 1789:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1790:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1791:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1792:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1793:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1794:         my $section=$1;
                   1795:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1796:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1797:         my $now=time;
1.548     albertel 1798:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1799:             $Expired{$end}=$section;
                   1800:             next;
                   1801:         }
1.548     albertel 1802:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1803:             $Pending{$start}=$section;
                   1804:             next;
                   1805:         }
1.599     albertel 1806:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1807:     }
                   1808:     #
                   1809:     # Presumedly there will be few matching roles from the above
                   1810:     # loop and the sorting time will be negligible.
                   1811:     if (scalar(keys(%Pending))) {
                   1812:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1813:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1814:     } 
                   1815:     if (scalar(keys(%Expired))) {
                   1816:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1817:         my $time = pop(@sorted);
1.599     albertel 1818:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1819:     }
1.599     albertel 1820:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1821: }
1.70      www      1822: 
1.599     albertel 1823: sub save_cache {
                   1824:     &purge_remembered();
1.722     albertel 1825:     #&Apache::loncommon::validate_page();
1.620     albertel 1826:     undef(%env);
1.780     albertel 1827:     undef($env_loaded);
1.599     albertel 1828: }
1.452     albertel 1829: 
1.599     albertel 1830: my $to_remember=-1;
                   1831: my %remembered;
                   1832: my %accessed;
                   1833: my $kicks=0;
                   1834: my $hits=0;
1.849     albertel 1835: sub make_key {
                   1836:     my ($name,$id) = @_;
1.872     albertel 1837:     if (length($id) > 65 
                   1838: 	&& length(&escape($id)) > 200) {
                   1839: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1840:     }
1.849     albertel 1841:     return &escape($name.':'.$id);
                   1842: }
                   1843: 
1.599     albertel 1844: sub devalidate_cache_new {
                   1845:     my ($name,$id,$debug) = @_;
                   1846:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1847:     $id=&make_key($name,$id);
1.599     albertel 1848:     $memcache->delete($id);
                   1849:     delete($remembered{$id});
                   1850:     delete($accessed{$id});
                   1851: }
                   1852: 
                   1853: sub is_cached_new {
                   1854:     my ($name,$id,$debug) = @_;
1.849     albertel 1855:     $id=&make_key($name,$id);
1.599     albertel 1856:     if (exists($remembered{$id})) {
                   1857: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1858: 	$accessed{$id}=[&gettimeofday()];
                   1859: 	$hits++;
                   1860: 	return ($remembered{$id},1);
                   1861:     }
                   1862:     my $value = $memcache->get($id);
                   1863:     if (!(defined($value))) {
                   1864: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1865: 	return (undef,undef);
1.416     albertel 1866:     }
1.599     albertel 1867:     if ($value eq '__undef__') {
                   1868: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1869: 	$value=undef;
                   1870:     }
                   1871:     &make_room($id,$value,$debug);
                   1872:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1873:     return ($value,1);
                   1874: }
                   1875: 
                   1876: sub do_cache_new {
                   1877:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1878:     $id=&make_key($name,$id);
1.599     albertel 1879:     my $setvalue=$value;
                   1880:     if (!defined($setvalue)) {
                   1881: 	$setvalue='__undef__';
                   1882:     }
1.623     albertel 1883:     if (!defined($time) ) {
                   1884: 	$time=600;
                   1885:     }
1.599     albertel 1886:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1887:     my $result = $memcache->set($id,$setvalue,$time);
                   1888:     if (! $result) {
1.872     albertel 1889: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1890: 	$memcache->disconnect_all();
1.872     albertel 1891:     }
1.600     albertel 1892:     # need to make a copy of $value
1.919     albertel 1893:     &make_room($id,$value,$debug);
1.599     albertel 1894:     return $value;
                   1895: }
                   1896: 
                   1897: sub make_room {
                   1898:     my ($id,$value,$debug)=@_;
1.919     albertel 1899: 
                   1900:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1901:                                     : $value;
1.599     albertel 1902:     if ($to_remember<0) { return; }
                   1903:     $accessed{$id}=[&gettimeofday()];
                   1904:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1905:     my $to_kick;
                   1906:     my $max_time=0;
                   1907:     foreach my $other (keys(%accessed)) {
                   1908: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1909: 	    $to_kick=$other;
                   1910: 	    $max_time=&tv_interval($accessed{$other});
                   1911: 	}
                   1912:     }
                   1913:     delete($remembered{$to_kick});
                   1914:     delete($accessed{$to_kick});
                   1915:     $kicks++;
                   1916:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1917:     return;
                   1918: }
                   1919: 
1.599     albertel 1920: sub purge_remembered {
1.604     albertel 1921:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1922:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1923:     undef(%remembered);
                   1924:     undef(%accessed);
1.428     albertel 1925: }
1.70      www      1926: # ------------------------------------- Read an entry from a user's environment
                   1927: 
                   1928: sub userenvironment {
                   1929:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1930:     my $items;
                   1931:     foreach my $item (@what) {
                   1932:         $items.=&escape($item).'&';
                   1933:     }
                   1934:     $items=~s/\&$//;
1.70      www      1935:     my %returnhash=();
1.1009    raeburn  1936:     my $uhome = &homeserver($unam,$udom);
                   1937:     unless ($uhome eq 'no_host') {
                   1938:         my @answer=split(/\&/, 
                   1939:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1940:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1941:             return %returnhash;
                   1942:         }
1.1009    raeburn  1943:         my $i;
                   1944:         for ($i=0;$i<=$#what;$i++) {
                   1945: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1946:         }
1.70      www      1947:     }
                   1948:     return %returnhash;
1.1       albertel 1949: }
                   1950: 
1.617     albertel 1951: # ---------------------------------------------------------- Get a studentphoto
                   1952: sub studentphoto {
                   1953:     my ($udom,$unam,$ext) = @_;
                   1954:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1955:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1956:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1957:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1958:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1959:             } else {
                   1960:                 my ($result,$perm_reqd)=
1.707     albertel 1961: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1962:                 if ($result eq 'ok') {
                   1963:                     if (!($perm_reqd eq 'yes')) {
                   1964:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1965:                     }
                   1966:                 }
                   1967:             }
                   1968:         }
                   1969:     } else {
                   1970:         my ($result,$perm_reqd) = 
1.707     albertel 1971: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1972:         if ($result eq 'ok') {
                   1973:             if (!($perm_reqd eq 'yes')) {
                   1974:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1975:             }
                   1976:         }
                   1977:     }
                   1978:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1979: }
                   1980: 
                   1981: sub retrievestudentphoto {
                   1982:     my ($udom,$unam,$ext,$type) = @_;
                   1983:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1984:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1985:     if ($ret eq 'ok') {
                   1986:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1987:         if ($type eq 'thumbnail') {
                   1988:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1989:         }
                   1990:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1991:         return $tokenurl;
                   1992:     } else {
                   1993:         if ($type eq 'thumbnail') {
                   1994:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1995:         } else { 
                   1996:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1997:         }
1.617     albertel 1998:     }
                   1999: }
                   2000: 
1.263     www      2001: # -------------------------------------------------------------------- New chat
                   2002: 
                   2003: sub chatsend {
1.724     raeburn  2004:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2005:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2006:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2007:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2008:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2009: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2010: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2011: }
                   2012: 
                   2013: # ------------------------------------------ Find current version of a resource
                   2014: 
                   2015: sub getversion {
                   2016:     my $fname=&clutter(shift);
                   2017:     unless ($fname=~/^\/res\//) { return -1; }
                   2018:     return &currentversion(&filelocation('',$fname));
                   2019: }
                   2020: 
                   2021: sub currentversion {
                   2022:     my $fname=shift;
                   2023:     my $author=$fname;
                   2024:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2025:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2026:     my $home=&homeserver($uname,$udom);
1.292     www      2027:     if ($home eq 'no_host') { 
                   2028:         return -1; 
                   2029:     }
1.1112    www      2030:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2031:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2032: 	return -1;
                   2033:     }
1.1112    www      2034:     return $answer;
1.263     www      2035: }
                   2036: 
1.1111    www      2037: #
                   2038: # Return special version number of resource if set by override, empty otherwise
                   2039: #
                   2040: sub usedversion {
                   2041:     my $fname=shift;
                   2042:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2043:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2044:     if ($urlversion) { return $urlversion; }
                   2045:     return '';
                   2046: }
                   2047: 
1.1       albertel 2048: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2049: 
1.1       albertel 2050: sub subscribe {
                   2051:     my $fname=shift;
1.761     raeburn  2052:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2053:     $fname=~s/[\n\r]//g;
1.1       albertel 2054:     my $author=$fname;
                   2055:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2056:     my ($udom,$uname)=split(/\//,$author);
                   2057:     my $home=homeserver($uname,$udom);
1.335     albertel 2058:     if ($home eq 'no_host') {
                   2059:         return 'not_found';
1.1       albertel 2060:     }
                   2061:     my $answer=reply("sub:$fname",$home);
1.64      www      2062:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2063: 	$answer.=' by '.$home;
                   2064:     }
1.1       albertel 2065:     return $answer;
                   2066: }
                   2067:     
1.8       www      2068: # -------------------------------------------------------------- Replicate file
                   2069: 
                   2070: sub repcopy {
                   2071:     my $filename=shift;
1.23      www      2072:     $filename=~s/\/+/\//g;
1.607     raeburn  2073:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2074:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2075:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2076: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2077: 	return &repcopy_userfile($filename);
                   2078:     }
1.532     albertel 2079:     $filename=~s/[\n\r]//g;
1.8       www      2080:     my $transname="$filename.in.transfer";
1.828     www      2081: # FIXME: this should flock
1.607     raeburn  2082:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2083:     my $remoteurl=subscribe($filename);
1.64      www      2084:     if ($remoteurl =~ /^con_lost by/) {
                   2085: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2086:            return 'unavailable';
1.8       www      2087:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2088: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2089: 	   return 'not_found';
1.64      www      2090:     } elsif ($remoteurl =~ /^rejected by/) {
                   2091: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2092:            return 'forbidden';
1.20      www      2093:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2094:            return 'ok';
1.8       www      2095:     } else {
1.290     www      2096:         my $author=$filename;
                   2097:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2098:         my ($udom,$uname)=split(/\//,$author);
                   2099:         my $home=homeserver($uname,$udom);
                   2100:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2101:            my @parts=split(/\//,$filename);
                   2102:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2103:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2104:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2105: 	       return 'bad_request';
1.8       www      2106:            }
                   2107:            my $count;
                   2108:            for ($count=5;$count<$#parts;$count++) {
                   2109:                $path.="/$parts[$count]";
                   2110:                if ((-e $path)!=1) {
                   2111: 		   mkdir($path,0777);
                   2112:                }
                   2113:            }
                   2114:            my $ua=new LWP::UserAgent;
                   2115:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2116:            my $response=$ua->request($request,$transname);
                   2117:            if ($response->is_error()) {
                   2118: 	       unlink($transname);
                   2119:                my $message=$response->status_line;
1.672     albertel 2120:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2121:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2122:                return 'unavailable';
1.8       www      2123:            } else {
1.16      www      2124: 	       if ($remoteurl!~/\.meta$/) {
                   2125:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2126:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2127:                   if ($mresponse->is_error()) {
                   2128: 		      unlink($filename.'.meta');
                   2129:                       &logthis(
1.672     albertel 2130:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2131:                   }
                   2132: 	       }
1.8       www      2133:                rename($transname,$filename);
1.607     raeburn  2134:                return 'ok';
1.8       www      2135:            }
1.290     www      2136:        }
1.8       www      2137:     }
1.330     www      2138: }
                   2139: 
                   2140: # ------------------------------------------------ Get server side include body
                   2141: sub ssi_body {
1.381     albertel 2142:     my ($filelink,%form)=@_;
1.606     matthew  2143:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2144:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2145:     }
1.953     www      2146:     my $output='';
                   2147:     my $response;
1.980     raeburn  2148:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2149:        ($output,$response)=&externalssi($filelink);
1.953     www      2150:     } else {
1.1004    droeschl 2151:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2152:        $filelink .= 'inhibitmenu=yes';
1.953     www      2153:        ($output,$response)=&ssi($filelink,%form);
                   2154:     }
1.778     albertel 2155:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2156:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2157:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2158:     if (wantarray) {
                   2159:         return ($output, $response);
                   2160:     } else {
                   2161:         return $output;
                   2162:     }
1.8       www      2163: }
                   2164: 
1.15      www      2165: # --------------------------------------------------------- Server Side Include
                   2166: 
1.782     albertel 2167: sub absolute_url {
                   2168:     my ($host_name) = @_;
                   2169:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2170:     if ($host_name eq '') {
                   2171: 	$host_name = $ENV{'SERVER_NAME'};
                   2172:     }
                   2173:     return $protocol.$host_name;
                   2174: }
                   2175: 
1.942     foxr     2176: #
                   2177: #   Server side include.
                   2178: # Parameters:
                   2179: #  fn     Possibly encrypted resource name/id.
                   2180: #  form   Hash that describes how the rendering should be done
                   2181: #         and other things.
1.944     foxr     2182: # Returns:
1.950     raeburn  2183: #   Scalar context: The content of the response.
                   2184: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2185: #     
1.15      www      2186: sub ssi {
                   2187: 
1.944     foxr     2188:     my ($fn,%form)=@_;
1.15      www      2189:     my $ua=new LWP::UserAgent;
1.23      www      2190:     my $request;
1.711     albertel 2191: 
                   2192:     $form{'no_update_last_known'}=1;
1.895     albertel 2193:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2194:     if (%form) {
1.782     albertel 2195:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2196:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2197:     } else {
1.782     albertel 2198:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2199:     }
                   2200: 
1.15      www      2201:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2202:     my $response=$ua->request($request);
                   2203: 
1.944     foxr     2204:     if (wantarray) {
                   2205: 	return ($response->content, $response);
                   2206:     } else {
                   2207: 	return $response->content;
1.942     foxr     2208:     }
1.324     www      2209: }
                   2210: 
                   2211: sub externalssi {
                   2212:     my ($url)=@_;
                   2213:     my $ua=new LWP::UserAgent;
                   2214:     my $request=new HTTP::Request('GET',$url);
                   2215:     my $response=$ua->request($request);
1.954     raeburn  2216:     if (wantarray) {
                   2217:         return ($response->content, $response);
                   2218:     } else {
                   2219:         return $response->content;
                   2220:     }
1.15      www      2221: }
1.254     www      2222: 
1.492     albertel 2223: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2224: 
                   2225: sub allowuploaded {
                   2226:     my ($srcurl,$url)=@_;
                   2227:     $url=&clutter(&declutter($url));
                   2228:     my $dir=$url;
                   2229:     $dir=~s/\/[^\/]+$//;
                   2230:     my %httpref=();
                   2231:     my $httpurl=&hreflocation('',$url);
                   2232:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2233:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2234: }
1.477     raeburn  2235: 
1.478     albertel 2236: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2237: # input: action, courseID, current domain, intended
1.637     raeburn  2238: #        path to file, source of file, instruction to parse file for objects,
                   2239: #        ref to hash for embedded objects,
                   2240: #        ref to hash for codebase of java objects.
1.1095    raeburn  2241: #        reference to scalar to accommodate mime type determined
                   2242: #          from File::MMagic if $parser = parse.
1.637     raeburn  2243: #
1.485     raeburn  2244: # output: url to file (if action was uploaddoc), 
                   2245: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2246: #
1.478     albertel 2247: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2248: # course.
1.477     raeburn  2249: #
1.478     albertel 2250: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2251: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2252: #          course's home server.
1.477     raeburn  2253: #
1.478     albertel 2254: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2255: #          be copied from $source (current location) to 
                   2256: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2257: #         and will then be copied to
                   2258: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2259: #         course's home server.
1.485     raeburn  2260: #
1.481     raeburn  2261: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2262: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2263: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2264: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2265: #         in course's home server.
1.637     raeburn  2266: #
1.477     raeburn  2267: 
                   2268: sub process_coursefile {
1.1095    raeburn  2269:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2270:         $mimetype)=@_;
1.477     raeburn  2271:     my $fetchresult;
1.638     albertel 2272:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2273:     if ($action eq 'propagate') {
1.638     albertel 2274:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2275: 			     $home);
1.481     raeburn  2276:     } else {
1.477     raeburn  2277:         my $fpath = '';
                   2278:         my $fname = $file;
1.478     albertel 2279:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2280:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2281:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2282:         if ($action eq 'copy') {
                   2283:             if ($source eq '') {
                   2284:                 $fetchresult = 'no source file';
                   2285:                 return $fetchresult;
                   2286:             } else {
                   2287:                 my $destination = $filepath.'/'.$fname;
                   2288:                 rename($source,$destination);
                   2289:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2290:                                  $home);
1.481     raeburn  2291:             }
                   2292:         } elsif ($action eq 'uploaddoc') {
                   2293:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2294:             print $fh $env{'form.'.$source};
1.481     raeburn  2295:             close($fh);
1.637     raeburn  2296:             if ($parser eq 'parse') {
1.1024    raeburn  2297:                 my $mm = new File::MMagic;
1.1095    raeburn  2298:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2299:                 if ($type eq 'text/html') {
1.1024    raeburn  2300:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2301:                     unless ($parse_result eq 'ok') {
                   2302:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2303:                     }
1.637     raeburn  2304:                 }
1.1095    raeburn  2305:                 if (ref($mimetype)) {
                   2306:                     $$mimetype = $type;
                   2307:                 } 
1.637     raeburn  2308:             }
1.477     raeburn  2309:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2310:                                  $home);
1.481     raeburn  2311:             if ($fetchresult eq 'ok') {
                   2312:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2313:             } else {
                   2314:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2315:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2316:                 return '/adm/notfound.html';
                   2317:             }
1.477     raeburn  2318:         }
                   2319:     }
1.485     raeburn  2320:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2321:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2322:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2323:     }
                   2324:     return $fetchresult;
                   2325: }
                   2326: 
1.637     raeburn  2327: sub build_filepath {
                   2328:     my ($fpath) = @_;
                   2329:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2330:     unless ($fpath eq '') {
                   2331:         my @parts=split('/',$fpath);
                   2332:         foreach my $part (@parts) {
                   2333:             $filepath.= '/'.$part;
                   2334:             if ((-e $filepath)!=1) {
                   2335:                 mkdir($filepath,0777);
                   2336:             }
                   2337:         }
                   2338:     }
                   2339:     return $filepath;
                   2340: }
                   2341: 
                   2342: sub store_edited_file {
1.638     albertel 2343:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2344:     my $file = $primary_url;
                   2345:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2346:     my $fpath = '';
                   2347:     my $fname = $file;
                   2348:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2349:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2350:     my $filepath = &build_filepath($fpath);
                   2351:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2352:     print $fh $content;
                   2353:     close($fh);
1.638     albertel 2354:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2355:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2356: 			  $home);
1.637     raeburn  2357:     if ($$fetchresult eq 'ok') {
                   2358:         return '/uploaded/'.$fpath.'/'.$fname;
                   2359:     } else {
1.638     albertel 2360:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2361: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2362:         return '/adm/notfound.html';
                   2363:     }
                   2364: }
                   2365: 
1.531     albertel 2366: sub clean_filename {
1.831     albertel 2367:     my ($fname,$args)=@_;
1.315     www      2368: # Replace Windows backslashes by forward slashes
1.257     www      2369:     $fname=~s/\\/\//g;
1.831     albertel 2370:     if (!$args->{'keep_path'}) {
                   2371:         # Get rid of everything but the actual filename
                   2372: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2373:     }
1.315     www      2374: # Replace spaces by underscores
                   2375:     $fname=~s/\s+/\_/g;
                   2376: # Replace all other weird characters by nothing
1.831     albertel 2377:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2378: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2379: # numbers
                   2380:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2381:     return $fname;
                   2382: }
1.1051    raeburn  2383: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2384: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2385: # image with the same aspect ratio as the original, but with dimensions which do 
                   2386: # not exceed $resizewidth and $resizeheight.
                   2387:  
1.984     neumanie 2388: sub resizeImage {
1.1051    raeburn  2389:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2390:     my $ima = Image::Magick->new;
                   2391:     my $resized;
                   2392:     if (-e $img_path) {
                   2393:         $ima->Read($img_path);
                   2394:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2395:             my $width = $ima->Get('width');
                   2396:             my $height = $ima->Get('height');
                   2397:             if ($width > $resizewidth) {
                   2398: 	        my $factor = $width/$resizewidth;
                   2399:                 my $newheight = $height/$factor;
                   2400:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2401:                 $resized = 1;
                   2402:             }
                   2403:         }
                   2404:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2405:             my $width = $ima->Get('width');
                   2406:             my $height = $ima->Get('height');
                   2407:             if ($height > $resizeheight) {
                   2408:                 my $factor = $height/$resizeheight;
                   2409:                 my $newwidth = $width/$factor;
                   2410:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2411:                 $resized = 1;
                   2412:             }
                   2413:         }
                   2414:         if ($resized) {
                   2415:             $ima->Write($img_path);
                   2416:         }
                   2417:     }
                   2418:     return;
1.977     amueller 2419: }
                   2420: 
1.608     albertel 2421: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2422: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2423: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2424: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2425: #                                    canceloverwrite, or ''. 
                   2426: #                   if 'coursedoc': upload to the current course
                   2427: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2428: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2429: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2430: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2431: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2432: #        $allfiles - reference to hash for embedded objects
                   2433: #        $codebase - reference to hash for codebase of java objects
                   2434: #        $desuname - username for permanent storage of uploaded file
                   2435: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2436: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2437: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2438: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2439: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2440: #        $mimetype - reference to scalar to accommodate mime type determined
                   2441: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2442: # 
1.686     albertel 2443: # output: url of file in userspace, or error: <message> 
                   2444: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2445: 
1.531     albertel 2446: sub userfileupload {
1.1090    raeburn  2447:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2448:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2449:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2450:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2451:     $fname=&clean_filename($fname);
1.1090    raeburn  2452:     # See if there is anything left
1.257     www      2453:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2454:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2455:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2456:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2457:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2458:         my $now = time;
1.1090    raeburn  2459:         my $filepath;
1.1095    raeburn  2460:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2461:              $filepath = 'tmp/helprequests/'.$now;
                   2462:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2463:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2464:                          '_'.$env{'user.domain'}.'/pending';
                   2465:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2466:             my ($docuname,$docudom);
                   2467:             if ($destudom) {
                   2468:                 $docudom = $destudom;
                   2469:             } else {
                   2470:                 $docudom = $env{'user.domain'};
                   2471:             }
                   2472:             if ($destuname) {
                   2473:                 $docuname = $destuname;
                   2474:             } else {
                   2475:                 $docuname = $env{'user.name'};
                   2476:             }
                   2477:             if (exists($env{'form.group'})) {
                   2478:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2479:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2480:             }
                   2481:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2482:             if ($context eq 'canceloverwrite') {
                   2483:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2484:                 if (-e  $tempfile) {
                   2485:                     my @info = stat($tempfile);
                   2486:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2487:                         unlink($tempfile);
                   2488:                     }
                   2489:                 }
                   2490:                 return;
1.523     raeburn  2491:             }
                   2492:         }
1.1090    raeburn  2493:         # Create the directory if not present
1.741     raeburn  2494:         my @parts=split(/\//,$filepath);
                   2495:         my $fullpath = $perlvar{'lonDaemons'};
                   2496:         for (my $i=0;$i<@parts;$i++) {
                   2497:             $fullpath .= '/'.$parts[$i];
                   2498:             if ((-e $fullpath)!=1) {
                   2499:                 mkdir($fullpath,0777);
                   2500:             }
                   2501:         }
                   2502:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2503:         print $fh $env{'form.'.$formname};
                   2504:         close($fh);
1.1090    raeburn  2505:         if ($context eq 'existingfile') {
                   2506:             my @info = stat($fullpath.'/'.$fname);
                   2507:             return ($fullpath.'/'.$fname,$info[9]);
                   2508:         } else {
                   2509:             return $fullpath.'/'.$fname;
                   2510:         }
1.523     raeburn  2511:     }
1.995     raeburn  2512:     if ($subdir eq 'scantron') {
                   2513:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2514:     } else {
1.995     raeburn  2515:         $fname="$subdir/$fname";
                   2516:     }
1.1090    raeburn  2517:     if ($context eq 'coursedoc') {
1.638     albertel 2518: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2519: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2520:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2521:             return &finishuserfileupload($docuname,$docudom,
                   2522: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2523: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2524:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2525:         } else {
1.620     albertel 2526:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2527:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2528: 				       $fname,$formname,$parser,
1.1095    raeburn  2529: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2530:         }
1.719     banghart 2531:     } elsif (defined($destuname)) {
                   2532:         my $docuname=$destuname;
                   2533:         my $docudom=$destudom;
1.860     raeburn  2534: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2535: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2536:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2537:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2538:     } else {
1.638     albertel 2539:         my $docuname=$env{'user.name'};
                   2540:         my $docudom=$env{'user.domain'};
1.714     raeburn  2541:         if (exists($env{'form.group'})) {
                   2542:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2543:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2544:         }
1.860     raeburn  2545: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2546: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2547:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2548:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2549:     }
1.271     www      2550: }
                   2551: 
                   2552: sub finishuserfileupload {
1.860     raeburn  2553:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2554:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2555:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2556:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2557:   
1.860     raeburn  2558:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2559:     $file=$fname;
                   2560:     if ($fname=~m|/|) {
                   2561:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2562: 	$path.=$fnamepath.'/';
                   2563:     }
1.259     www      2564:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2565:     my $count;
                   2566:     for ($count=4;$count<=$#parts;$count++) {
                   2567:         $filepath.="/$parts[$count]";
                   2568:         if ((-e $filepath)!=1) {
                   2569: 	    mkdir($filepath,0777);
                   2570:         }
                   2571:     }
1.984     neumanie 2572: 
1.258     www      2573: # Save the file
                   2574:     {
1.701     albertel 2575: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2576: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2577: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2578: 	    return '/adm/notfound.html';
                   2579: 	}
1.1090    raeburn  2580:         if ($context eq 'overwrite') {
1.1117    foxr     2581:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2582:             my $target = $filepath.'/'.$file;
                   2583:             if (-e $source) {
                   2584:                 my @info = stat($source);
                   2585:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2586:                     unless (&File::Copy::move($source,$target)) {
                   2587:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2588:                         return "Moving from $source failed";
                   2589:                     }
                   2590:                 } else {
                   2591:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2592:                 }
                   2593:             } else {
                   2594:                 return "Temporary file: $source missing";
                   2595:             }
                   2596:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2597: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2598: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2599: 	    return '/adm/notfound.html';
                   2600: 	}
1.570     albertel 2601: 	close(FH);
1.1051    raeburn  2602:         if ($resizewidth && $resizeheight) {
                   2603:             my $mm = new File::MMagic;
                   2604:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2605:             if ($mime_type =~ m{^image/}) {
                   2606: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2607:             }  
1.977     amueller 2608: 	}
1.258     www      2609:     }
1.637     raeburn  2610:     if ($parser eq 'parse') {
1.1024    raeburn  2611:         my $mm = new File::MMagic;
1.1095    raeburn  2612:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2613:         if ($type eq 'text/html') {
1.1024    raeburn  2614:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2615:                                                        $allfiles,$codebase);
                   2616:             unless ($parse_result eq 'ok') {
                   2617:                 &logthis('Failed to parse '.$filepath.$file.
                   2618: 	   	         ' for embedded media: '.$parse_result); 
                   2619:             }
1.637     raeburn  2620:         }
1.1095    raeburn  2621:         if (ref($mimetype)) {
                   2622:             $$mimetype = $type;
                   2623:         }
1.637     raeburn  2624:     }
1.860     raeburn  2625:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2626:         my $input = $filepath.'/'.$file;
                   2627:         my $output = $filepath.'/'.'tn-'.$file;
                   2628:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2629:         system("convert -sample $thumbsize $input $output");
                   2630:         if (-e $filepath.'/'.'tn-'.$file) {
                   2631:             $fetchthumb  = 1; 
                   2632:         }
                   2633:     }
1.858     raeburn  2634:  
1.259     www      2635: # Notify homeserver to grep it
                   2636: #
1.984     neumanie 2637:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2638:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2639:     if ($fetchresult eq 'ok') {
1.860     raeburn  2640:         if ($fetchthumb) {
                   2641:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2642:             if ($thumbresult ne 'ok') {
                   2643:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2644:                          $docuhome.': '.$thumbresult);
                   2645:             }
                   2646:         }
1.259     www      2647: #
1.258     www      2648: # Return the URL to it
1.494     albertel 2649:         return '/uploaded/'.$path.$file;
1.263     www      2650:     } else {
1.494     albertel 2651:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2652: 		 ': '.$fetchresult);
1.263     www      2653:         return '/adm/notfound.html';
1.858     raeburn  2654:     }
1.493     albertel 2655: }
                   2656: 
1.637     raeburn  2657: sub extract_embedded_items {
1.961     raeburn  2658:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2659:     my @state = ();
                   2660:     my %javafiles = (
                   2661:                       codebase => '',
                   2662:                       code => '',
                   2663:                       archive => ''
                   2664:                     );
                   2665:     my %mediafiles = (
                   2666:                       src => '',
                   2667:                       movie => '',
                   2668:                      );
1.648     raeburn  2669:     my $p;
                   2670:     if ($content) {
                   2671:         $p = HTML::LCParser->new($content);
                   2672:     } else {
1.961     raeburn  2673:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2674:     }
1.641     albertel 2675:     while (my $t=$p->get_token()) {
1.640     albertel 2676: 	if ($t->[0] eq 'S') {
                   2677: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2678: 	    push(@state, $tagname);
1.648     raeburn  2679:             if (lc($tagname) eq 'allow') {
                   2680:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2681:             }
1.640     albertel 2682: 	    if (lc($tagname) eq 'img') {
                   2683: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2684: 	    }
1.886     albertel 2685: 	    if (lc($tagname) eq 'a') {
                   2686: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2687: 	    }
1.645     raeburn  2688:             if (lc($tagname) eq 'script') {
                   2689:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2690:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2691:                 } else {
                   2692:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2693:                 }
                   2694:             }
                   2695:             if (lc($tagname) eq 'link') {
                   2696:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2697:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2698:                 }
                   2699:             }
1.640     albertel 2700: 	    if (lc($tagname) eq 'object' ||
                   2701: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2702: 		foreach my $item (keys(%javafiles)) {
                   2703: 		    $javafiles{$item} = '';
                   2704: 		}
                   2705: 	    }
                   2706: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2707: 		my $name = lc($attr->{'name'});
                   2708: 		foreach my $item (keys(%javafiles)) {
                   2709: 		    if ($name eq $item) {
                   2710: 			$javafiles{$item} = $attr->{'value'};
                   2711: 			last;
                   2712: 		    }
                   2713: 		}
                   2714: 		foreach my $item (keys(%mediafiles)) {
                   2715: 		    if ($name eq $item) {
                   2716: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2717: 			last;
                   2718: 		    }
                   2719: 		}
                   2720: 	    }
                   2721: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2722: 		foreach my $item (keys(%javafiles)) {
                   2723: 		    if ($attr->{$item}) {
                   2724: 			$javafiles{$item} = $attr->{$item};
                   2725: 			last;
                   2726: 		    }
                   2727: 		}
                   2728: 		foreach my $item (keys(%mediafiles)) {
                   2729: 		    if ($attr->{$item}) {
                   2730: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2731: 			last;
                   2732: 		    }
                   2733: 		}
                   2734: 	    }
                   2735: 	} elsif ($t->[0] eq 'E') {
                   2736: 	    my ($tagname) = ($t->[1]);
                   2737: 	    if ($javafiles{'codebase'} ne '') {
                   2738: 		$javafiles{'codebase'} .= '/';
                   2739: 	    }  
                   2740: 	    if (lc($tagname) eq 'applet' ||
                   2741: 		lc($tagname) eq 'object' ||
                   2742: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2743: 		) {
                   2744: 		foreach my $item (keys(%javafiles)) {
                   2745: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2746: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2747: 			&add_filetype($allfiles,$file,$item);
                   2748: 		    }
                   2749: 		}
                   2750: 	    } 
                   2751: 	    pop @state;
                   2752: 	}
                   2753:     }
1.637     raeburn  2754:     return 'ok';
                   2755: }
                   2756: 
1.639     albertel 2757: sub add_filetype {
                   2758:     my ($allfiles,$file,$type)=@_;
                   2759:     if (exists($allfiles->{$file})) {
                   2760: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2761: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2762: 	}
                   2763:     } else {
                   2764: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2765:     }
                   2766: }
                   2767: 
1.493     albertel 2768: sub removeuploadedurl {
1.984     neumanie 2769:     my ($url)=@_;	
                   2770:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2771:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2772: }
                   2773: 
                   2774: sub removeuserfile {
                   2775:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2776:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2777:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2778:     if ($result eq 'ok') {	
1.798     raeburn  2779:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2780:             my $metafile = $fname.'.meta';
                   2781:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2782: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2783:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2784:             my $sqlresult = 
1.823     albertel 2785:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2786:                                         'portfolio_metadata',$group,
                   2787:                                         'delete');
1.798     raeburn  2788:         }
                   2789:     }
                   2790:     return $result;
1.257     www      2791: }
1.15      www      2792: 
1.530     albertel 2793: sub mkdiruserfile {
                   2794:     my ($docuname,$docudom,$dir)=@_;
                   2795:     my $home=&homeserver($docuname,$docudom);
                   2796:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2797: }
                   2798: 
1.531     albertel 2799: sub renameuserfile {
                   2800:     my ($docuname,$docudom,$old,$new)=@_;
                   2801:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2802:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2803:                         &escape("$old").':'.&escape("$new"),$home);
                   2804:     if ($result eq 'ok') {
                   2805:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2806:             my $oldmeta = $old.'.meta';
                   2807:             my $newmeta = $new.'.meta';
                   2808:             my $metaresult = 
                   2809:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2810: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2811:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2812:             my $sqlresult = 
1.823     albertel 2813:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2814:                                         'portfolio_metadata',$group,
                   2815:                                         'delete');
1.798     raeburn  2816:         }
                   2817:     }
                   2818:     return $result;
1.531     albertel 2819: }
                   2820: 
1.14      www      2821: # ------------------------------------------------------------------------- Log
                   2822: 
                   2823: sub log {
                   2824:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2825:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2826: }
                   2827: 
                   2828: # ------------------------------------------------------------------ Course Log
1.352     www      2829: #
                   2830: # This routine flushes several buffers of non-mission-critical nature
                   2831: #
1.157     www      2832: 
                   2833: sub flushcourselogs {
1.352     www      2834:     &logthis('Flushing log buffers');
                   2835: #
                   2836: # course logs
                   2837: # This is a log of all transactions in a course, which can be used
                   2838: # for data mining purposes
                   2839: #
                   2840: # It also collects the courseid database, which lists last transaction
                   2841: # times and course titles for all courseids
                   2842: #
                   2843:     my %courseidbuffer=();
1.921     raeburn  2844:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2845:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2846: 		          &escape($courselogs{$crsid}),
                   2847: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2848: 	    delete $courselogs{$crsid};
                   2849:         } else {
                   2850:             &logthis('Failed to flush log buffer for '.$crsid);
                   2851:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2852:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2853:                         " exceeded maximum size, deleting.</font>");
                   2854:                delete $courselogs{$crsid};
                   2855:             }
1.352     www      2856:         }
1.920     raeburn  2857:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2858:             'description' => $coursedescrbuf{$crsid},
                   2859:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2860:             'type'        => $coursetypebuf{$crsid},
                   2861:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2862:         };
1.191     harris41 2863:     }
1.352     www      2864: #
                   2865: # Write course id database (reverse lookup) to homeserver of courses 
                   2866: # Is used in pickcourse
                   2867: #
1.840     albertel 2868:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2869:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2870:                                     $courseidbuffer{$crs_home},
                   2871:                                     $crs_home,'timeonly');
1.352     www      2872:     }
                   2873: #
                   2874: # File accesses
                   2875: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2876: #
1.449     matthew  2877:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2878:         if ($entry =~ /___count$/) {
                   2879:             my ($dom,$name);
1.807     albertel 2880:             ($dom,$name,undef)=
1.811     albertel 2881: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2882:             if (! defined($dom) || $dom eq '' || 
                   2883:                 ! defined($name) || $name eq '') {
1.620     albertel 2884:                 my $cid = $env{'request.course.id'};
                   2885:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2886:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2887:             }
1.450     matthew  2888:             my $value = $accesshash{$entry};
                   2889:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2890:             my %temphash=($url => $value);
1.449     matthew  2891:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2892:             if ($result eq 'ok') {
                   2893:                 delete $accesshash{$entry};
                   2894:             } elsif ($result eq 'unknown_cmd') {
                   2895:                 # Target server has old code running on it.
1.450     matthew  2896:                 my %temphash=($entry => $value);
1.449     matthew  2897:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2898:                     delete $accesshash{$entry};
                   2899:                 }
                   2900:             }
                   2901:         } else {
1.811     albertel 2902:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2903:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2904:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2905:                 delete $accesshash{$entry};
                   2906:             }
1.185     www      2907:         }
1.191     harris41 2908:     }
1.352     www      2909: #
                   2910: # Roles
                   2911: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2912: #
1.800     albertel 2913:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2914:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2915: 	    split(/\:/,$entry);
                   2916:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2917:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2918:                 $rudom,$runame) eq 'ok') {
                   2919: 	    delete $userrolehash{$entry};
                   2920:         }
                   2921:     }
1.662     raeburn  2922: #
                   2923: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2924: #
                   2925:     my %domrolebuffer = ();
1.1000    raeburn  2926:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2927:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2928:         if ($domrolebuffer{$rudom}) {
                   2929:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2930:                       '='.&escape($domainrolehash{$entry});
                   2931:         } else {
                   2932:             $domrolebuffer{$rudom}.=&escape($entry).
                   2933:                       '='.&escape($domainrolehash{$entry});
                   2934:         }
                   2935:         delete $domainrolehash{$entry};
                   2936:     }
                   2937:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2938: 	my %servers = &get_servers($dom,'library');
                   2939: 	foreach my $tryserver (keys(%servers)) {
                   2940: 	    unless (&reply('domroleput:'.$dom.':'.
                   2941: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2942: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2943: 	    }
1.662     raeburn  2944:         }
                   2945:     }
1.186     www      2946:     $dumpcount++;
1.157     www      2947: }
                   2948: 
                   2949: sub courselog {
                   2950:     my $what=shift;
1.158     www      2951:     $what=time.':'.$what;
1.620     albertel 2952:     unless ($env{'request.course.id'}) { return ''; }
                   2953:     $coursedombuf{$env{'request.course.id'}}=
                   2954:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2955:     $coursenumbuf{$env{'request.course.id'}}=
                   2956:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2957:     $coursehombuf{$env{'request.course.id'}}=
                   2958:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2959:     $coursedescrbuf{$env{'request.course.id'}}=
                   2960:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2961:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2962:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2963:     $courseownerbuf{$env{'request.course.id'}}=
                   2964:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2965:     $coursetypebuf{$env{'request.course.id'}}=
                   2966:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2967:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2968: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2969:     } else {
1.620     albertel 2970: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2971:     }
1.620     albertel 2972:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2973: 	&flushcourselogs();
                   2974:     }
1.158     www      2975: }
                   2976: 
                   2977: sub courseacclog {
                   2978:     my $fnsymb=shift;
1.620     albertel 2979:     unless ($env{'request.course.id'}) { return ''; }
                   2980:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2981:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2982:         $what.=':POST';
1.583     matthew  2983:         # FIXME: Probably ought to escape things....
1.800     albertel 2984: 	foreach my $key (keys(%env)) {
                   2985:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2986:                 my $formitem = $1;
                   2987:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2988:                     $what.=':'.$formitem.'='.$env{$key};
                   2989:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2990:                     $what.=':'.$formitem.'='.$env{$key};
                   2991:                 }
1.158     www      2992:             }
1.191     harris41 2993:         }
1.583     matthew  2994:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2995:         # FIXME: We should not be depending on a form parameter that someone
                   2996:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2997:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2998:             $what.= ':POST';
                   2999:             # FIXME: Probably ought to escape things....
                   3000:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3001:                                  'crsdiscuss') {
1.620     albertel 3002:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3003:             }
                   3004:         }
1.158     www      3005:     }
                   3006:     &courselog($what);
1.149     www      3007: }
                   3008: 
1.185     www      3009: sub countacc {
                   3010:     my $url=&declutter(shift);
1.458     matthew  3011:     return if (! defined($url) || $url eq '');
1.620     albertel 3012:     unless ($env{'request.course.id'}) { return ''; }
                   3013:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3014:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3015:     $accesshash{$key}++;
1.185     www      3016: }
1.349     www      3017: 
1.361     www      3018: sub linklog {
                   3019:     my ($from,$to)=@_;
                   3020:     $from=&declutter($from);
                   3021:     $to=&declutter($to);
                   3022:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3023:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3024: }
                   3025:   
1.349     www      3026: sub userrolelog {
                   3027:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3028:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3029:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3030:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3031:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3032:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3033:        $userrolehash
                   3034:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3035:                     =$tend.':'.$tstart;
1.662     raeburn  3036:     }
1.898     albertel 3037:     if (($env{'request.role'} =~ /dc\./) &&
                   3038: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3039: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3040: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3041:          ($trole=~/^co/))) {
1.898     albertel 3042:        $userrolehash
                   3043:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3044:                     =$tend.':'.$tstart;
                   3045:     }
1.662     raeburn  3046:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3047:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3048:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3049:         ($trole=~/^sc/)) {
                   3050:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3051:        $domainrolehash
                   3052:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3053:                     = $tend.':'.$tstart;
                   3054:     }
1.351     www      3055: }
                   3056: 
1.957     raeburn  3057: sub courserolelog {
                   3058:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3059:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3060:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3061:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3062:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3063:         ($trole eq 'co')) {
1.957     raeburn  3064:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3065:             my $cdom = $1;
                   3066:             my $cnum = $2;
                   3067:             my $sec = $3;
                   3068:             my $namespace = 'rolelog';
                   3069:             my %storehash = (
                   3070:                                role    => $trole,
                   3071:                                start   => $tstart,
                   3072:                                end     => $tend,
                   3073:                                selfenroll => $selfenroll,
                   3074:                                context    => $context,
                   3075:                             );
                   3076:             if ($trole eq 'gr') {
                   3077:                 $namespace = 'groupslog';
                   3078:                 $storehash{'group'} = $sec;
                   3079:             } else {
                   3080:                 $storehash{'section'} = $sec;
                   3081:             }
                   3082:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3083:             if (($trole ne 'st') || ($sec ne '')) {
                   3084:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3085:             }
1.957     raeburn  3086:         }
                   3087:     }
                   3088:     return;
                   3089: }
                   3090: 
1.351     www      3091: sub get_course_adv_roles {
1.948     raeburn  3092:     my ($cid,$codes) = @_;
1.620     albertel 3093:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3094:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3095:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3096:     my %nothide=();
1.800     albertel 3097:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3098:         if ($user !~ /:/) {
                   3099: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3100:         } else {
                   3101:             $nothide{$user}=1;
                   3102:         }
1.470     www      3103:     }
1.351     www      3104:     my %returnhash=();
                   3105:     my %dumphash=
                   3106:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3107:     my $now=time;
1.997     raeburn  3108:     my %privileged;
1.1000    raeburn  3109:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3110: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3111:         if (($tstart) && ($tstart<0)) { next; }
                   3112:         if (($tend) && ($tend<$now)) { next; }
                   3113:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3114:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3115: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3116:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3117:             my %dompersonnel =
1.998     raeburn  3118:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3119:             $privileged{$domain} = {};
                   3120:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3121:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3122:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3123:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3124:                         $privileged{$udom}{$uname} = 1;
                   3125:                     }
                   3126:                 }
                   3127:             }
                   3128:         }
                   3129:         if ((exists($privileged{$domain}{$username})) && 
                   3130:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3131: 	if ($role eq 'cr') { next; }
1.948     raeburn  3132:         if ($codes) {
                   3133:             if ($section) { $role .= ':'.$section; }
                   3134:             if ($returnhash{$role}) {
                   3135:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3136:             } else {
                   3137:                 $returnhash{$role}=$username.':'.$domain;
                   3138:             }
1.351     www      3139:         } else {
1.988     raeburn  3140:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3141:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3142:             if ($returnhash{$key}) {
                   3143: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3144:             } else {
                   3145:                 $returnhash{$key}=$username.':'.$domain;
                   3146:             }
1.351     www      3147:         }
1.948     raeburn  3148:     }
1.400     www      3149:     return %returnhash;
                   3150: }
                   3151: 
                   3152: sub get_my_roles {
1.937     raeburn  3153:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3154:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3155:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3156:     my (%dumphash,%nothide);
1.1086    raeburn  3157:     if ($context eq 'userroles') {
                   3158:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3159:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3160:     } else {
                   3161:         %dumphash=
1.400     www      3162:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3163:         if ($hidepriv) {
                   3164:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3165:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3166:                 if ($user !~ /:/) {
                   3167:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3168:                 } else {
                   3169:                     $nothide{$user} = 1;
                   3170:                 }
                   3171:             }
                   3172:         }
1.858     raeburn  3173:     }
1.400     www      3174:     my %returnhash=();
                   3175:     my $now=time;
1.999     raeburn  3176:     my %privileged;
1.800     albertel 3177:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3178:         my ($role,$tend,$tstart);
                   3179:         if ($context eq 'userroles') {
                   3180: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3181:         } else {
                   3182:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3183:         }
1.400     www      3184:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3185:         my $status = 'active';
1.939     raeburn  3186:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3187:             $status = 'previous';
                   3188:         } 
                   3189:         if (($tstart) && ($now<$tstart)) {
                   3190:             $status = 'future';
                   3191:         }
                   3192:         if (ref($types) eq 'ARRAY') {
                   3193:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3194:                 next;
                   3195:             } 
                   3196:         } else {
                   3197:             if ($status ne 'active') {
                   3198:                 next;
                   3199:             }
                   3200:         }
1.867     raeburn  3201:         my ($rolecode,$username,$domain,$section,$area);
                   3202:         if ($context eq 'userroles') {
                   3203:             ($area,$rolecode) = split(/_/,$entry);
                   3204:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3205:         } else {
                   3206:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3207:         }
1.832     raeburn  3208:         if (ref($roledoms) eq 'ARRAY') {
                   3209:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3210:                 next;
                   3211:             }
                   3212:         }
                   3213:         if (ref($roles) eq 'ARRAY') {
                   3214:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3215:                 if ($role =~ /^cr\//) {
                   3216:                     if (!grep(/^cr$/,@{$roles})) {
                   3217:                         next;
                   3218:                     }
1.1104    raeburn  3219:                 } elsif ($role =~ /^gr\//) {
                   3220:                     if (!grep(/^gr$/,@{$roles})) {
                   3221:                         next;
                   3222:                     }
1.922     raeburn  3223:                 } else {
                   3224:                     next;
                   3225:                 }
1.832     raeburn  3226:             }
1.867     raeburn  3227:         }
1.937     raeburn  3228:         if ($hidepriv) {
1.999     raeburn  3229:             if ($context eq 'userroles') {
                   3230:                 if ((&privileged($username,$domain)) &&
                   3231:                     (!$nothide{$username.':'.$domain})) {
                   3232:                     next;
                   3233:                 }
                   3234:             } else {
                   3235:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3236:                     my %dompersonnel =
                   3237:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3238:                     $privileged{$domain} = {};
                   3239:                     if (keys(%dompersonnel)) {
                   3240:                         foreach my $server (keys(%dompersonnel)) {
                   3241:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3242:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3243:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3244:                                     $privileged{$udom}{$uname} = $trole;
                   3245:                                 }
                   3246:                             }
                   3247:                         }
                   3248:                     }
                   3249:                 }
                   3250:                 if (exists($privileged{$domain}{$username})) {
                   3251:                     if (!$nothide{$username.':'.$domain}) {
                   3252:                         next;
                   3253:                     }
                   3254:                 }
1.937     raeburn  3255:             }
                   3256:         }
1.933     raeburn  3257:         if ($withsec) {
                   3258:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3259:                 $tstart.':'.$tend;
                   3260:         } else {
                   3261:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3262:         }
1.832     raeburn  3263:     }
1.373     www      3264:     return %returnhash;
1.399     www      3265: }
                   3266: 
                   3267: # ----------------------------------------------------- Frontpage Announcements
                   3268: #
                   3269: #
                   3270: 
                   3271: sub postannounce {
                   3272:     my ($server,$text)=@_;
1.844     albertel 3273:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3274:     unless ($text=~/\w/) { $text=''; }
                   3275:     return &reply('setannounce:'.&escape($text),$server);
                   3276: }
                   3277: 
                   3278: sub getannounce {
1.448     albertel 3279: 
                   3280:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3281: 	my $announcement='';
1.800     albertel 3282: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3283: 	close($fh);
1.399     www      3284: 	if ($announcement=~/\w/) { 
                   3285: 	    return 
                   3286:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3287:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3288: 	} else {
                   3289: 	    return '';
                   3290: 	}
                   3291:     } else {
                   3292: 	return '';
                   3293:     }
1.351     www      3294: }
1.353     www      3295: 
                   3296: # ---------------------------------------------------------- Course ID routines
                   3297: # Deal with domain's nohist_courseid.db files
                   3298: #
                   3299: 
                   3300: sub courseidput {
1.921     raeburn  3301:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3302:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3303:     my $outcome;
                   3304:     if ($caller eq 'timeonly') {
                   3305:         my $cids = '';
                   3306:         foreach my $item (keys(%$storehash)) {
                   3307:             $cids.=&escape($item).'&';
                   3308:         }
                   3309:         $cids=~s/\&$//;
                   3310:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3311:                           $coursehome);       
                   3312:     } else {
                   3313:         my $items = '';
                   3314:         foreach my $item (keys(%$storehash)) {
                   3315:             $items.= &escape($item).'='.
                   3316:                      &freeze_escape($$storehash{$item}).'&';
                   3317:         }
                   3318:         $items=~s/\&$//;
                   3319:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3320:                           $coursehome);
1.918     raeburn  3321:     }
                   3322:     if ($outcome eq 'unknown_cmd') {
                   3323:         my $what;
                   3324:         foreach my $cid (keys(%$storehash)) {
                   3325:             $what .= &escape($cid).'=';
1.921     raeburn  3326:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3327:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3328:             }
                   3329:             $what =~ s/\:$/&/;
                   3330:         }
                   3331:         $what =~ s/\&$//;  
                   3332:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3333:     } else {
                   3334:         return $outcome;
                   3335:     }
1.353     www      3336: }
                   3337: 
                   3338: sub courseiddump {
1.921     raeburn  3339:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3340:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3341:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3342:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3343:     my $as_hash = 1;
                   3344:     my %returnhash;
                   3345:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3346:     my %libserv = &all_library();
                   3347:     foreach my $tryserver (keys(%libserv)) {
                   3348:         if ( (  $hostidflag == 1 
                   3349: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3350: 	     || (!defined($hostidflag)) ) {
                   3351: 
1.918     raeburn  3352: 	    if (($domfilter eq '') ||
                   3353: 		(&host_domain($tryserver) eq $domfilter)) {
                   3354:                 my $rep = 
                   3355:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3356:                          $sincefilter.':'.&escape($descfilter).':'.
                   3357:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3358:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3359:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3360:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3361:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3362:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3363:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3364:                          &escape($creationcontext).':'.$domcloner,
                   3365:                          $tryserver);
1.918     raeburn  3366:                 my @pairs=split(/\&/,$rep);
                   3367:                 foreach my $item (@pairs) {
                   3368:                     my ($key,$value)=split(/\=/,$item,2);
                   3369:                     $key = &unescape($key);
                   3370:                     next if ($key =~ /^error: 2 /);
                   3371:                     my $result = &thaw_unescape($value);
                   3372:                     if (ref($result) eq 'HASH') {
                   3373:                         $returnhash{$key}=$result;
                   3374:                     } else {
1.921     raeburn  3375:                         my @responses = split(/:/,$value);
                   3376:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3377:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3378:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3379:                         }
1.1008    raeburn  3380:                     }
1.353     www      3381:                 }
                   3382:             }
                   3383:         }
                   3384:     }
                   3385:     return %returnhash;
                   3386: }
                   3387: 
1.1055    raeburn  3388: sub courselastaccess {
                   3389:     my ($cdom,$cnum,$hostidref) = @_;
                   3390:     my %returnhash;
                   3391:     if ($cdom && $cnum) {
                   3392:         my $chome = &homeserver($cnum,$cdom);
                   3393:         if ($chome ne 'no_host') {
                   3394:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3395:             &extract_lastaccess(\%returnhash,$rep);
                   3396:         }
                   3397:     } else {
                   3398:         if (!$cdom) { $cdom=''; }
                   3399:         my %libserv = &all_library();
                   3400:         foreach my $tryserver (keys(%libserv)) {
                   3401:             if (ref($hostidref) eq 'ARRAY') {
                   3402:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3403:             } 
                   3404:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3405:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3406:                 &extract_lastaccess(\%returnhash,$rep);
                   3407:             }
                   3408:         }
                   3409:     }
                   3410:     return %returnhash;
                   3411: }
                   3412: 
                   3413: sub extract_lastaccess {
                   3414:     my ($returnhash,$rep) = @_;
                   3415:     if (ref($returnhash) eq 'HASH') {
                   3416:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3417:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3418:                  $rep eq '') {
                   3419:             my @pairs=split(/\&/,$rep);
                   3420:             foreach my $item (@pairs) {
                   3421:                 my ($key,$value)=split(/\=/,$item,2);
                   3422:                 $key = &unescape($key);
                   3423:                 next if ($key =~ /^error: 2 /);
                   3424:                 $returnhash->{$key} = &thaw_unescape($value);
                   3425:             }
                   3426:         }
                   3427:     }
                   3428:     return;
                   3429: }
                   3430: 
1.658     raeburn  3431: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3432: 
                   3433: sub dcmailput {
1.685     raeburn  3434:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3435:     my $status = &Apache::lonnet::critical(
1.740     www      3436:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3437:        &escape($message),$server);
1.662     raeburn  3438:     return $status;
                   3439: }
                   3440: 
1.658     raeburn  3441: sub dcmaildump {
                   3442:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3443:     my %returnhash=();
1.846     albertel 3444: 
                   3445:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3446:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3447:                                                          &escape($enddate).':';
                   3448: 	my @esc_senders=map { &escape($_)} @$senders;
                   3449: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3450: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3451:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3452:             if (($key) && ($value)) {
                   3453:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3454:             }
                   3455:         }
                   3456:     }
                   3457:     return %returnhash;
                   3458: }
1.662     raeburn  3459: # ---------------------------------------------------------- Domain roles
                   3460: 
                   3461: sub get_domain_roles {
                   3462:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3463:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3464:         $startdate = '.';
                   3465:     }
1.1018    raeburn  3466:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3467:         $enddate = '.';
                   3468:     }
1.922     raeburn  3469:     my $rolelist;
                   3470:     if (ref($roles) eq 'ARRAY') {
                   3471:         $rolelist = join(':',@{$roles});
                   3472:     }
1.662     raeburn  3473:     my %personnel = ();
1.841     albertel 3474: 
                   3475:     my %servers = &get_servers($dom,'library');
                   3476:     foreach my $tryserver (keys(%servers)) {
                   3477: 	%{$personnel{$tryserver}}=();
                   3478: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3479: 					    &escape($startdate).':'.
                   3480: 					    &escape($enddate).':'.
                   3481: 					    &escape($rolelist), $tryserver))) {
                   3482: 	    my ($key,$value) = split(/\=/,$line,2);
                   3483: 	    if (($key) && ($value)) {
                   3484: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3485: 	    }
                   3486: 	}
1.662     raeburn  3487:     }
                   3488:     return %personnel;
                   3489: }
1.658     raeburn  3490: 
1.1057    www      3491: # ----------------------------------------------------------- Interval timing 
1.149     www      3492: 
1.504     albertel 3493: sub get_first_access {
                   3494:     my ($type,$argsymb)=@_;
1.790     albertel 3495:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3496:     if ($argsymb) { $symb=$argsymb; }
                   3497:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3498:     if ($type eq 'course') {
                   3499: 	$res='course';
                   3500:     } elsif ($type eq 'map') {
1.588     albertel 3501: 	$res=&symbread($map);
                   3502:     } else {
                   3503: 	$res=$symb;
                   3504:     }
                   3505:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3506:     return $times{"$courseid\0$res"};
1.504     albertel 3507: }
                   3508: 
                   3509: sub set_first_access {
                   3510:     my ($type)=@_;
1.790     albertel 3511:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3512:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3513:     if ($type eq 'course') {
                   3514: 	$res='course';
                   3515:     } elsif ($type eq 'map') {
1.588     albertel 3516: 	$res=&symbread($map);
                   3517:     } else {
                   3518: 	$res=$symb;
                   3519:     }
                   3520:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3521:     if (!$firstaccess) {
1.588     albertel 3522: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3523:     }
                   3524:     return 'already_set';
1.504     albertel 3525: }
                   3526: 
1.110     www      3527: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3528: 
                   3529: sub expirespread {
                   3530:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3531:     my $cid=$env{'request.course.id'}; 
1.110     www      3532:     if ($cid) {
                   3533:        my $now=time;
                   3534:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3535:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3536:                             $env{'course.'.$cid.'.num'}.
1.110     www      3537: 	        	    ':nohist_expirationdates:'.
                   3538:                             &escape($key).'='.$now,
1.620     albertel 3539:                             $env{'course.'.$cid.'.home'})
1.110     www      3540:     }
                   3541:     return 'ok';
1.14      www      3542: }
                   3543: 
1.109     www      3544: # ----------------------------------------------------- Devalidate Spreadsheets
                   3545: 
                   3546: sub devalidate {
1.325     www      3547:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3548:     my $cid=$env{'request.course.id'}; 
1.109     www      3549:     if ($cid) {
1.391     matthew  3550:         # delete the stored spreadsheets for
                   3551:         # - the student level sheet of this user in course's homespace
                   3552:         # - the assessment level sheet for this resource 
                   3553:         #   for this user in user's homespace
1.553     albertel 3554: 	# - current conditional state info
1.325     www      3555: 	my $key=$uname.':'.$udom.':';
1.109     www      3556:         my $status=
1.299     matthew  3557: 	    &del('nohist_calculatedsheets',
1.391     matthew  3558: 		 [$key.'studentcalc:'],
1.620     albertel 3559: 		 $env{'course.'.$cid.'.domain'},
                   3560: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3561: 		.' '.
                   3562: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3563: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3564:         unless ($status eq 'ok ok') {
                   3565:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3566:                     $uname.' at '.$udom.' for '.
1.109     www      3567: 		    $symb.': '.$status);
1.133     albertel 3568:         }
1.553     albertel 3569: 	&delenv('user.state.'.$cid);
1.109     www      3570:     }
                   3571: }
                   3572: 
1.265     albertel 3573: sub get_scalar {
                   3574:     my ($string,$end) = @_;
                   3575:     my $value;
                   3576:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3577: 	$value = $1;
                   3578:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3579: 	$value = $1;
                   3580:     }
                   3581:     return &unescape($value);
                   3582: }
                   3583: 
                   3584: sub array2str {
                   3585:   my (@array) = @_;
                   3586:   my $result=&arrayref2str(\@array);
                   3587:   $result=~s/^__ARRAY_REF__//;
                   3588:   $result=~s/__END_ARRAY_REF__$//;
                   3589:   return $result;
                   3590: }
                   3591: 
1.204     albertel 3592: sub arrayref2str {
                   3593:   my ($arrayref) = @_;
1.265     albertel 3594:   my $result='__ARRAY_REF__';
1.204     albertel 3595:   foreach my $elem (@$arrayref) {
1.265     albertel 3596:     if(ref($elem) eq 'ARRAY') {
                   3597:       $result.=&arrayref2str($elem).'&';
                   3598:     } elsif(ref($elem) eq 'HASH') {
                   3599:       $result.=&hashref2str($elem).'&';
                   3600:     } elsif(ref($elem)) {
                   3601:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3602:     } else {
                   3603:       $result.=&escape($elem).'&';
                   3604:     }
                   3605:   }
                   3606:   $result=~s/\&$//;
1.265     albertel 3607:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3608:   return $result;
                   3609: }
                   3610: 
1.168     albertel 3611: sub hash2str {
1.204     albertel 3612:   my (%hash) = @_;
                   3613:   my $result=&hashref2str(\%hash);
1.265     albertel 3614:   $result=~s/^__HASH_REF__//;
                   3615:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3616:   return $result;
                   3617: }
                   3618: 
                   3619: sub hashref2str {
                   3620:   my ($hashref)=@_;
1.265     albertel 3621:   my $result='__HASH_REF__';
1.800     albertel 3622:   foreach my $key (sort(keys(%$hashref))) {
                   3623:     if (ref($key) eq 'ARRAY') {
                   3624:       $result.=&arrayref2str($key).'=';
                   3625:     } elsif (ref($key) eq 'HASH') {
                   3626:       $result.=&hashref2str($key).'=';
                   3627:     } elsif (ref($key)) {
1.265     albertel 3628:       $result.='=';
1.800     albertel 3629:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3630:     } else {
1.800     albertel 3631: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3632:     }
                   3633: 
1.800     albertel 3634:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3635:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3636:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3637:       $result.=&hashref2str($hashref->{$key}).'&';
                   3638:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3639:        $result.='&';
1.800     albertel 3640:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3641:     } else {
1.800     albertel 3642:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3643:     }
                   3644:   }
1.168     albertel 3645:   $result=~s/\&$//;
1.265     albertel 3646:   $result .= '__END_HASH_REF__';
1.168     albertel 3647:   return $result;
                   3648: }
                   3649: 
                   3650: sub str2hash {
1.265     albertel 3651:     my ($string)=@_;
                   3652:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3653:     return %$hash;
                   3654: }
                   3655: 
                   3656: sub str2hashref {
1.168     albertel 3657:   my ($string) = @_;
1.265     albertel 3658: 
                   3659:   my %hash;
                   3660: 
                   3661:   if($string !~ /^__HASH_REF__/) {
                   3662:       if (! ($string eq '' || !defined($string))) {
                   3663: 	  $hash{'error'}='Not hash reference';
                   3664:       }
                   3665:       return (\%hash, $string);
                   3666:   }
                   3667: 
                   3668:   $string =~ s/^__HASH_REF__//;
                   3669: 
                   3670:   while($string !~ /^__END_HASH_REF__/) {
                   3671:       #key
                   3672:       my $key='';
                   3673:       if($string =~ /^__HASH_REF__/) {
                   3674:           ($key, $string)=&str2hashref($string);
                   3675:           if(defined($key->{'error'})) {
                   3676:               $hash{'error'}='Bad data';
                   3677:               return (\%hash, $string);
                   3678:           }
                   3679:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3680:           ($key, $string)=&str2arrayref($string);
                   3681:           if($key->[0] eq 'Array reference error') {
                   3682:               $hash{'error'}='Bad data';
                   3683:               return (\%hash, $string);
                   3684:           }
                   3685:       } else {
                   3686:           $string =~ s/^(.*?)=//;
1.267     albertel 3687: 	  $key=&unescape($1);
1.265     albertel 3688:       }
                   3689:       $string =~ s/^=//;
                   3690: 
                   3691:       #value
                   3692:       my $value='';
                   3693:       if($string =~ /^__HASH_REF__/) {
                   3694:           ($value, $string)=&str2hashref($string);
                   3695:           if(defined($value->{'error'})) {
                   3696:               $hash{'error'}='Bad data';
                   3697:               return (\%hash, $string);
                   3698:           }
                   3699:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3700:           ($value, $string)=&str2arrayref($string);
                   3701:           if($value->[0] eq 'Array reference error') {
                   3702:               $hash{'error'}='Bad data';
                   3703:               return (\%hash, $string);
                   3704:           }
                   3705:       } else {
                   3706: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3707:       }
                   3708:       $string =~ s/^&//;
                   3709: 
                   3710:       $hash{$key}=$value;
1.204     albertel 3711:   }
1.265     albertel 3712: 
                   3713:   $string =~ s/^__END_HASH_REF__//;
                   3714: 
                   3715:   return (\%hash, $string);
1.204     albertel 3716: }
                   3717: 
                   3718: sub str2array {
1.265     albertel 3719:     my ($string)=@_;
                   3720:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3721:     return @$array;
                   3722: }
                   3723: 
                   3724: sub str2arrayref {
1.204     albertel 3725:   my ($string) = @_;
1.265     albertel 3726:   my @array;
                   3727: 
                   3728:   if($string !~ /^__ARRAY_REF__/) {
                   3729:       if (! ($string eq '' || !defined($string))) {
                   3730: 	  $array[0]='Array reference error';
                   3731:       }
                   3732:       return (\@array, $string);
                   3733:   }
                   3734: 
                   3735:   $string =~ s/^__ARRAY_REF__//;
                   3736: 
                   3737:   while($string !~ /^__END_ARRAY_REF__/) {
                   3738:       my $value='';
                   3739:       if($string =~ /^__HASH_REF__/) {
                   3740:           ($value, $string)=&str2hashref($string);
                   3741:           if(defined($value->{'error'})) {
                   3742:               $array[0] ='Array reference error';
                   3743:               return (\@array, $string);
                   3744:           }
                   3745:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3746:           ($value, $string)=&str2arrayref($string);
                   3747:           if($value->[0] eq 'Array reference error') {
                   3748:               $array[0] ='Array reference error';
                   3749:               return (\@array, $string);
                   3750:           }
                   3751:       } else {
                   3752: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3753:       }
                   3754:       $string =~ s/^&//;
                   3755: 
                   3756:       push(@array, $value);
1.191     harris41 3757:   }
1.265     albertel 3758: 
                   3759:   $string =~ s/^__END_ARRAY_REF__//;
                   3760: 
                   3761:   return (\@array, $string);
1.168     albertel 3762: }
                   3763: 
1.167     albertel 3764: # -------------------------------------------------------------------Temp Store
                   3765: 
1.168     albertel 3766: sub tmpreset {
                   3767:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3768:   if (!$symb) {
                   3769:     $symb=&symbread();
1.620     albertel 3770:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3771:   }
                   3772:   $symb=escape($symb);
                   3773: 
1.620     albertel 3774:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3775:   $namespace=~s/\//\_/g;
                   3776:   $namespace=~s/\W//g;
                   3777: 
1.620     albertel 3778:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3779:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3780:   if ($domain eq 'public' && $stuname eq 'public') {
                   3781:       $stuname=$ENV{'REMOTE_ADDR'};
                   3782:   }
1.1117    foxr     3783:   my $path=LONCAPA::tempdir();
1.168     albertel 3784:   my %hash;
                   3785:   if (tie(%hash,'GDBM_File',
                   3786: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3787: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3788:     foreach my $key (keys(%hash)) {
1.180     albertel 3789:       if ($key=~ /:$symb/) {
1.168     albertel 3790: 	delete($hash{$key});
                   3791:       }
                   3792:     }
                   3793:   }
                   3794: }
                   3795: 
1.167     albertel 3796: sub tmpstore {
1.168     albertel 3797:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3798: 
                   3799:   if (!$symb) {
                   3800:     $symb=&symbread();
1.620     albertel 3801:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3802:   }
                   3803:   $symb=escape($symb);
                   3804: 
                   3805:   if (!$namespace) {
                   3806:     # I don't think we would ever want to store this for a course.
                   3807:     # it seems this will only be used if we don't have a course.
1.620     albertel 3808:     #$namespace=$env{'request.course.id'};
1.168     albertel 3809:     #if (!$namespace) {
1.620     albertel 3810:       $namespace=$env{'request.state'};
1.168     albertel 3811:     #}
                   3812:   }
                   3813:   $namespace=~s/\//\_/g;
                   3814:   $namespace=~s/\W//g;
1.620     albertel 3815:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3816:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3817:   if ($domain eq 'public' && $stuname eq 'public') {
                   3818:       $stuname=$ENV{'REMOTE_ADDR'};
                   3819:   }
1.168     albertel 3820:   my $now=time;
                   3821:   my %hash;
1.1117    foxr     3822:   my $path=LONCAPA::tempdir();
1.168     albertel 3823:   if (tie(%hash,'GDBM_File',
                   3824: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3825: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3826:     $hash{"version:$symb"}++;
                   3827:     my $version=$hash{"version:$symb"};
                   3828:     my $allkeys=''; 
                   3829:     foreach my $key (keys(%$storehash)) {
                   3830:       $allkeys.=$key.':';
1.591     albertel 3831:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3832:     }
                   3833:     $hash{"$version:$symb:timestamp"}=$now;
                   3834:     $allkeys.='timestamp';
                   3835:     $hash{"$version:keys:$symb"}=$allkeys;
                   3836:     if (untie(%hash)) {
                   3837:       return 'ok';
                   3838:     } else {
                   3839:       return "error:$!";
                   3840:     }
                   3841:   } else {
                   3842:     return "error:$!";
                   3843:   }
                   3844: }
1.167     albertel 3845: 
1.168     albertel 3846: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3847: 
1.168     albertel 3848: sub tmprestore {
                   3849:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3850: 
1.168     albertel 3851:   if (!$symb) {
                   3852:     $symb=&symbread();
1.620     albertel 3853:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3854:   }
                   3855:   $symb=escape($symb);
                   3856: 
1.620     albertel 3857:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3858: 
1.620     albertel 3859:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3860:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3861:   if ($domain eq 'public' && $stuname eq 'public') {
                   3862:       $stuname=$ENV{'REMOTE_ADDR'};
                   3863:   }
1.168     albertel 3864:   my %returnhash;
                   3865:   $namespace=~s/\//\_/g;
                   3866:   $namespace=~s/\W//g;
                   3867:   my %hash;
1.1117    foxr     3868:   my $path=LONCAPA::tempdir();
1.168     albertel 3869:   if (tie(%hash,'GDBM_File',
                   3870: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3871: 	  &GDBM_READER(),0640)) {
1.168     albertel 3872:     my $version=$hash{"version:$symb"};
                   3873:     $returnhash{'version'}=$version;
                   3874:     my $scope;
                   3875:     for ($scope=1;$scope<=$version;$scope++) {
                   3876:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3877:       my @keys=split(/:/,$vkeys);
                   3878:       my $key;
                   3879:       $returnhash{"$scope:keys"}=$vkeys;
                   3880:       foreach $key (@keys) {
1.591     albertel 3881: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3882: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3883:       }
                   3884:     }
1.168     albertel 3885:     if (!(untie(%hash))) {
                   3886:       return "error:$!";
                   3887:     }
                   3888:   } else {
                   3889:     return "error:$!";
                   3890:   }
                   3891:   return %returnhash;
1.167     albertel 3892: }
                   3893: 
1.9       www      3894: # ----------------------------------------------------------------------- Store
                   3895: 
                   3896: sub store {
1.124     www      3897:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3898:     my $home='';
                   3899: 
1.168     albertel 3900:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3901: 
1.213     www      3902:     $symb=&symbclean($symb);
1.122     albertel 3903:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3904: 
1.620     albertel 3905:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3906:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3907: 
                   3908:     &devalidate($symb,$stuname,$domain);
1.109     www      3909: 
                   3910:     $symb=escape($symb);
1.187     www      3911:     if (!$namespace) { 
1.620     albertel 3912:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3913:           return ''; 
                   3914:        } 
                   3915:     }
1.620     albertel 3916:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3917: 
                   3918:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3919:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3920: 
1.12      www      3921:     my $namevalue='';
1.800     albertel 3922:     foreach my $key (keys(%$storehash)) {
                   3923:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3924:     }
1.12      www      3925:     $namevalue=~s/\&$//;
1.187     www      3926:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3927:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3928: }
                   3929: 
1.47      www      3930: # -------------------------------------------------------------- Critical Store
                   3931: 
                   3932: sub cstore {
1.124     www      3933:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3934:     my $home='';
                   3935: 
1.168     albertel 3936:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3937: 
1.213     www      3938:     $symb=&symbclean($symb);
1.122     albertel 3939:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3940: 
1.620     albertel 3941:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3942:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3943: 
                   3944:     &devalidate($symb,$stuname,$domain);
1.109     www      3945: 
                   3946:     $symb=escape($symb);
1.187     www      3947:     if (!$namespace) { 
1.620     albertel 3948:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3949:           return ''; 
                   3950:        } 
                   3951:     }
1.620     albertel 3952:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3953: 
                   3954:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3955:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3956: 
1.47      www      3957:     my $namevalue='';
1.800     albertel 3958:     foreach my $key (keys(%$storehash)) {
                   3959:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3960:     }
1.47      www      3961:     $namevalue=~s/\&$//;
1.187     www      3962:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3963:     return critical
                   3964:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3965: }
                   3966: 
1.9       www      3967: # --------------------------------------------------------------------- Restore
                   3968: 
                   3969: sub restore {
1.124     www      3970:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3971:     my $home='';
                   3972: 
1.168     albertel 3973:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3974: 
1.122     albertel 3975:     if (!$symb) {
                   3976:       unless ($symb=escape(&symbread())) { return ''; }
                   3977:     } else {
1.213     www      3978:       $symb=&escape(&symbclean($symb));
1.122     albertel 3979:     }
1.188     www      3980:     if (!$namespace) { 
1.620     albertel 3981:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3982:           return ''; 
                   3983:        } 
                   3984:     }
1.620     albertel 3985:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3986:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3987:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3988:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3989: 
1.12      www      3990:     my %returnhash=();
1.800     albertel 3991:     foreach my $line (split(/\&/,$answer)) {
                   3992: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3993:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3994:     }
1.75      www      3995:     my $version;
                   3996:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3997:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3998:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3999:        }
1.75      www      4000:     }
1.13      www      4001:     return %returnhash;
1.34      www      4002: }
                   4003: 
                   4004: # ---------------------------------------------------------- Course Description
1.1118    foxr     4005: #
                   4006: #  
1.34      www      4007: 
                   4008: sub coursedescription {
1.731     albertel 4009:     my ($courseid,$args)=@_;
1.34      www      4010:     $courseid=~s/^\///;
1.49      www      4011:     $courseid=~s/\_/\//g;
1.34      www      4012:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4013:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4014:     my $normalid=$cdomain.'_'.$cnum;
                   4015:     # need to always cache even if we get errors otherwise we keep 
                   4016:     # trying and trying and trying to get the course description.
                   4017:     my %envhash=();
                   4018:     my %returnhash=();
1.731     albertel 4019:     
                   4020:     my $expiretime=600;
                   4021:     if ($env{'request.course.id'} eq $normalid) {
                   4022: 	$expiretime=120;
                   4023:     }
                   4024: 
                   4025:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4026:     if (!$args->{'freshen_cache'}
                   4027: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4028: 	foreach my $key (keys(%env)) {
                   4029: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4030: 	    my ($setting) = $1;
                   4031: 	    $returnhash{$setting} = $env{$key};
                   4032: 	}
                   4033: 	return %returnhash;
                   4034:     }
                   4035: 
1.1118    foxr     4036:     # get the data again
                   4037: 
1.731     albertel 4038:     if (!$args->{'one_time'}) {
                   4039: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4040:     }
1.811     albertel 4041: 
1.34      www      4042:     if ($chome ne 'no_host') {
1.302     albertel 4043:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4044:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4045: 	   my $username = $env{'user.name'}; # Defult username
                   4046: 	   if(defined $args->{'user'}) {
                   4047: 	       $username = $args->{'user'};
                   4048: 	   }
1.129     albertel 4049:            $returnhash{'home'}= $chome;
                   4050: 	   $returnhash{'domain'} = $cdomain;
                   4051: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4052:            if (!defined($returnhash{'type'})) {
                   4053:                $returnhash{'type'} = 'Course';
                   4054:            }
1.130     albertel 4055:            while (my ($name,$value) = each %returnhash) {
1.53      www      4056:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4057:            }
1.270     www      4058:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4059:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4060: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4061:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4062:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4063:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4064:        }
                   4065:     }
1.731     albertel 4066:     if (!$args->{'one_time'}) {
1.949     raeburn  4067: 	&appenv(\%envhash);
1.731     albertel 4068:     }
1.302     albertel 4069:     return %returnhash;
1.461     www      4070: }
                   4071: 
1.1080    raeburn  4072: sub update_released_required {
                   4073:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4074:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4075:         $cid = $env{'request.course.id'};
                   4076:         $cdom = $env{'course.'.$cid.'.domain'};
                   4077:         $cnum = $env{'course.'.$cid.'.num'};
                   4078:         $chome = $env{'course.'.$cid.'.home'};
                   4079:     }
                   4080:     if ($needsrelease) {
                   4081:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4082:         my $needsupdate;
                   4083:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4084:             $needsupdate = 1;
                   4085:         } else {
                   4086:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4087:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4088:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4089:                 $needsupdate = 1;
                   4090:             }
                   4091:         }
                   4092:         if ($needsupdate) {
                   4093:             my %needshash = (
                   4094:                              'internal.releaserequired' => $needsrelease,
                   4095:                             );
                   4096:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4097:             if ($putresult eq 'ok') {
                   4098:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4099:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4100:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4101:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4102:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4103:                 }
                   4104:             }
                   4105:         }
                   4106:     }
                   4107:     return;
                   4108: }
                   4109: 
1.461     www      4110: # -------------------------------------------------See if a user is privileged
                   4111: 
                   4112: sub privileged {
                   4113:     my ($username,$domain)=@_;
                   4114:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4115: 			&homeserver($username,$domain));
1.1033    raeburn  4116:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4117:         ($rolesdump =~ /^error:/)) {
                   4118:         return 0;
                   4119:     }
1.461     www      4120:     my $now=time;
                   4121:     if ($rolesdump ne '') {
1.800     albertel 4122:         foreach my $entry (split(/&/,$rolesdump)) {
                   4123: 	    if ($entry!~/^rolesdef_/) {
                   4124: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4125: 		$area=~s/\_\w\w$//;
                   4126: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4127: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4128: 		    my $active=1;
                   4129: 		    if ($tend) {
                   4130: 			if ($tend<$now) { $active=0; }
                   4131: 		    }
                   4132: 		    if ($tstart) {
                   4133: 			if ($tstart>$now) { $active=0; }
                   4134: 		    }
                   4135: 		    if ($active) { return 1; }
                   4136: 		}
                   4137: 	    }
                   4138: 	}
                   4139:     }
                   4140:     return 0;
1.9       www      4141: }
1.1       albertel 4142: 
1.103     harris41 4143: # -------------------------------------------------------- Get user privileges
1.11      www      4144: 
                   4145: sub rolesinit {
                   4146:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4147:     my $now=time;
                   4148:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4149:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4150:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4151:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4152:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4153:         return \%userroles;
                   4154:     }
1.11      www      4155:     my %allroles=();
1.678     raeburn  4156:     my %allgroups=();   
1.11      www      4157: 
                   4158:     if ($rolesdump ne '') {
1.800     albertel 4159:         foreach my $entry (split(/&/,$rolesdump)) {
                   4160: 	  if ($entry!~/^rolesdef_/) {
                   4161:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4162: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4163:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4164: 	    if ($role=~/^cr/) { 
1.807     albertel 4165: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4166: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4167: 		    ($tend,$tstart)=split('_',$trest);
                   4168: 		} else {
                   4169: 		    $trole=$role;
                   4170: 		}
1.678     raeburn  4171:             } elsif ($role =~ m|^gr/|) {
                   4172:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4173:                 next if ($tstart eq '-1');
1.678     raeburn  4174:                 ($trole,$group_privs) = split(/\//,$trole);
                   4175:                 $group_privs = &unescape($group_privs);
1.587     albertel 4176: 	    } else {
                   4177: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4178: 	    }
1.743     albertel 4179: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4180: 					 $username);
                   4181: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4182:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4183:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4184:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4185: 		my $spec=$trole.'.'.$area;
                   4186: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4187: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4188:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4189:                 } elsif ($trole eq 'gr') {
                   4190:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4191: 		} else {
1.567     raeburn  4192:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4193: 		}
1.12      www      4194:             }
1.662     raeburn  4195:           }
1.191     harris41 4196:         }
1.743     albertel 4197:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4198:         $userroles{'user.adv'}    = $adv;
                   4199: 	$userroles{'user.author'} = $author;
1.620     albertel 4200:         $env{'user.adv'}=$adv;
1.11      www      4201:     }
1.743     albertel 4202:     return \%userroles;  
1.11      www      4203: }
                   4204: 
1.567     raeburn  4205: sub set_arearole {
                   4206:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4207: # log the associated role with the area
                   4208:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4209:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4210: }
                   4211: 
                   4212: sub custom_roleprivs {
                   4213:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4214:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4215:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4216:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4217:         my ($rdummy,$roledef)=
                   4218:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4219:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4220:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4221:             if (defined($syspriv)) {
1.1043    raeburn  4222:                 if ($trest =~ /^$match_community$/) {
                   4223:                     $syspriv =~ s/bre\&S//; 
                   4224:                 }
1.567     raeburn  4225:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4226:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4227:             }
                   4228:             if ($tdomain ne '') {
                   4229:                 if (defined($dompriv)) {
                   4230:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4231:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4232:                 }
                   4233:                 if (($trest ne '') && (defined($coursepriv))) {
                   4234:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4235:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4236:                 }
                   4237:             }
                   4238:         }
                   4239:     }
                   4240: }
                   4241: 
1.678     raeburn  4242: sub group_roleprivs {
                   4243:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4244:     my $access = 1;
                   4245:     my $now = time;
                   4246:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4247:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4248:     if ($access) {
1.811     albertel 4249:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4250:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4251:     }
                   4252: }
1.567     raeburn  4253: 
                   4254: sub standard_roleprivs {
                   4255:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4256:     if (defined($pr{$trole.':s'})) {
                   4257:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4258:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4259:     }
                   4260:     if ($tdomain ne '') {
                   4261:         if (defined($pr{$trole.':d'})) {
                   4262:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4263:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4264:         }
                   4265:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4266:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4267:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4268:         }
                   4269:     }
                   4270: }
                   4271: 
                   4272: sub set_userprivs {
1.1064    raeburn  4273:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4274:     my $author=0;
                   4275:     my $adv=0;
1.678     raeburn  4276:     my %grouproles = ();
                   4277:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4278:         my @groupkeys; 
1.1000    raeburn  4279:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4280:             push(@groupkeys,$role);
                   4281:         }
                   4282:         if (ref($groups_roles) eq 'HASH') {
                   4283:             foreach my $key (keys(%{$groups_roles})) {
                   4284:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4285:                     push(@groupkeys,$key);
                   4286:                 }
                   4287:             }
                   4288:         }
                   4289:         if (@groupkeys > 0) {
                   4290:             foreach my $role (@groupkeys) {
                   4291:                 my ($trole,$area,$sec,$extendedarea);
                   4292:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4293:                     $trole = $1;
                   4294:                     $area = $2;
                   4295:                     $sec = $3;
                   4296:                     $extendedarea = $area.$sec;
                   4297:                     if (exists($$allgroups{$area})) {
                   4298:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4299:                             my $spec = $trole.'.'.$extendedarea;
                   4300:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4301:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4302:                         }
1.678     raeburn  4303:                     }
                   4304:                 }
                   4305:             }
                   4306:         }
                   4307:     }
1.800     albertel 4308:     foreach my $group (keys(%grouproles)) {
                   4309:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4310:     }
1.800     albertel 4311:     foreach my $role (keys(%{$allroles})) {
                   4312:         my %thesepriv;
1.941     raeburn  4313:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4314:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4315:             if ($item ne '') {
                   4316:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4317:                 if ($restrictions eq '') {
                   4318:                     $thesepriv{$privilege}='F';
                   4319:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4320:                     $thesepriv{$privilege}.=$restrictions;
                   4321:                 }
                   4322:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4323:             }
                   4324:         }
                   4325:         my $thesestr='';
1.1104    raeburn  4326:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4327: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4328: 	}
                   4329:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4330:     }
                   4331:     return ($author,$adv);
                   4332: }
                   4333: 
1.994     raeburn  4334: sub role_status {
1.1104    raeburn  4335:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4336:     my @pwhere = ();
                   4337:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4338:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4339:         unless (!defined($$role) || $$role eq '') {
                   4340:             $$where=join('.',@pwhere);
                   4341:             $$trolecode=$$role.'.'.$$where;
                   4342:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4343:             $$tstatus='is';
1.1104    raeburn  4344:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4345:                 $$tstatus='future';
1.1034    raeburn  4346:                 if ($$tstart<$now) {
                   4347:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4348:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4349:                             my (%allroles,%allgroups,$group_privs,
                   4350:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4351:                             my %userroles = (
                   4352:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4353:                             );
1.1064    raeburn  4354:                             @rolecodes = ('cm'); 
1.1002    raeburn  4355:                             my $spec=$$role.'.'.$$where;
                   4356:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4357:                             if ($$role =~ /^cr\//) {
                   4358:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4359:                                 push(@rolecodes,'cr');
1.1002    raeburn  4360:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4361:                                 push(@rolecodes,$$role);
1.1002    raeburn  4362:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4363:                                                     $env{'user.name'});
1.1064    raeburn  4364:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4365:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4366:                                 $group_privs = &unescape($group_privs);
                   4367:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4368:                                 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  4369:                                 &get_groups_roles($tdomain,$trest,
                   4370:                                                   \%course_roles,\@rolecodes,
                   4371:                                                   \%groups_roles);
1.1002    raeburn  4372:                             } else {
1.1064    raeburn  4373:                                 push(@rolecodes,$$role);
1.1002    raeburn  4374:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4375:                             }
1.1064    raeburn  4376:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4377:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4378:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4379:                         }
                   4380:                     }
1.1034    raeburn  4381:                     $$tstatus = 'is';
1.1002    raeburn  4382:                 }
1.994     raeburn  4383:             }
                   4384:             if ($$tend) {
1.1104    raeburn  4385:                 if ($$tend<$update) {
1.994     raeburn  4386:                     $$tstatus='expired';
                   4387:                 } elsif ($$tend<$now) {
                   4388:                     $$tstatus='will_not';
                   4389:                 }
                   4390:             }
                   4391:         }
                   4392:     }
                   4393: }
                   4394: 
1.1104    raeburn  4395: sub get_groups_roles {
                   4396:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4397:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4398:                   (ref($rolecodes) eq 'ARRAY') && 
                   4399:                   (ref($groups_roles) eq 'HASH')); 
                   4400:     if (keys(%{$cdom_courseroles}) > 0) {
                   4401:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4402:         if ($cdom ne '' && $cnum ne '') {
                   4403:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4404:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4405:                     my $crsrole = $1;
                   4406:                     my $crssec = $2;
                   4407:                     if ($crsrole =~ /^cr/) {
                   4408:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4409:                             push(@{$rolecodes},'cr');
                   4410:                         }
                   4411:                     } else {
                   4412:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4413:                             push(@{$rolecodes},$crsrole);
                   4414:                         }
                   4415:                     }
                   4416:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4417:                     if ($crssec ne '') {
                   4418:                         $rolekey .= "/$crssec";
                   4419:                     }
                   4420:                     $rolekey .= './';
                   4421:                     $groups_roles->{$rolekey} = $rolecodes;
                   4422:                 }
                   4423:             }
                   4424:         }
                   4425:     }
                   4426:     return;
                   4427: }
                   4428: 
                   4429: sub delete_env_groupprivs {
                   4430:     my ($where,$courseroles,$possroles) = @_;
                   4431:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4432:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4433:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4434:         %{$courseroles->{$udom}} =
                   4435:             &get_my_roles('','','userroles',['active'],
                   4436:                           $possroles,[$udom],1);
                   4437:     }
                   4438:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4439:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4440:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4441:             my $area = '/'.$cdom.'/'.$cnum;
                   4442:             my $privkey = "user.priv.$crsrole.$area";
                   4443:             if ($crssec ne '') {
                   4444:                 $privkey .= '/'.$crssec;
                   4445:             }
                   4446:             $privkey .= ".$area/$group";
                   4447:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4448:         }
                   4449:     }
                   4450:     return;
                   4451: }
                   4452: 
1.994     raeburn  4453: sub check_adhoc_privs {
1.1104    raeburn  4454:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4455:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4456:     if ($env{$cckey}) {
                   4457:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4458:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4459:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4460:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4461:         }
                   4462:     } else {
1.1088    raeburn  4463:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4464:     }
                   4465: }
                   4466: 
                   4467: sub set_adhoc_privileges {
                   4468: # role can be cc or ca
1.1088    raeburn  4469:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4470:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4471:     my $spec = $role.'.'.$area;
                   4472:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4473:                                   $env{'user.name'});
                   4474:     my %ccrole = ();
                   4475:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4476:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4477:     &appenv(\%userroles,[$role,'cm']);
                   4478:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4479:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4480:         &appenv( {'request.role'        => $spec,
                   4481:                   'request.role.domain' => $dcdom,
                   4482:                   'request.course.sec'  => ''
                   4483:                  }
                   4484:                );
                   4485:         my $tadv=0;
                   4486:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4487:         &appenv({'request.role.adv'    => $tadv});
                   4488:     }
1.994     raeburn  4489: }
                   4490: 
1.12      www      4491: # --------------------------------------------------------------- get interface
                   4492: 
                   4493: sub get {
1.131     albertel 4494:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4495:    my $items='';
1.800     albertel 4496:    foreach my $item (@$storearr) {
                   4497:        $items.=&escape($item).'&';
1.191     harris41 4498:    }
1.12      www      4499:    $items=~s/\&$//;
1.620     albertel 4500:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4501:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4502:    my $uhome=&homeserver($uname,$udomain);
                   4503: 
1.133     albertel 4504:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4505:    my @pairs=split(/\&/,$rep);
1.273     albertel 4506:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4507:      return @pairs;
                   4508:    }
1.15      www      4509:    my %returnhash=();
1.42      www      4510:    my $i=0;
1.800     albertel 4511:    foreach my $item (@$storearr) {
                   4512:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4513:       $i++;
1.191     harris41 4514:    }
1.15      www      4515:    return %returnhash;
1.27      www      4516: }
                   4517: 
                   4518: # --------------------------------------------------------------- del interface
                   4519: 
                   4520: sub del {
1.133     albertel 4521:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4522:    my $items='';
1.800     albertel 4523:    foreach my $item (@$storearr) {
                   4524:        $items.=&escape($item).'&';
1.191     harris41 4525:    }
1.984     neumanie 4526: 
1.27      www      4527:    $items=~s/\&$//;
1.620     albertel 4528:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4529:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4530:    my $uhome=&homeserver($uname,$udomain);
                   4531:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4532: }
                   4533: 
                   4534: # -------------------------------------------------------------- dump interface
                   4535: 
                   4536: sub dump {
1.1086    raeburn  4537:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4538:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4539:     if (!$uname) { $uname=$env{'user.name'}; }
                   4540:     my $uhome=&homeserver($uname,$udomain);
                   4541:     if ($regexp) {
                   4542: 	$regexp=&escape($regexp);
                   4543:     } else {
                   4544: 	$regexp='.';
                   4545:     }
1.1086    raeburn  4546:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4547:     my @pairs=split(/\&/,$rep);
                   4548:     my %returnhash=();
1.1098    foxr     4549:     if (!($rep =~ /^error/ )) {
                   4550: 	foreach my $item (@pairs) {
                   4551: 	    my ($key,$value)=split(/=/,$item,2);
                   4552: 	    $key = &unescape($key);
                   4553: 	    next if ($key =~ /^error: 2 /);
                   4554: 	    $returnhash{$key}=&thaw_unescape($value);
                   4555: 	}
1.755     albertel 4556:     }
                   4557:     return %returnhash;
1.407     www      4558: }
                   4559: 
1.1098    foxr     4560: 
1.717     albertel 4561: # --------------------------------------------------------- dumpstore interface
                   4562: 
                   4563: sub dumpstore {
                   4564:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4565:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4566:    if (!$uname) { $uname=$env{'user.name'}; }
                   4567:    my $uhome=&homeserver($uname,$udomain);
                   4568:    if ($regexp) {
                   4569:        $regexp=&escape($regexp);
                   4570:    } else {
                   4571:        $regexp='.';
                   4572:    }
                   4573:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4574:    my @pairs=split(/\&/,$rep);
                   4575:    my %returnhash=();
                   4576:    foreach my $item (@pairs) {
                   4577:        my ($key,$value)=split(/=/,$item,2);
                   4578:        next if ($key =~ /^error: 2 /);
                   4579:        $returnhash{$key}=&thaw_unescape($value);
                   4580:    }
                   4581:    return %returnhash;
1.717     albertel 4582: }
                   4583: 
1.407     www      4584: # -------------------------------------------------------------- keys interface
                   4585: 
                   4586: sub getkeys {
                   4587:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4588:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4589:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4590:    my $uhome=&homeserver($uname,$udomain);
                   4591:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4592:    my @keyarray=();
1.800     albertel 4593:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4594:       next if ($key =~ /^error: 2 /);
1.800     albertel 4595:       push(@keyarray,&unescape($key));
1.407     www      4596:    }
                   4597:    return @keyarray;
1.318     matthew  4598: }
                   4599: 
1.319     matthew  4600: # --------------------------------------------------------------- currentdump
                   4601: sub currentdump {
1.328     matthew  4602:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4603:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4604:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4605:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4606:    my $uhome = &homeserver($sname,$sdom);
                   4607:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4608:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4609:    #
1.318     matthew  4610:    my %returnhash=();
1.319     matthew  4611:    #
                   4612:    if ($rep eq "unknown_cmd") { 
                   4613:        # an old lond will not know currentdump
                   4614:        # Do a dump and make it look like a currentdump
1.822     albertel 4615:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4616:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4617:        my %hash = @tmp;
                   4618:        @tmp=();
1.424     matthew  4619:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4620:    } else {
                   4621:        my @pairs=split(/\&/,$rep);
1.800     albertel 4622:        foreach my $pair (@pairs) {
                   4623:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4624:            my ($symb,$param) = split(/:/,$key);
                   4625:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4626:                                                         &thaw_unescape($value);
1.319     matthew  4627:        }
1.191     harris41 4628:    }
1.12      www      4629:    return %returnhash;
1.424     matthew  4630: }
                   4631: 
                   4632: sub convert_dump_to_currentdump{
                   4633:     my %hash = %{shift()};
                   4634:     my %returnhash;
                   4635:     # Code ripped from lond, essentially.  The only difference
                   4636:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4637:     # we might run in to problems with parameter names =~ /^v\./
                   4638:     while (my ($key,$value) = each(%hash)) {
                   4639:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4640: 	$symb  = &unescape($symb);
                   4641: 	$param = &unescape($param);
1.424     matthew  4642:         next if ($v eq 'version' || $symb eq 'keys');
                   4643:         next if (exists($returnhash{$symb}) &&
                   4644:                  exists($returnhash{$symb}->{$param}) &&
                   4645:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4646:         $returnhash{$symb}->{$param}=$value;
                   4647:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4648:     }
                   4649:     #
                   4650:     # Remove all of the keys in the hashes which keep track of
                   4651:     # the version of the parameter.
                   4652:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4653:         # use a foreach because we are going to delete from the hash.
                   4654:         foreach my $key (keys(%$param_hash)) {
                   4655:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4656:         }
                   4657:     }
                   4658:     return \%returnhash;
1.12      www      4659: }
                   4660: 
1.627     albertel 4661: # ------------------------------------------------------ critical inc interface
                   4662: 
                   4663: sub cinc {
                   4664:     return &inc(@_,'critical');
                   4665: }
                   4666: 
1.449     matthew  4667: # --------------------------------------------------------------- inc interface
                   4668: 
                   4669: sub inc {
1.627     albertel 4670:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4671:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4672:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4673:     my $uhome=&homeserver($uname,$udomain);
                   4674:     my $items='';
                   4675:     if (! ref($store)) {
                   4676:         # got a single value, so use that instead
                   4677:         $items = &escape($store).'=&';
                   4678:     } elsif (ref($store) eq 'SCALAR') {
                   4679:         $items = &escape($$store).'=&';        
                   4680:     } elsif (ref($store) eq 'ARRAY') {
                   4681:         $items = join('=&',map {&escape($_);} @{$store});
                   4682:     } elsif (ref($store) eq 'HASH') {
                   4683:         while (my($key,$value) = each(%{$store})) {
                   4684:             $items.= &escape($key).'='.&escape($value).'&';
                   4685:         }
                   4686:     }
                   4687:     $items=~s/\&$//;
1.627     albertel 4688:     if ($critical) {
                   4689: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4690:     } else {
                   4691: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4692:     }
1.449     matthew  4693: }
                   4694: 
1.12      www      4695: # --------------------------------------------------------------- put interface
                   4696: 
                   4697: sub put {
1.134     albertel 4698:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4699:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4700:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4701:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4702:    my $items='';
1.800     albertel 4703:    foreach my $item (keys(%$storehash)) {
                   4704:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4705:    }
1.12      www      4706:    $items=~s/\&$//;
1.134     albertel 4707:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4708: }
                   4709: 
1.631     albertel 4710: # ------------------------------------------------------------ newput interface
                   4711: 
                   4712: sub newput {
                   4713:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4714:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4715:    if (!$uname) { $uname=$env{'user.name'}; }
                   4716:    my $uhome=&homeserver($uname,$udomain);
                   4717:    my $items='';
                   4718:    foreach my $key (keys(%$storehash)) {
                   4719:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4720:    }
                   4721:    $items=~s/\&$//;
                   4722:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4723: }
                   4724: 
                   4725: # ---------------------------------------------------------  putstore interface
                   4726: 
1.524     raeburn  4727: sub putstore {
1.715     albertel 4728:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4729:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4730:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4731:    my $uhome=&homeserver($uname,$udomain);
                   4732:    my $items='';
1.715     albertel 4733:    foreach my $key (keys(%$storehash)) {
                   4734:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4735:    }
1.715     albertel 4736:    $items=~s/\&$//;
1.716     albertel 4737:    my $esc_symb=&escape($symb);
                   4738:    my $esc_v=&escape($version);
1.715     albertel 4739:    my $reply =
1.716     albertel 4740:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4741: 	      $uhome);
                   4742:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4743:        # gfall back to way things use to be done
1.715     albertel 4744:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4745: 			    $uname);
1.524     raeburn  4746:    }
1.715     albertel 4747:    return $reply;
                   4748: }
                   4749: 
                   4750: sub old_putstore {
1.716     albertel 4751:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4752:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4753:     if (!$uname) { $uname=$env{'user.name'}; }
                   4754:     my $uhome=&homeserver($uname,$udomain);
                   4755:     my %newstorehash;
1.800     albertel 4756:     foreach my $item (keys(%$storehash)) {
                   4757: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4758: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4759:     }
                   4760:     my $items='';
                   4761:     my %allitems = ();
1.800     albertel 4762:     foreach my $item (keys(%newstorehash)) {
                   4763: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4764: 	    my $key = $1.':keys:'.$2;
                   4765: 	    $allitems{$key} .= $3.':';
                   4766: 	}
1.800     albertel 4767: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4768:     }
1.800     albertel 4769:     foreach my $item (keys(%allitems)) {
                   4770: 	$allitems{$item} =~ s/\:$//;
                   4771: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4772:     }
                   4773:     $items=~s/\&$//;
                   4774:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4775: }
                   4776: 
1.47      www      4777: # ------------------------------------------------------ critical put interface
                   4778: 
                   4779: sub cput {
1.134     albertel 4780:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4781:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4782:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4783:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4784:    my $items='';
1.800     albertel 4785:    foreach my $item (keys(%$storehash)) {
                   4786:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4787:    }
1.47      www      4788:    $items=~s/\&$//;
1.134     albertel 4789:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4790: }
                   4791: 
                   4792: # -------------------------------------------------------------- eget interface
                   4793: 
                   4794: sub eget {
1.133     albertel 4795:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4796:    my $items='';
1.800     albertel 4797:    foreach my $item (@$storearr) {
                   4798:        $items.=&escape($item).'&';
1.191     harris41 4799:    }
1.12      www      4800:    $items=~s/\&$//;
1.620     albertel 4801:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4802:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4803:    my $uhome=&homeserver($uname,$udomain);
                   4804:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4805:    my @pairs=split(/\&/,$rep);
                   4806:    my %returnhash=();
1.42      www      4807:    my $i=0;
1.800     albertel 4808:    foreach my $item (@$storearr) {
                   4809:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4810:       $i++;
1.191     harris41 4811:    }
1.12      www      4812:    return %returnhash;
                   4813: }
                   4814: 
1.667     albertel 4815: # ------------------------------------------------------------ tmpput interface
                   4816: sub tmpput {
1.802     raeburn  4817:     my ($storehash,$server,$context)=@_;
1.667     albertel 4818:     my $items='';
1.800     albertel 4819:     foreach my $item (keys(%$storehash)) {
                   4820: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4821:     }
                   4822:     $items=~s/\&$//;
1.802     raeburn  4823:     if (defined($context)) {
                   4824:         $items .= ':'.&escape($context);
                   4825:     }
1.667     albertel 4826:     return &reply("tmpput:$items",$server);
                   4827: }
                   4828: 
                   4829: # ------------------------------------------------------------ tmpget interface
                   4830: sub tmpget {
1.688     albertel 4831:     my ($token,$server)=@_;
                   4832:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4833:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4834:     my %returnhash;
                   4835:     foreach my $item (split(/\&/,$rep)) {
                   4836: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4837:         next if ($key =~ /^error: 2 /);
1.667     albertel 4838: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4839:     }
                   4840:     return %returnhash;
                   4841: }
                   4842: 
1.1113    raeburn  4843: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4844: sub tmpdel {
                   4845:     my ($token,$server)=@_;
                   4846:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4847:     return &reply("tmpdel:$token",$server);
                   4848: }
                   4849: 
1.765     albertel 4850: # -------------------------------------------------- portfolio access checking
                   4851: 
                   4852: sub portfolio_access {
1.766     albertel 4853:     my ($requrl) = @_;
1.765     albertel 4854:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4855:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4856:     if ($result) {
                   4857:         my %setters;
                   4858:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4859:             my ($startblock,$endblock) =
                   4860:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4861:             if ($startblock && $endblock) {
                   4862:                 return 'B';
                   4863:             }
                   4864:         } else {
                   4865:             my ($startblock,$endblock) =
                   4866:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4867:             if ($startblock && $endblock) {
                   4868:                 return 'B';
                   4869:             }
                   4870:         }
                   4871:     }
1.765     albertel 4872:     if ($result eq 'ok') {
1.766     albertel 4873:        return 'F';
1.765     albertel 4874:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4875:        return 'A';
1.765     albertel 4876:     }
1.766     albertel 4877:     return '';
1.765     albertel 4878: }
                   4879: 
                   4880: sub get_portfolio_access {
1.767     albertel 4881:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4882: 
                   4883:     if (!ref($access_hash)) {
                   4884: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4885: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4886: 						   $file_name);
                   4887: 	$access_hash = $access_controls{$file_name};
                   4888:     }
                   4889: 
1.765     albertel 4890:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4891:     my $now = time;
                   4892:     if (ref($access_hash) eq 'HASH') {
                   4893:         foreach my $key (keys(%{$access_hash})) {
                   4894:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4895:             if ($start > $now) {
                   4896:                 next;
                   4897:             }
                   4898:             if ($end && $end<$now) {
                   4899:                 next;
                   4900:             }
                   4901:             if ($scope eq 'public') {
                   4902:                 $public = $key;
                   4903:                 last;
                   4904:             } elsif ($scope eq 'guest') {
                   4905:                 $guest = $key;
                   4906:             } elsif ($scope eq 'domains') {
                   4907:                 push(@domains,$key);
                   4908:             } elsif ($scope eq 'users') {
                   4909:                 push(@users,$key);
                   4910:             } elsif ($scope eq 'course') {
                   4911:                 push(@courses,$key);
                   4912:             } elsif ($scope eq 'group') {
                   4913:                 push(@groups,$key);
                   4914:             }
                   4915:         }
                   4916:         if ($public) {
                   4917:             return 'ok';
                   4918:         }
                   4919:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4920:             if ($guest) {
                   4921:                 return $guest;
                   4922:             }
                   4923:         } else {
                   4924:             if (@domains > 0) {
                   4925:                 foreach my $domkey (@domains) {
                   4926:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4927:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4928:                             return 'ok';
                   4929:                         }
                   4930:                     }
                   4931:                 }
                   4932:             }
                   4933:             if (@users > 0) {
                   4934:                 foreach my $userkey (@users) {
1.865     raeburn  4935:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4936:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4937:                             if (ref($item) eq 'HASH') {
                   4938:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4939:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4940:                                     return 'ok';
                   4941:                                 }
                   4942:                             }
                   4943:                         }
                   4944:                     } 
1.765     albertel 4945:                 }
                   4946:             }
                   4947:             my %roleshash;
                   4948:             my @courses_and_groups = @courses;
                   4949:             push(@courses_and_groups,@groups); 
                   4950:             if (@courses_and_groups > 0) {
                   4951:                 my (%allgroups,%allroles); 
                   4952:                 my ($start,$end,$role,$sec,$group);
                   4953:                 foreach my $envkey (%env) {
1.1060    raeburn  4954:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4955:                         my $cid = $2.'_'.$3; 
                   4956:                         if ($1 eq 'gr') {
                   4957:                             $group = $4;
                   4958:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4959:                         } else {
                   4960:                             if ($4 eq '') {
                   4961:                                 $sec = 'none';
                   4962:                             } else {
                   4963:                                 $sec = $4;
                   4964:                             }
                   4965:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4966:                         }
1.811     albertel 4967:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4968:                         my $cid = $2.'_'.$3;
                   4969:                         if ($4 eq '') {
                   4970:                             $sec = 'none';
                   4971:                         } else {
                   4972:                             $sec = $4;
                   4973:                         }
                   4974:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4975:                     }
                   4976:                 }
                   4977:                 if (keys(%allroles) == 0) {
                   4978:                     return;
                   4979:                 }
                   4980:                 foreach my $key (@courses_and_groups) {
                   4981:                     my %content = %{$$access_hash{$key}};
                   4982:                     my $cnum = $content{'number'};
                   4983:                     my $cdom = $content{'domain'};
                   4984:                     my $cid = $cdom.'_'.$cnum;
                   4985:                     if (!exists($allroles{$cid})) {
                   4986:                         next;
                   4987:                     }    
                   4988:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4989:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4990:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4991:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4992:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4993:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4994:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4995:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4996:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4997:                                         if (grep/^all$/,@sections) {
                   4998:                                             return 'ok';
                   4999:                                         } else {
                   5000:                                             if (grep/^$sec$/,@sections) {
                   5001:                                                 return 'ok';
                   5002:                                             }
                   5003:                                         }
                   5004:                                     }
                   5005:                                 }
                   5006:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5007:                                     if (grep/^none$/,@groups) {
                   5008:                                         return 'ok';
                   5009:                                     }
                   5010:                                 } else {
                   5011:                                     if (grep/^all$/,@groups) {
                   5012:                                         return 'ok';
                   5013:                                     } 
                   5014:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5015:                                         if (grep/^$group$/,@groups) {
                   5016:                                             return 'ok';
                   5017:                                         }
                   5018:                                     }
                   5019:                                 } 
                   5020:                             }
                   5021:                         }
                   5022:                     }
                   5023:                 }
                   5024:             }
                   5025:             if ($guest) {
                   5026:                 return $guest;
                   5027:             }
                   5028:         }
                   5029:     }
                   5030:     return;
                   5031: }
                   5032: 
                   5033: sub course_group_datechecker {
                   5034:     my ($dates,$now,$status) = @_;
                   5035:     my ($start,$end) = split(/\./,$dates);
                   5036:     if (!$start && !$end) {
                   5037:         return 'ok';
                   5038:     }
                   5039:     if (grep/^active$/,@{$status}) {
                   5040:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5041:             return 'ok';
                   5042:         }
                   5043:     }
                   5044:     if (grep/^previous$/,@{$status}) {
                   5045:         if ($end > $now ) {
                   5046:             return 'ok';
                   5047:         }
                   5048:     }
                   5049:     if (grep/^future$/,@{$status}) {
                   5050:         if ($start > $now) {
                   5051:             return 'ok';
                   5052:         }
                   5053:     }
                   5054:     return; 
                   5055: }
                   5056: 
                   5057: sub parse_portfolio_url {
                   5058:     my ($url) = @_;
                   5059: 
                   5060:     my ($type,$udom,$unum,$group,$file_name);
                   5061:     
1.823     albertel 5062:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5063: 	$type = 1;
                   5064:         $udom = $1;
                   5065:         $unum = $2;
                   5066:         $file_name = $3;
1.823     albertel 5067:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5068: 	$type = 2;
                   5069:         $udom = $1;
                   5070:         $unum = $2;
                   5071:         $group = $3;
                   5072:         $file_name = $3.'/'.$4;
                   5073:     }
                   5074:     if (wantarray) {
                   5075: 	return ($type,$udom,$unum,$file_name,$group);
                   5076:     }
                   5077:     return $type;
                   5078: }
                   5079: 
                   5080: sub is_portfolio_url {
                   5081:     my ($url) = @_;
                   5082:     return scalar(&parse_portfolio_url($url));
                   5083: }
                   5084: 
1.798     raeburn  5085: sub is_portfolio_file {
                   5086:     my ($file) = @_;
1.820     raeburn  5087:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5088:         return 1;
                   5089:     }
                   5090:     return;
                   5091: }
                   5092: 
1.976     raeburn  5093: sub usertools_access {
1.1084    raeburn  5094:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5095:     my ($access,%tools);
                   5096:     if ($context eq '') {
                   5097:         $context = 'tools';
                   5098:     }
                   5099:     if ($context eq 'requestcourses') {
                   5100:         %tools = (
                   5101:                       official   => 1,
                   5102:                       unofficial => 1,
1.1006    raeburn  5103:                       community  => 1,
1.985     raeburn  5104:                  );
                   5105:     } else {
                   5106:         %tools = (
                   5107:                       aboutme   => 1,
                   5108:                       blog      => 1,
                   5109:                       portfolio => 1,
                   5110:                  );
                   5111:     }
1.976     raeburn  5112:     return if (!defined($tools{$tool}));
                   5113: 
                   5114:     if ((!defined($udom)) || (!defined($uname))) {
                   5115:         $udom = $env{'user.domain'};
                   5116:         $uname = $env{'user.name'};
                   5117:     }
                   5118: 
1.978     raeburn  5119:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5120:         if ($action ne 'reload') {
1.985     raeburn  5121:             if ($context eq 'requestcourses') {
                   5122:                 return $env{'environment.canrequest.'.$tool};
                   5123:             } else {
                   5124:                 return $env{'environment.availabletools.'.$tool};
                   5125:             }
                   5126:         }
1.976     raeburn  5127:     }
                   5128: 
                   5129:     my ($toolstatus,$inststatus);
                   5130: 
1.985     raeburn  5131:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5132:          ($action ne 'reload')) {
                   5133:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5134:         $inststatus = $env{'environment.inststatus'};
                   5135:     } else {
1.1084    raeburn  5136:         if (ref($userenvref) eq 'HASH') {
                   5137:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5138:             $inststatus = $userenvref->{'inststatus'};
                   5139:         } else {
                   5140:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5141:             $toolstatus = $userenv{$context.'.'.$tool};
                   5142:             $inststatus = $userenv{'inststatus'};
                   5143:         }
1.976     raeburn  5144:     }
                   5145: 
                   5146:     if ($toolstatus ne '') {
                   5147:         if ($toolstatus) {
                   5148:             $access = 1;
                   5149:         } else {
                   5150:             $access = 0;
                   5151:         }
                   5152:         return $access;
                   5153:     }
                   5154: 
1.1084    raeburn  5155:     my ($is_adv,%domdef);
                   5156:     if (ref($is_advref) eq 'HASH') {
                   5157:         $is_adv = $is_advref->{'is_adv'};
                   5158:     } else {
                   5159:         $is_adv = &is_advanced_user($udom,$uname);
                   5160:     }
                   5161:     if (ref($domdefref) eq 'HASH') {
                   5162:         %domdef = %{$domdefref};
                   5163:     } else {
                   5164:         %domdef = &get_domain_defaults($udom);
                   5165:     }
1.976     raeburn  5166:     if (ref($domdef{$tool}) eq 'HASH') {
                   5167:         if ($is_adv) {
                   5168:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5169:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5170:                     $access = 1;
                   5171:                 } else {
                   5172:                     $access = 0;
                   5173:                 }
                   5174:                 return $access;
                   5175:             }
                   5176:         }
                   5177:         if ($inststatus ne '') {
                   5178:             my ($hasaccess,$hasnoaccess);
                   5179:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5180:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5181:                     if ($domdef{$tool}{$affiliation}) {
                   5182:                         $hasaccess = 1;
                   5183:                     } else {
                   5184:                         $hasnoaccess = 1;
                   5185:                     }
                   5186:                 }
                   5187:             }
                   5188:             if ($hasaccess || $hasnoaccess) {
                   5189:                 if ($hasaccess) {
                   5190:                     $access = 1;
                   5191:                 } elsif ($hasnoaccess) {
                   5192:                     $access = 0; 
                   5193:                 }
                   5194:                 return $access;
                   5195:             }
                   5196:         } else {
                   5197:             if ($domdef{$tool}{'default'} ne '') {
                   5198:                 if ($domdef{$tool}{'default'}) {
                   5199:                     $access = 1;
                   5200:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5201:                     $access = 0;
                   5202:                 }
                   5203:                 return $access;
                   5204:             }
                   5205:         }
                   5206:     } else {
1.985     raeburn  5207:         if ($context eq 'tools') {
                   5208:             $access = 1;
                   5209:         } else {
                   5210:             $access = 0;
                   5211:         }
1.976     raeburn  5212:         return $access;
                   5213:     }
                   5214: }
                   5215: 
1.1050    raeburn  5216: sub is_course_owner {
                   5217:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5218:     if (($udom eq '') || ($uname eq '')) {
                   5219:         $udom = $env{'user.domain'};
                   5220:         $uname = $env{'user.name'};
                   5221:     }
                   5222:     unless (($udom eq '') || ($uname eq '')) {
                   5223:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5224:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5225:                 return 1;
                   5226:             } else {
                   5227:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5228:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5229:                     return 1;
                   5230:                 }
                   5231:             }
                   5232:         }
                   5233:     }
                   5234:     return;
                   5235: }
                   5236: 
1.976     raeburn  5237: sub is_advanced_user {
                   5238:     my ($udom,$uname) = @_;
1.1085    raeburn  5239:     if ($udom ne '' && $uname ne '') {
                   5240:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5241:             return $env{'user.adv'};  
                   5242:         }
                   5243:     }
1.976     raeburn  5244:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5245:     my %allroles;
                   5246:     my $is_adv;
                   5247:     foreach my $role (keys(%roleshash)) {
                   5248:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5249:         my $area = '/'.$tdomain.'/'.$trest;
                   5250:         if ($sec ne '') {
                   5251:             $area .= '/'.$sec;
                   5252:         }
                   5253:         if (($area ne '') && ($trole ne '')) {
                   5254:             my $spec=$trole.'.'.$area;
                   5255:             if ($trole =~ /^cr\//) {
                   5256:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5257:             } elsif ($trole ne 'gr') {
                   5258:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5259:             }
                   5260:         }
                   5261:     }
                   5262:     foreach my $role (keys(%allroles)) {
                   5263:         last if ($is_adv);
                   5264:         foreach my $item (split(/:/,$allroles{$role})) {
                   5265:             if ($item ne '') {
                   5266:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5267:                 if ($privilege eq 'adv') {
                   5268:                     $is_adv = 1;
                   5269:                     last;
                   5270:                 }
                   5271:             }
                   5272:         }
                   5273:     }
                   5274:     return $is_adv;
                   5275: }
1.798     raeburn  5276: 
1.1035    raeburn  5277: sub check_can_request {
1.1036    raeburn  5278:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5279:     my $canreq = 0;
                   5280:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5281:     my @options = ('approval','validate','autolimit');
                   5282:     my $optregex = join('|',@options);
                   5283:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5284:         foreach my $type (@{$types}) {
                   5285:             if (&usertools_access($env{'user.name'},
                   5286:                                   $env{'user.domain'},
                   5287:                                   $type,undef,'requestcourses')) {
                   5288:                 $canreq ++;
1.1036    raeburn  5289:                 if (ref($request_domains) eq 'HASH') {
                   5290:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5291:                 }
1.1035    raeburn  5292:                 if ($dom eq $env{'user.domain'}) {
                   5293:                     $can_request->{$type} = 1;
                   5294:                 }
                   5295:             }
                   5296:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5297:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5298:                 if (@curr > 0) {
1.1036    raeburn  5299:                     foreach my $item (@curr) {
                   5300:                         if (ref($request_domains) eq 'HASH') {
                   5301:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5302:                             if ($otherdom ne '') {
                   5303:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5304:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5305:                                         push(@{$request_domains->{$type}},$otherdom);
                   5306:                                     }
                   5307:                                 } else {
                   5308:                                     push(@{$request_domains->{$type}},$otherdom);
                   5309:                                 }
                   5310:                             }
                   5311:                         }
                   5312:                     }
                   5313:                     unless($dom eq $env{'user.domain'}) {
                   5314:                         $canreq ++;
1.1035    raeburn  5315:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5316:                             $can_request->{$type} = 1;
                   5317:                         }
                   5318:                     }
                   5319:                 }
                   5320:             }
                   5321:         }
                   5322:     }
                   5323:     return $canreq;
                   5324: }
                   5325: 
1.341     www      5326: # ---------------------------------------------- Custom access rule evaluation
                   5327: 
                   5328: sub customaccess {
                   5329:     my ($priv,$uri)=@_;
1.807     albertel 5330:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5331:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5332:     $udom = &LONCAPA::clean_domain($udom);
                   5333:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5334:     my $access=0;
1.800     albertel 5335:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5336: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5337: 	if ($type eq 'user') {
                   5338: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5339: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5340: 		if ($tdom) {
                   5341: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5342: 		}
1.896     albertel 5343: 		if ($tuname) {
                   5344: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5345: 		}
                   5346: 		$access=($effect eq 'allow');
                   5347: 		last;
                   5348: 	    }
                   5349: 	} else {
                   5350: 	    if ($role) {
                   5351: 		if ($role ne $urole) { next; }
                   5352: 	    }
                   5353: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5354: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5355: 		if ($tdom) {
                   5356: 		    if ($tdom ne $udom) { next; }
                   5357: 		}
                   5358: 		if ($tcrs) {
                   5359: 		    if ($tcrs ne $ucrs) { next; }
                   5360: 		}
                   5361: 		if ($tsec) {
                   5362: 		    if ($tsec ne $usec) { next; }
                   5363: 		}
                   5364: 		$access=($effect eq 'allow');
                   5365: 		last;
                   5366: 	    }
                   5367: 	    if ($realm eq '' && $role eq '') {
                   5368: 		$access=($effect eq 'allow');
                   5369: 	    }
1.402     bowersj2 5370: 	}
1.341     www      5371:     }
                   5372:     return $access;
                   5373: }
                   5374: 
1.103     harris41 5375: # ------------------------------------------------- Check for a user privilege
1.12      www      5376: 
                   5377: sub allowed {
1.810     raeburn  5378:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5379:     my $ver_orguri=$uri;
1.439     www      5380:     $uri=&deversion($uri);
1.152     www      5381:     my $orguri=$uri;
1.52      www      5382:     $uri=&declutter($uri);
1.809     raeburn  5383: 
1.810     raeburn  5384:     if ($priv eq 'evb') {
                   5385: # Evade communication block restrictions for specified role in a course
                   5386:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5387:             return $1;
                   5388:         } else {
                   5389:             return;
                   5390:         }
                   5391:     }
                   5392: 
1.620     albertel 5393:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5394: # Free bre access to adm and meta resources
1.775     albertel 5395:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5396: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5397: 	&& ($priv eq 'bre')) {
1.14      www      5398: 	return 'F';
1.159     www      5399:     }
                   5400: 
1.545     banghart 5401: # Free bre access to user's own portfolio contents
1.714     raeburn  5402:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5403:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5404: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5405:         my %setters;
                   5406:         my ($startblock,$endblock) = 
                   5407:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5408:         if ($startblock && $endblock) {
                   5409:             return 'B';
                   5410:         } else {
                   5411:             return 'F';
                   5412:         }
1.545     banghart 5413:     }
                   5414: 
1.762     raeburn  5415: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5416:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5417:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5418:         if (exists($env{'request.course.id'})) {
                   5419:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5420:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5421:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5422:                 my $courseprivid=$env{'request.course.id'};
                   5423:                 $courseprivid=~s/\_/\//;
                   5424:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5425:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5426:                     return $1; 
1.762     raeburn  5427:                 } else {
                   5428:                     if ($env{'request.course.sec'}) {
                   5429:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5430:                     }
                   5431:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5432:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5433:                         return $2;
                   5434:                     }
1.714     raeburn  5435:                 }
                   5436:             }
                   5437:         }
                   5438:     }
                   5439: 
1.159     www      5440: # Free bre to public access
                   5441: 
                   5442:     if ($priv eq 'bre') {
1.238     www      5443:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5444: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5445:            return 'F'; 
                   5446:         }
1.238     www      5447:         if ($copyright eq 'priv') {
                   5448:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5449: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5450: 		return '';
                   5451:             }
                   5452:         }
                   5453:         if ($copyright eq 'domain') {
                   5454:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5455: 	    unless (($env{'user.domain'} eq $1) ||
                   5456:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5457: 		return '';
                   5458:             }
1.262     matthew  5459:         }
1.620     albertel 5460:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5461:             # Library role, so allow browsing of resources in this domain.
                   5462:             return 'F';
1.238     www      5463:         }
1.341     www      5464:         if ($copyright eq 'custom') {
                   5465: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5466:         }
1.14      www      5467:     }
1.264     matthew  5468:     # Domain coordinator is trying to create a course
1.620     albertel 5469:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5470:         # uri is the requested domain in this case.
                   5471:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5472:         # a role of dc for the domain in question.
1.620     albertel 5473:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5474:     }
1.29      www      5475: 
1.52      www      5476:     my $thisallowed='';
                   5477:     my $statecond=0;
                   5478:     my $courseprivid='';
                   5479: 
1.1039    raeburn  5480:     my $ownaccess;
1.1043    raeburn  5481:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5482:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5483:         if ($uri eq '') {
                   5484:             $ownaccess = 1;
                   5485:         } else {
                   5486:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5487:                 my $udom = $env{'user.domain'};
                   5488:                 my $uname = $env{'user.name'};
                   5489:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5490:                     $ownaccess = 1;
1.1040    raeburn  5491:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5492:                     unless ($uri =~ m{\.\./}) {
                   5493:                         $ownaccess = 1;
                   5494:                     }
                   5495:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5496:                     my $now = time;
                   5497:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5498:                         my $adom = $1;
                   5499:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5500:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5501:                                 my ($start,$end) = split('.',$env{$key});
                   5502:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5503:                                     $ownaccess = 1;
                   5504:                                     last;
                   5505:                                 }
                   5506:                             }
                   5507:                         }
                   5508:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5509:                         my $adom = $1;
                   5510:                         my $aname = $2;
1.1042    raeburn  5511:                         foreach my $role ('ca','aa') { 
                   5512:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5513:                                 my ($start,$end) =
                   5514:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5515:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5516:                                     $ownaccess = 1;
                   5517:                                     last;
                   5518:                                 }
1.1039    raeburn  5519:                             }
                   5520:                         }
                   5521:                     }
                   5522:                 }
                   5523:             }
                   5524:         }
                   5525:     }
                   5526: 
1.52      www      5527: # Course
                   5528: 
1.620     albertel 5529:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5530:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5531:             $thisallowed.=$1;
                   5532:         }
1.52      www      5533:     }
1.29      www      5534: 
1.52      www      5535: # Domain
                   5536: 
1.620     albertel 5537:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5538:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5539:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5540:             $thisallowed.=$1;
                   5541:         }
1.12      www      5542:     }
1.52      www      5543: 
                   5544: # Course: uri itself is a course
1.66      www      5545:     my $courseuri=$uri;
                   5546:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5547:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5548: 
1.620     albertel 5549:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5550:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5551:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5552:             $thisallowed.=$1;
                   5553:         }
1.12      www      5554:     }
1.29      www      5555: 
1.665     albertel 5556: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5557: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5558:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5559: 	$thisallowed='';
1.671     raeburn  5560:         my ($match)=&is_on_map($uri);
                   5561:         if ($match) {
                   5562:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5563:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5564:                 $thisallowed.=$1;
                   5565:             }
                   5566:         } else {
1.705     albertel 5567:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5568:             if ($refuri) {
                   5569:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5570:                     $thisallowed='F';
1.671     raeburn  5571:                 } else {
                   5572:                     $refuri=&declutter($refuri);
                   5573:                     my ($match) = &is_on_map($refuri);
                   5574:                     if ($match) {
                   5575:                         $thisallowed='F';
                   5576:                     }
1.669     raeburn  5577:                 }
1.671     raeburn  5578:             }
                   5579:         }
1.314     www      5580:     }
1.492     albertel 5581: 
1.766     albertel 5582:     if ($priv eq 'bre'
                   5583: 	&& $thisallowed ne 'F' 
                   5584: 	&& $thisallowed ne '2'
                   5585: 	&& &is_portfolio_url($uri)) {
                   5586: 	$thisallowed = &portfolio_access($uri);
                   5587:     }
                   5588:     
1.52      www      5589: # Full access at system, domain or course-wide level? Exit.
1.29      www      5590:     if ($thisallowed=~/F/) {
                   5591: 	return 'F';
                   5592:     }
                   5593: 
1.52      www      5594: # If this is generating or modifying users, exit with special codes
1.29      www      5595: 
1.643     www      5596:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5597: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5598: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5599: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5600: 	    unless ($auname) { return $thisallowed; }
                   5601: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5602: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5603: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5604: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5605: 	}
1.52      www      5606: 	return $thisallowed;
                   5607:     }
                   5608: #
1.103     harris41 5609: # Gathered so far: system, domain and course wide privileges
1.52      www      5610: #
                   5611: # Course: See if uri or referer is an individual resource that is part of 
                   5612: # the course
                   5613: 
1.620     albertel 5614:     if ($env{'request.course.id'}) {
1.232     www      5615: 
1.620     albertel 5616:        $courseprivid=$env{'request.course.id'};
                   5617:        if ($env{'request.course.sec'}) {
                   5618:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5619:        }
                   5620:        $courseprivid=~s/\_/\//;
                   5621:        my $checkreferer=1;
1.232     www      5622:        my ($match,$cond)=&is_on_map($uri);
                   5623:        if ($match) {
                   5624:            $statecond=$cond;
1.620     albertel 5625:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5626:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5627:                $thisallowed.=$1;
                   5628:                $checkreferer=0;
                   5629:            }
1.29      www      5630:        }
1.83      www      5631:        
1.148     www      5632:        if ($checkreferer) {
1.620     albertel 5633: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5634:             unless ($refuri) {
1.800     albertel 5635:                 foreach my $key (keys(%env)) {
                   5636: 		    if ($key=~/^httpref\..*\*/) {
                   5637: 			my $pattern=$key;
1.156     www      5638:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5639:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5640:                         $pattern=~s/\//\\\//g;
1.152     www      5641:                         if ($orguri=~/$pattern/) {
1.800     albertel 5642: 			    $refuri=$env{$key};
1.148     www      5643:                         }
                   5644:                     }
1.191     harris41 5645:                 }
1.148     www      5646:             }
1.232     www      5647: 
1.148     www      5648:          if ($refuri) { 
1.152     www      5649: 	  $refuri=&declutter($refuri);
1.232     www      5650:           my ($match,$cond)=&is_on_map($refuri);
                   5651:             if ($match) {
                   5652:               my $refstatecond=$cond;
1.620     albertel 5653:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5654:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5655:                   $thisallowed.=$1;
1.53      www      5656:                   $uri=$refuri;
                   5657:                   $statecond=$refstatecond;
1.52      www      5658:               }
                   5659:           }
1.148     www      5660:         }
1.29      www      5661:        }
1.52      www      5662:    }
1.29      www      5663: 
1.52      www      5664: #
1.103     harris41 5665: # Gathered now: all privileges that could apply, and condition number
1.52      www      5666: # 
                   5667: #
                   5668: # Full or no access?
                   5669: #
1.29      www      5670: 
1.52      www      5671:     if ($thisallowed=~/F/) {
                   5672: 	return 'F';
                   5673:     }
1.29      www      5674: 
1.52      www      5675:     unless ($thisallowed) {
                   5676:         return '';
                   5677:     }
1.29      www      5678: 
1.52      www      5679: # Restrictions exist, deal with them
                   5680: #
                   5681: #   C:according to course preferences
                   5682: #   R:according to resource settings
                   5683: #   L:unless locked
                   5684: #   X:according to user session state
                   5685: #
                   5686: 
                   5687: # Possibly locked functionality, check all courses
1.54      www      5688: # Locks might take effect only after 10 minutes cache expiration for other
                   5689: # courses, and 2 minutes for current course
1.52      www      5690: 
                   5691:     my $envkey;
                   5692:     if ($thisallowed=~/L/) {
1.1000    raeburn  5693:         foreach $envkey (keys(%env)) {
1.54      www      5694:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5695:                my $courseid=$2;
                   5696:                my $roleid=$1.'.'.$2;
1.92      www      5697:                $courseid=~s/^\///;
1.54      www      5698:                my $expiretime=600;
1.620     albertel 5699:                if ($env{'request.role'} eq $roleid) {
1.54      www      5700: 		  $expiretime=120;
                   5701:                }
                   5702: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5703:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5704:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5705: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5706:                }
1.620     albertel 5707:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5708:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5709: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5710:                        &log($env{'user.domain'},$env{'user.name'},
                   5711:                             $env{'user.home'},
1.57      www      5712:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5713:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5714:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5715: 		       return '';
                   5716:                    }
                   5717:                }
1.620     albertel 5718:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5719:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5720: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5721:                        &log($env{'user.domain'},$env{'user.name'},
                   5722:                             $env{'user.home'},
1.57      www      5723:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5724:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5725:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5726: 		       return '';
                   5727:                    }
                   5728:                }
                   5729: 	   }
1.29      www      5730:        }
1.52      www      5731:     }
                   5732:    
                   5733: #
                   5734: # Rest of the restrictions depend on selected course
                   5735: #
                   5736: 
1.620     albertel 5737:     unless ($env{'request.course.id'}) {
1.766     albertel 5738: 	if ($thisallowed eq 'A') {
                   5739: 	    return 'A';
1.814     raeburn  5740:         } elsif ($thisallowed eq 'B') {
                   5741:             return 'B';
1.766     albertel 5742: 	} else {
                   5743: 	    return '1';
                   5744: 	}
1.52      www      5745:     }
1.29      www      5746: 
1.52      www      5747: #
                   5748: # Now user is definitely in a course
                   5749: #
1.53      www      5750: 
                   5751: 
                   5752: # Course preferences
                   5753: 
                   5754:    if ($thisallowed=~/C/) {
1.620     albertel 5755:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5756:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5757:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5758: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5759: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5760: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5761: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5762: 			$env{'request.course.id'});
                   5763: 	   }
1.237     www      5764:            return '';
                   5765:        }
                   5766: 
1.620     albertel 5767:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5768: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5769: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5770: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5771: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5772: 			$env{'request.course.id'});
                   5773: 	   }
1.54      www      5774:            return '';
                   5775:        }
1.53      www      5776:    }
                   5777: 
                   5778: # Resource preferences
                   5779: 
                   5780:    if ($thisallowed=~/R/) {
1.620     albertel 5781:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5782:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5783: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5784: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5785: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5786: 	   }
                   5787: 	   return '';
1.54      www      5788:        }
1.53      www      5789:    }
1.30      www      5790: 
1.246     www      5791: # Restricted by state or randomout?
1.30      www      5792: 
1.52      www      5793:    if ($thisallowed=~/X/) {
1.620     albertel 5794:       if ($env{'acc.randomout'}) {
1.579     albertel 5795: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5796:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5797:             return ''; 
                   5798:          }
1.247     www      5799:       }
                   5800:       if (&condval($statecond)) {
1.52      www      5801: 	 return '2';
                   5802:       } else {
                   5803:          return '';
                   5804:       }
                   5805:    }
1.30      www      5806: 
1.766     albertel 5807:     if ($thisallowed eq 'A') {
                   5808: 	return 'A';
1.814     raeburn  5809:     } elsif ($thisallowed eq 'B') {
                   5810:         return 'B';
1.766     albertel 5811:     }
1.52      www      5812:    return 'F';
1.232     www      5813: }
                   5814: 
1.710     albertel 5815: sub split_uri_for_cond {
                   5816:     my $uri=&deversion(&declutter(shift));
                   5817:     my @uriparts=split(/\//,$uri);
                   5818:     my $filename=pop(@uriparts);
                   5819:     my $pathname=join('/',@uriparts);
                   5820:     return ($pathname,$filename);
                   5821: }
1.232     www      5822: # --------------------------------------------------- Is a resource on the map?
                   5823: 
                   5824: sub is_on_map {
1.710     albertel 5825:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5826:     #Trying to find the conditional for the file
1.620     albertel 5827:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5828: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5829:     if ($match) {
1.289     bowersj2 5830: 	return (1,$1);
                   5831:     } else {
1.434     www      5832: 	return (0,0);
1.289     bowersj2 5833:     }
1.12      www      5834: }
                   5835: 
1.427     www      5836: # --------------------------------------------------------- Get symb from alias
                   5837: 
                   5838: sub get_symb_from_alias {
                   5839:     my $symb=shift;
                   5840:     my ($map,$resid,$url)=&decode_symb($symb);
                   5841: # Already is a symb
                   5842:     if ($url) { return $symb; }
                   5843: # Must be an alias
                   5844:     my $aliassymb='';
                   5845:     my %bighash;
1.620     albertel 5846:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5847:                             &GDBM_READER(),0640)) {
                   5848:         my $rid=$bighash{'mapalias_'.$symb};
                   5849: 	if ($rid) {
                   5850: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5851: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5852: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5853: 	}
                   5854:         untie %bighash;
                   5855:     }
                   5856:     return $aliassymb;
                   5857: }
                   5858: 
1.12      www      5859: # ----------------------------------------------------------------- Define Role
                   5860: 
                   5861: sub definerole {
                   5862:   if (allowed('mcr','/')) {
                   5863:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5864:     foreach my $role (split(':',$sysrole)) {
                   5865: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5866:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5867:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5868: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5869:                return "refused:s:$crole&$cqual"; 
                   5870:             }
                   5871:         }
1.191     harris41 5872:     }
1.800     albertel 5873:     foreach my $role (split(':',$domrole)) {
                   5874: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5875:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5876:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5877: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5878:                return "refused:d:$crole&$cqual"; 
                   5879:             }
                   5880:         }
1.191     harris41 5881:     }
1.800     albertel 5882:     foreach my $role (split(':',$courole)) {
                   5883: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5884:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5885:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5886: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5887:                return "refused:c:$crole&$cqual"; 
                   5888:             }
                   5889:         }
1.191     harris41 5890:     }
1.620     albertel 5891:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5892:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5893: 	        "rolesdef_$rolename=".
                   5894:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5895:     return reply($command,$env{'user.home'});
1.12      www      5896:   } else {
                   5897:     return 'refused';
                   5898:   }
1.105     harris41 5899: }
                   5900: 
                   5901: # ---------------- Make a metadata query against the network of library servers
                   5902: 
                   5903: sub metadata_query {
1.244     matthew  5904:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5905:     my %rhash;
1.845     albertel 5906:     my %libserv = &all_library();
1.244     matthew  5907:     my @server_list = (defined($server_array) ? @$server_array
                   5908:                                               : keys(%libserv) );
                   5909:     for my $server (@server_list) {
1.118     harris41 5910: 	unless ($custom or $customshow) {
                   5911: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5912: 	    $rhash{$server}=$reply;
                   5913: 	}
                   5914: 	else {
                   5915: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5916: 			     &escape($custom).':'.&escape($customshow),
                   5917: 			     $server);
                   5918: 	    $rhash{$server}=$reply;
                   5919: 	}
1.112     harris41 5920:     }
1.118     harris41 5921:     return \%rhash;
1.240     www      5922: }
                   5923: 
                   5924: # ----------------------------------------- Send log queries and wait for reply
                   5925: 
                   5926: sub log_query {
                   5927:     my ($uname,$udom,$query,%filters)=@_;
                   5928:     my $uhome=&homeserver($uname,$udom);
                   5929:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5930:     my $uhost=&hostname($uhome);
1.800     albertel 5931:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5932:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5933:                        $uhome);
1.479     albertel 5934:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5935:     return get_query_reply($queryid);
                   5936: }
                   5937: 
1.818     raeburn  5938: # -------------------------- Update MySQL table for portfolio file
                   5939: 
                   5940: sub update_portfolio_table {
1.821     raeburn  5941:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5942:     if ($group ne '') {
                   5943:         $file_name =~s /^\Q$group\E//;
                   5944:     }
1.818     raeburn  5945:     my $homeserver = &homeserver($uname,$udom);
                   5946:     my $queryid=
1.821     raeburn  5947:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5948:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5949:     my $reply = &get_query_reply($queryid);
                   5950:     return $reply;
                   5951: }
                   5952: 
1.899     raeburn  5953: # -------------------------- Update MySQL allusers table
                   5954: 
                   5955: sub update_allusers_table {
                   5956:     my ($uname,$udom,$names) = @_;
                   5957:     my $homeserver = &homeserver($uname,$udom);
                   5958:     my $queryid=
                   5959:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5960:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5961:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5962:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5963:                'generation='.&escape($names->{'generation'}).'%%'.
                   5964:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5965:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5966:     return;
1.899     raeburn  5967: }
                   5968: 
1.508     raeburn  5969: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5970: 
                   5971: sub fetch_enrollment_query {
1.511     raeburn  5972:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5973:     my $homeserver;
1.547     raeburn  5974:     my $maxtries = 1;
1.508     raeburn  5975:     if ($context eq 'automated') {
                   5976:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5977:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5978:     } else {
                   5979:         $homeserver = &homeserver($cnum,$dom);
                   5980:     }
1.838     albertel 5981:     my $host=&hostname($homeserver);
1.506     raeburn  5982:     my $cmd = '';
1.1000    raeburn  5983:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5984:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5985:     }
                   5986:     $cmd =~ s/%%$//;
                   5987:     $cmd = &escape($cmd);
                   5988:     my $query = 'fetchenrollment';
1.620     albertel 5989:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5990:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5991:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5992:         return 'error: '.$queryid;
                   5993:     }
1.506     raeburn  5994:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5995:     my $tries = 1;
                   5996:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5997:         $reply = &get_query_reply($queryid);
                   5998:         $tries ++;
                   5999:     }
1.526     raeburn  6000:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6001:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6002:     } else {
1.901     albertel 6003:         my @responses = split(/:/,$reply);
1.515     raeburn  6004:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6005:             foreach my $line (@responses) {
                   6006:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6007:                 $$replyref{$key} = $value;
                   6008:             }
                   6009:         } else {
1.1117    foxr     6010:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6011:             foreach my $line (@responses) {
                   6012:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6013:                 $$replyref{$key} = $value;
                   6014:                 if ($value > 0) {
1.800     albertel 6015:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6016:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6017:                         my $destname = $pathname.'/'.$filename;
                   6018:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6019:                         if ($xml_classlist =~ /^error/) {
                   6020:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6021:                         } else {
1.506     raeburn  6022:                             if ( open(FILE,">$destname") ) {
                   6023:                                 print FILE &unescape($xml_classlist);
                   6024:                                 close(FILE);
1.526     raeburn  6025:                             } else {
                   6026:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6027:                             }
                   6028:                         }
                   6029:                     }
                   6030:                 }
                   6031:             }
                   6032:         }
                   6033:         return 'ok';
                   6034:     }
                   6035:     return 'error';
                   6036: }
                   6037: 
1.242     www      6038: sub get_query_reply {
                   6039:     my $queryid=shift;
1.1117    foxr     6040:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6041:     my $reply='';
                   6042:     for (1..100) {
                   6043: 	sleep 2;
                   6044:         if (-e $replyfile.'.end') {
1.448     albertel 6045: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6046: 		$reply = join('',<$fh>);
                   6047: 		close($fh);
1.240     www      6048: 	   } else { return 'error: reply_file_error'; }
1.242     www      6049:            return &unescape($reply);
                   6050: 	}
1.240     www      6051:     }
1.242     www      6052:     return 'timeout:'.$queryid;
1.240     www      6053: }
                   6054: 
                   6055: sub courselog_query {
1.241     www      6056: #
                   6057: # possible filters:
                   6058: # url: url or symb
                   6059: # username
                   6060: # domain
                   6061: # action: view, submit, grade
                   6062: # start: timestamp
                   6063: # end: timestamp
                   6064: #
1.240     www      6065:     my (%filters)=@_;
1.620     albertel 6066:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6067:     if ($filters{'url'}) {
                   6068: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6069:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6070:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6071:     }
1.620     albertel 6072:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6073:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6074:     return &log_query($cname,$cdom,'courselog',%filters);
                   6075: }
                   6076: 
                   6077: sub userlog_query {
1.858     raeburn  6078: #
                   6079: # possible filters:
                   6080: # action: log check role
                   6081: # start: timestamp
                   6082: # end: timestamp
                   6083: #
1.240     www      6084:     my ($uname,$udom,%filters)=@_;
                   6085:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6086: }
                   6087: 
1.506     raeburn  6088: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6089: 
                   6090: sub auto_run {
1.508     raeburn  6091:     my ($cnum,$cdom) = @_;
1.876     raeburn  6092:     my $response = 0;
                   6093:     my $settings;
                   6094:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6095:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6096:         $settings = $domconfig{'autoenroll'};
                   6097:         if ($settings->{'run'} eq '1') {
                   6098:             $response = 1;
                   6099:         }
                   6100:     } else {
1.934     raeburn  6101:         my $homeserver;
                   6102:         if (&is_course($cdom,$cnum)) {
                   6103:             $homeserver = &homeserver($cnum,$cdom);
                   6104:         } else {
                   6105:             $homeserver = &domain($cdom,'primary');
                   6106:         }
                   6107:         if ($homeserver ne 'no_host') {
                   6108:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6109:         }
1.876     raeburn  6110:     }
1.506     raeburn  6111:     return $response;
                   6112: }
1.776     albertel 6113: 
1.506     raeburn  6114: sub auto_get_sections {
1.508     raeburn  6115:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6116:     my $homeserver;
                   6117:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6118:         $homeserver = &homeserver($cnum,$cdom);
                   6119:     }
                   6120:     if (!defined($homeserver)) { 
                   6121:         if ($cdom =~ /^$match_domain$/) {
                   6122:             $homeserver = &domain($cdom,'primary');
                   6123:         }
                   6124:     }
                   6125:     my @secs;
                   6126:     if (defined($homeserver)) {
                   6127:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6128:         unless ($response eq 'refused') {
                   6129:             @secs = split(/:/,$response);
                   6130:         }
1.506     raeburn  6131:     }
                   6132:     return @secs;
                   6133: }
1.776     albertel 6134: 
1.506     raeburn  6135: sub auto_new_course {
1.1099    raeburn  6136:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6137:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6138:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6139:     return $response;
                   6140: }
1.776     albertel 6141: 
1.506     raeburn  6142: sub auto_validate_courseID {
1.508     raeburn  6143:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6144:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6145:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6146:     return $response;
                   6147: }
1.776     albertel 6148: 
1.1007    raeburn  6149: sub auto_validate_instcode {
1.1020    raeburn  6150:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6151:     my ($homeserver,$response);
                   6152:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6153:         $homeserver = &homeserver($cnum,$cdom);
                   6154:     }
                   6155:     if (!defined($homeserver)) {
                   6156:         if ($cdom =~ /^$match_domain$/) {
                   6157:             $homeserver = &domain($cdom,'primary');
                   6158:         }
                   6159:     }
1.1065    raeburn  6160:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6161:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6162:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6163:     return ($outcome,$description);
1.1007    raeburn  6164: }
                   6165: 
1.506     raeburn  6166: sub auto_create_password {
1.873     raeburn  6167:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6168:     my ($homeserver,$response);
1.506     raeburn  6169:     my $create_passwd = 0;
                   6170:     my $authchk = '';
1.873     raeburn  6171:     if ($udom =~ /^$match_domain$/) {
                   6172:         $homeserver = &domain($udom,'primary');
                   6173:     }
                   6174:     if ($homeserver eq '') {
                   6175:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6176:             $homeserver = &homeserver($cnum,$cdom);
                   6177:         }
                   6178:     }
                   6179:     if ($homeserver eq '') {
                   6180:         $authchk = 'nodomain';
1.506     raeburn  6181:     } else {
1.873     raeburn  6182:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6183:         if ($response eq 'refused') {
                   6184:             $authchk = 'refused';
                   6185:         } else {
1.901     albertel 6186:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6187:         }
1.506     raeburn  6188:     }
                   6189:     return ($authparam,$create_passwd,$authchk);
                   6190: }
                   6191: 
1.706     raeburn  6192: sub auto_photo_permission {
                   6193:     my ($cnum,$cdom,$students) = @_;
                   6194:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6195:     my ($outcome,$perm_reqd,$conditions) = 
                   6196: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6197:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6198: 	return (undef,undef);
                   6199:     }
1.706     raeburn  6200:     return ($outcome,$perm_reqd,$conditions);
                   6201: }
                   6202: 
                   6203: sub auto_checkphotos {
                   6204:     my ($uname,$udom,$pid) = @_;
                   6205:     my $homeserver = &homeserver($uname,$udom);
                   6206:     my ($result,$resulttype);
                   6207:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6208: 				   &escape($uname).':'.&escape($pid),
                   6209: 				   $homeserver));
1.709     albertel 6210:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6211: 	return (undef,undef);
                   6212:     }
1.706     raeburn  6213:     if ($outcome) {
                   6214:         ($result,$resulttype) = split(/:/,$outcome);
                   6215:     } 
                   6216:     return ($result,$resulttype);
                   6217: }
                   6218: 
                   6219: sub auto_photochoice {
                   6220:     my ($cnum,$cdom) = @_;
                   6221:     my $homeserver = &homeserver($cnum,$cdom);
                   6222:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6223: 						       &escape($cdom),
                   6224: 						       $homeserver)));
1.709     albertel 6225:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6226: 	return (undef,undef);
                   6227:     }
1.706     raeburn  6228:     return ($update,$comment);
                   6229: }
                   6230: 
                   6231: sub auto_photoupdate {
                   6232:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6233:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6234:     my $host=&hostname($homeserver);
1.706     raeburn  6235:     my $cmd = '';
                   6236:     my $maxtries = 1;
1.800     albertel 6237:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6238:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6239:     }
                   6240:     $cmd =~ s/%%$//;
                   6241:     $cmd = &escape($cmd);
                   6242:     my $query = 'institutionalphotos';
                   6243:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6244:     unless ($queryid=~/^\Q$host\E\_/) {
                   6245:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6246:         return 'error: '.$queryid;
                   6247:     }
                   6248:     my $reply = &get_query_reply($queryid);
                   6249:     my $tries = 1;
                   6250:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6251:         $reply = &get_query_reply($queryid);
                   6252:         $tries ++;
                   6253:     }
                   6254:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6255:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6256:     } else {
                   6257:         my @responses = split(/:/,$reply);
                   6258:         my $outcome = shift(@responses); 
                   6259:         foreach my $item (@responses) {
                   6260:             my ($key,$value) = split(/=/,$item);
                   6261:             $$photo{$key} = $value;
                   6262:         }
                   6263:         return $outcome;
                   6264:     }
                   6265:     return 'error';
                   6266: }
                   6267: 
1.521     raeburn  6268: sub auto_instcode_format {
1.793     albertel 6269:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6270: 	$cat_order) = @_;
1.521     raeburn  6271:     my $courses = '';
1.772     raeburn  6272:     my @homeservers;
1.521     raeburn  6273:     if ($caller eq 'global') {
1.841     albertel 6274: 	my %servers = &get_servers($codedom,'library');
                   6275: 	foreach my $tryserver (keys(%servers)) {
                   6276: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6277: 		push(@homeservers,$tryserver);
                   6278: 	    }
1.584     raeburn  6279:         }
1.1022    raeburn  6280:     } elsif ($caller eq 'requests') {
                   6281:         if ($codedom =~ /^$match_domain$/) {
                   6282:             my $chome = &domain($codedom,'primary');
                   6283:             unless ($chome eq 'no_host') {
                   6284:                 push(@homeservers,$chome);
                   6285:             }
                   6286:         }
1.521     raeburn  6287:     } else {
1.772     raeburn  6288:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6289:     }
1.793     albertel 6290:     foreach my $code (keys(%{$instcodes})) {
                   6291:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6292:     }
                   6293:     chop($courses);
1.772     raeburn  6294:     my $ok_response = 0;
                   6295:     my $response;
                   6296:     while (@homeservers > 0 && $ok_response == 0) {
                   6297:         my $server = shift(@homeservers); 
                   6298:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6299:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6300:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6301: 		split(/:/,$response);
1.772     raeburn  6302:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6303:             push(@{$codetitles},&str2array($codetitles_str));
                   6304:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6305:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6306:             $ok_response = 1;
                   6307:         }
                   6308:     }
                   6309:     if ($ok_response) {
1.521     raeburn  6310:         return 'ok';
1.772     raeburn  6311:     } else {
                   6312:         return $response;
1.521     raeburn  6313:     }
                   6314: }
                   6315: 
1.792     raeburn  6316: sub auto_instcode_defaults {
                   6317:     my ($domain,$returnhash,$code_order) = @_;
                   6318:     my @homeservers;
1.841     albertel 6319: 
                   6320:     my %servers = &get_servers($domain,'library');
                   6321:     foreach my $tryserver (keys(%servers)) {
                   6322: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6323: 	    push(@homeservers,$tryserver);
                   6324: 	}
1.792     raeburn  6325:     }
1.841     albertel 6326: 
1.792     raeburn  6327:     my $response;
1.841     albertel 6328:     foreach my $server (@homeservers) {
1.792     raeburn  6329:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6330:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6331: 	
                   6332: 	foreach my $pair (split(/\&/,$response)) {
                   6333: 	    my ($name,$value)=split(/\=/,$pair);
                   6334: 	    if ($name eq 'code_order') {
                   6335: 		@{$code_order} = split(/\&/,&unescape($value));
                   6336: 	    } else {
                   6337: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6338: 	    }
                   6339: 	}
                   6340: 	return 'ok';
1.792     raeburn  6341:     }
1.841     albertel 6342: 
                   6343:     return $response;
1.1003    raeburn  6344: }
                   6345: 
                   6346: sub auto_possible_instcodes {
1.1007    raeburn  6347:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6348:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6349:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6350:         return;
                   6351:     }
1.1003    raeburn  6352:     my (@homeservers,$uhome);
                   6353:     if (defined(&domain($domain,'primary'))) {
                   6354:         $uhome=&domain($domain,'primary');
                   6355:         push(@homeservers,&domain($domain,'primary'));
                   6356:     } else {
                   6357:         my %servers = &get_servers($domain,'library');
                   6358:         foreach my $tryserver (keys(%servers)) {
                   6359:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6360:                 push(@homeservers,$tryserver);
                   6361:             }
                   6362:         }
                   6363:     }
                   6364:     my $response;
                   6365:     foreach my $server (@homeservers) {
                   6366:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6367:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6368:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6369:             split(':',$response);
                   6370:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6371:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6372:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6373:             my ($name,$value)=split('=',$item);
                   6374:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6375:         }
                   6376:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6377:             my ($name,$value)=split('=',$item);
                   6378:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6379:         }
                   6380:         return 'ok';
                   6381:     }
                   6382:     return $response;
                   6383: }
1.792     raeburn  6384: 
1.1010    raeburn  6385: sub auto_courserequest_checks {
                   6386:     my ($dom) = @_;
1.1020    raeburn  6387:     my ($homeserver,%validations);
                   6388:     if ($dom =~ /^$match_domain$/) {
                   6389:         $homeserver = &domain($dom,'primary');
                   6390:     }
                   6391:     unless ($homeserver eq 'no_host') {
                   6392:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6393:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6394:             my @items = split(/&/,$response);
                   6395:             foreach my $item (@items) {
                   6396:                 my ($key,$value) = split('=',$item);
                   6397:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6398:             }
                   6399:         }
                   6400:     }
1.1010    raeburn  6401:     return %validations; 
                   6402: }
                   6403: 
1.1020    raeburn  6404: sub auto_courserequest_validation {
                   6405:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6406:     my ($homeserver,$response);
                   6407:     if ($dom =~ /^$match_domain$/) {
                   6408:         $homeserver = &domain($dom,'primary');
                   6409:     }
                   6410:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6411:           
1.1020    raeburn  6412:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6413:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6414:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6415:                                     $homeserver));
                   6416:     }
                   6417:     return $response;
                   6418: }
                   6419: 
1.777     albertel 6420: sub auto_validate_class_sec {
1.918     raeburn  6421:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6422:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6423:     my $ownerlist;
                   6424:     if (ref($owners) eq 'ARRAY') {
                   6425:         $ownerlist = join(',',@{$owners});
                   6426:     } else {
                   6427:         $ownerlist = $owners;
                   6428:     }
1.773     raeburn  6429:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6430:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6431:     return $response;
                   6432: }
                   6433: 
1.679     raeburn  6434: # ------------------------------------------------------- Course Group routines
                   6435: 
                   6436: sub get_coursegroups {
1.809     raeburn  6437:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6438:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6439: }
                   6440: 
1.679     raeburn  6441: sub modify_coursegroup {
                   6442:     my ($cdom,$cnum,$groupsettings) = @_;
                   6443:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6444: }
                   6445: 
1.809     raeburn  6446: sub toggle_coursegroup_status {
                   6447:     my ($cdom,$cnum,$group,$action) = @_;
                   6448:     my ($from_namespace,$to_namespace);
                   6449:     if ($action eq 'delete') {
                   6450:         $from_namespace = 'coursegroups';
                   6451:         $to_namespace = 'deleted_groups';
                   6452:     } else {
                   6453:         $from_namespace = 'deleted_groups';
                   6454:         $to_namespace = 'coursegroups';
                   6455:     }
                   6456:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6457:     if (my $tmp = &error(%curr_group)) {
                   6458:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6459:         return ('read error',$tmp);
                   6460:     } else {
                   6461:         my %savedsettings = %curr_group; 
1.809     raeburn  6462:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6463:         my $deloutcome;
                   6464:         if ($result eq 'ok') {
1.809     raeburn  6465:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6466:         } else {
                   6467:             return ('write error',$result);
                   6468:         }
                   6469:         if ($deloutcome eq 'ok') {
                   6470:             return 'ok';
                   6471:         } else {
                   6472:             return ('delete error',$deloutcome);
                   6473:         }
                   6474:     }
                   6475: }
                   6476: 
1.679     raeburn  6477: sub modify_group_roles {
1.957     raeburn  6478:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6479:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6480:     my $role = 'gr/'.&escape($userprivs);
                   6481:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6482:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6483:     if ($result eq 'ok') {
                   6484:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6485:     }
1.679     raeburn  6486:     return $result;
                   6487: }
                   6488: 
                   6489: sub modify_coursegroup_membership {
                   6490:     my ($cdom,$cnum,$membership) = @_;
                   6491:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6492:     return $result;
                   6493: }
                   6494: 
1.682     raeburn  6495: sub get_active_groups {
                   6496:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6497:     my $now = time;
                   6498:     my %groups = ();
                   6499:     foreach my $key (keys(%env)) {
1.811     albertel 6500:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6501:             my ($start,$end) = split(/\./,$env{$key});
                   6502:             if (($end!=0) && ($end<$now)) { next; }
                   6503:             if (($start!=0) && ($start>$now)) { next; }
                   6504:             if ($1 eq $cdom && $2 eq $cnum) {
                   6505:                 $groups{$3} = $env{$key} ;
                   6506:             }
                   6507:         }
                   6508:     }
                   6509:     return %groups;
                   6510: }
                   6511: 
1.683     raeburn  6512: sub get_group_membership {
                   6513:     my ($cdom,$cnum,$group) = @_;
                   6514:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6515: }
                   6516: 
                   6517: sub get_users_groups {
                   6518:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6519:     my @usersgroups;
1.683     raeburn  6520:     my $cachetime=1800;
                   6521: 
                   6522:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6523:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6524:     if (defined($cached)) {
1.734     albertel 6525:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6526:     } else {  
                   6527:         $grouplist = '';
1.816     raeburn  6528:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6529:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6530:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6531:         my $access_end = $env{'course.'.$courseid.
                   6532:                               '.default_enrollment_end_date'};
                   6533:         my $now = time;
                   6534:         foreach my $key (keys(%roleshash)) {
                   6535:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6536:                 my $group = $1;
                   6537:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6538:                     my $start = $2;
                   6539:                     my $end = $1;
                   6540:                     if ($start == -1) { next; } # deleted from group
                   6541:                     if (($start!=0) && ($start>$now)) { next; }
                   6542:                     if (($end!=0) && ($end<$now)) {
                   6543:                         if ($access_end && $access_end < $now) {
                   6544:                             if ($access_end - $end < 86400) {
                   6545:                                 push(@usersgroups,$group);
1.733     raeburn  6546:                             }
                   6547:                         }
1.817     raeburn  6548:                         next;
1.733     raeburn  6549:                     }
1.817     raeburn  6550:                     push(@usersgroups,$group);
1.683     raeburn  6551:                 }
                   6552:             }
                   6553:         }
1.817     raeburn  6554:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6555:         $grouplist = join(':',@usersgroups);
                   6556:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6557:     }
1.733     raeburn  6558:     return @usersgroups;
1.683     raeburn  6559: }
                   6560: 
                   6561: sub devalidate_getgroups_cache {
                   6562:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6563:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6564: 
1.683     raeburn  6565:     my $hashid="$udom:$uname:$courseid";
                   6566:     &devalidate_cache_new('getgroups',$hashid);
                   6567: }
                   6568: 
1.12      www      6569: # ------------------------------------------------------------------ Plain Text
                   6570: 
                   6571: sub plaintext {
1.988     raeburn  6572:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6573:     if ($short =~ m{^cr/}) {
1.758     albertel 6574: 	return (split('/',$short))[-1];
                   6575:     }
1.742     raeburn  6576:     if (!defined($cid)) {
                   6577:         $cid = $env{'request.course.id'};
                   6578:     }
                   6579:     my %rolenames = (
1.1008    raeburn  6580:                       Course    => 'std',
                   6581:                       Community => 'alt1',
1.742     raeburn  6582:                     );
1.1037    raeburn  6583:     if ($cid ne '') {
                   6584:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6585:             unless ($forcedefault) {
                   6586:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6587:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6588:                 return &Apache::lonlocal::mt($roletext);
                   6589:             }
                   6590:         }
                   6591:     }
                   6592:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6593:         (defined($rolenames{$type})) && 
                   6594:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6595:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6596:     } elsif ($cid ne '') {
                   6597:         my $crstype = $env{'course.'.$cid.'.type'};
                   6598:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6599:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6600:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6601:         }
1.742     raeburn  6602:     }
1.1037    raeburn  6603:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6604: }
                   6605: 
                   6606: # ----------------------------------------------------------------- Assign Role
                   6607: 
                   6608: sub assignrole {
1.957     raeburn  6609:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6610:         $context)=@_;
1.21      www      6611:     my $mrole;
                   6612:     if ($role =~ /^cr\//) {
1.393     www      6613:         my $cwosec=$url;
1.811     albertel 6614:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6615: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6616:            my $refused = 1;
                   6617:            if ($context eq 'requestcourses') {
                   6618:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6619:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6620:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6621:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6622:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6623:                            if ($crsenv{'internal.courseowner'} eq
                   6624:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6625:                                $refused = '';
                   6626:                            }
                   6627:                        }
                   6628:                    }
                   6629:                }
                   6630:            }
                   6631:            if ($refused) {
                   6632:                &logthis('Refused custom assignrole: '.
                   6633:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6634:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6635:                return 'refused';
                   6636:            }
1.104     www      6637:         }
1.21      www      6638:         $mrole='cr';
1.678     raeburn  6639:     } elsif ($role =~ /^gr\//) {
                   6640:         my $cwogrp=$url;
1.811     albertel 6641:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6642:         unless (&allowed('mdg',$cwogrp)) {
                   6643:             &logthis('Refused group assignrole: '.
                   6644:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6645:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6646:             return 'refused';
                   6647:         }
                   6648:         $mrole='gr';
1.21      www      6649:     } else {
1.82      www      6650:         my $cwosec=$url;
1.811     albertel 6651:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6652:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6653:             my $refused;
                   6654:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6655:                 if (!(&allowed('c'.$role,$url))) {
                   6656:                     $refused = 1;
                   6657:                 }
                   6658:             } else {
                   6659:                 $refused = 1;
                   6660:             }
1.947     raeburn  6661:             if ($refused) {
1.1045    raeburn  6662:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6663:                 if (!$selfenroll && $context eq 'course') {
                   6664:                     my %crsenv;
                   6665:                     if ($role eq 'cc' || $role eq 'co') {
                   6666:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6667:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6668:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6669:                                 if ($crsenv{'internal.courseowner'} eq 
                   6670:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6671:                                     $refused = '';
                   6672:                                 }
                   6673:                             }
                   6674:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6675:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6676:                                 if ($crsenv{'internal.courseowner'} eq 
                   6677:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6678:                                     $refused = '';
                   6679:                                 }
                   6680:                             }
                   6681:                         }
                   6682:                     }
                   6683:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6684:                     $refused = '';
1.1017    raeburn  6685:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6686:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6687:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6688:                         my $wrongcc;
                   6689:                         if ($cnum =~ /^$match_community$/) {
                   6690:                             $wrongcc = 1 if ($role eq 'cc');
                   6691:                         } else {
                   6692:                             $wrongcc = 1 if ($role eq 'co');
                   6693:                         }
                   6694:                         unless ($wrongcc) {
                   6695:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6696:                             if ($crsenv{'internal.courseowner'} eq 
                   6697:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6698:                                 $refused = '';
                   6699:                             }
1.1017    raeburn  6700:                         }
                   6701:                     }
                   6702:                 }
                   6703:                 if ($refused) {
1.947     raeburn  6704:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6705:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6706: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6707:                     return 'refused';
                   6708:                 }
1.932     raeburn  6709:             }
1.104     www      6710:         }
1.21      www      6711:         $mrole=$role;
                   6712:     }
1.620     albertel 6713:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6714:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6715:     if ($end) { $command.='_'.$end; }
1.21      www      6716:     if ($start) {
                   6717: 	if ($end) { 
1.81      www      6718:            $command.='_'.$start; 
1.21      www      6719:         } else {
1.81      www      6720:            $command.='_0_'.$start;
1.21      www      6721:         }
                   6722:     }
1.739     raeburn  6723:     my $origstart = $start;
                   6724:     my $origend = $end;
1.957     raeburn  6725:     my $delflag;
1.357     www      6726: # actually delete
                   6727:     if ($deleteflag) {
1.373     www      6728: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6729: # modify command to delete the role
1.620     albertel 6730:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6731:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6732: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6733: # set start and finish to negative values for userrolelog
                   6734:            $start=-1;
                   6735:            $end=-1;
1.957     raeburn  6736:            $delflag = 1;
1.357     www      6737:         }
                   6738:     }
                   6739: # send command
1.349     www      6740:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6741: # log new user role if status is ok
1.349     www      6742:     if ($answer eq 'ok') {
1.663     raeburn  6743: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6744: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6745:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6746:         unless ($role =~ /^gr/) {
                   6747:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6748:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6749:         }
1.1053    raeburn  6750:         if ($role eq 'cc') {
                   6751:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6752:         }
1.349     www      6753:     }
                   6754:     return $answer;
1.169     harris41 6755: }
                   6756: 
1.1053    raeburn  6757: sub autoupdate_coowners {
                   6758:     my ($url,$end,$start,$uname,$udom) = @_;
                   6759:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6760:     if (($cdom ne '') && ($cnum ne '')) {
                   6761:         my $now = time;
                   6762:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6763:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6764:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6765:             my $instcode = $coursehash{'internal.coursecode'};
                   6766:             if ($instcode ne '') {
1.1056    raeburn  6767:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6768:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6769:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6770:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6771:                         if ($result eq 'valid') {
                   6772:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6773:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6774:                                     push(@newcoowners,$coowner);
                   6775:                                 }
                   6776:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6777:                                     push(@newcoowners,$uname.':'.$udom);
                   6778:                                 }
                   6779:                                 @newcoowners = sort(@newcoowners);
                   6780:                             } else {
                   6781:                                 push(@newcoowners,$uname.':'.$udom);
                   6782:                             }
                   6783:                         } else {
                   6784:                             if ($coursehash{'internal.co-owners'}) {
                   6785:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6786:                                     unless ($coowner eq $uname.':'.$udom) {
                   6787:                                         push(@newcoowners,$coowner);
                   6788:                                     }
                   6789:                                 }
                   6790:                                 unless (@newcoowners > 0) {
                   6791:                                     $delcoowners = 1;
                   6792:                                     $coowners = '';
                   6793:                                 }
                   6794:                             }
                   6795:                         }
                   6796:                         if (@newcoowners || $delcoowners) {
                   6797:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6798:                                             $delcoowners,@newcoowners);
                   6799:                         }
                   6800:                     }
                   6801:                 }
                   6802:             }
                   6803:         }
                   6804:     }
                   6805: }
                   6806: 
                   6807: sub store_coowners {
                   6808:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6809:     my $cid = $cdom.'_'.$cnum;
                   6810:     my ($coowners,$delresult,$putresult);
                   6811:     if (@newcoowners) {
                   6812:         $coowners = join(',',@newcoowners);
                   6813:         my %coownershash = (
                   6814:                             'internal.co-owners' => $coowners,
                   6815:                            );
                   6816:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6817:         if ($putresult eq 'ok') {
                   6818:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6819:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6820:             }
                   6821:         }
                   6822:     }
                   6823:     if ($delcoowners) {
                   6824:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6825:         if ($delresult eq 'ok') {
                   6826:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6827:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6828:             }
                   6829:         }
                   6830:     }
                   6831:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6832:         my %crsinfo =
                   6833:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6834:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6835:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6836:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6837:         }
                   6838:     }
                   6839: }
                   6840: 
1.169     harris41 6841: # -------------------------------------------------- Modify user authentication
1.197     www      6842: # Overrides without validation
                   6843: 
1.169     harris41 6844: sub modifyuserauth {
                   6845:     my ($udom,$uname,$umode,$upass)=@_;
                   6846:     my $uhome=&homeserver($uname,$udom);
1.197     www      6847:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6848:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6849:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6850:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6851:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6852: 		     &escape($upass),$uhome);
1.620     albertel 6853:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6854:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6855:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6856:     &log($udom,,$uname,$uhome,
1.620     albertel 6857:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6858:                                      $env{'user.name'}.', '.$umode.
1.197     www      6859:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6860:     unless ($reply eq 'ok') {
1.197     www      6861:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6862: 	return 'error: '.$reply;
                   6863:     }   
1.170     harris41 6864:     return 'ok';
1.80      www      6865: }
                   6866: 
1.81      www      6867: # --------------------------------------------------------------- Modify a user
1.80      www      6868: 
1.81      www      6869: sub modifyuser {
1.206     matthew  6870:     my ($udom,    $uname, $uid,
                   6871:         $umode,   $upass, $first,
                   6872:         $middle,  $last,  $gene,
1.1058    raeburn  6873:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6874:     $udom= &LONCAPA::clean_domain($udom);
                   6875:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6876:     my $showcandelete = 'none';
                   6877:     if (ref($candelete) eq 'ARRAY') {
                   6878:         if (@{$candelete} > 0) {
                   6879:             $showcandelete = join(', ',@{$candelete});
                   6880:         }
                   6881:     }
1.81      www      6882:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6883:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6884: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6885:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6886:                                      ' desiredhome not specified'). 
1.620     albertel 6887:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6888:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6889:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6890:     my $newuser;
                   6891:     if ($uhome eq 'no_host') {
                   6892:         $newuser = 1;
                   6893:     }
1.80      www      6894: # ----------------------------------------------------------------- Create User
1.406     albertel 6895:     if (($uhome eq 'no_host') && 
                   6896: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6897:         my $unhome='';
1.844     albertel 6898:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6899:             $unhome = $desiredhome;
1.620     albertel 6900: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6901: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6902:         } else { # load balancing routine for determining $unhome
1.81      www      6903:             my $loadm=10000000;
1.841     albertel 6904: 	    my %servers = &get_servers($udom,'library');
                   6905: 	    foreach my $tryserver (keys(%servers)) {
                   6906: 		my $answer=reply('load',$tryserver);
                   6907: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6908: 		    $loadm=$answer;
                   6909: 		    $unhome=$tryserver;
                   6910: 		}
1.80      www      6911: 	    }
                   6912:         }
                   6913:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6914: 	    return 'error: unable to find a home server for '.$uname.
                   6915:                    ' in domain '.$udom;
1.80      www      6916:         }
                   6917:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6918:                          &escape($upass),$unhome);
                   6919: 	unless ($reply eq 'ok') {
                   6920:             return 'error: '.$reply;
                   6921:         }   
1.230     stredwic 6922:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6923:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6924: 	    return 'error: unable verify users home machine.';
1.80      www      6925:         }
1.209     matthew  6926:     }   # End of creation of new user
1.80      www      6927: # ---------------------------------------------------------------------- Add ID
                   6928:     if ($uid) {
                   6929:        $uid=~tr/A-Z/a-z/;
                   6930:        my %uidhash=&idrget($udom,$uname);
1.196     www      6931:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6932:          && (!$forceid)) {
1.80      www      6933: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6934: 	      return 'error: user id "'.$uid.'" does not match '.
                   6935:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6936:           }
                   6937:        } else {
                   6938: 	  &idput($udom,($uname => $uid));
                   6939:        }
                   6940:     }
                   6941: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6942:     my @tmp=&get('environment',
1.899     raeburn  6943: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6944:                     'permanentemail','inststatus'],
1.134     albertel 6945: 		   $udom,$uname);
1.1075    raeburn  6946:     my (%names,%oldnames);
1.313     matthew  6947:     if ($tmp[0] =~ m/^error:.*/) { 
                   6948:         %names=(); 
                   6949:     } else {
                   6950:         %names = @tmp;
1.1075    raeburn  6951:         %oldnames = %names;
1.313     matthew  6952:     }
1.388     www      6953: #
1.1058    raeburn  6954: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6955: # of users did not contain them), do not overwrite existing values
                   6956: # unless field is in $candelete array ref.  
                   6957: #
                   6958: 
                   6959:     my @fields = ('firstname','middlename','lastname','generation',
                   6960:                   'permanentemail','id');
                   6961:     my %newvalues;
                   6962:     if (ref($candelete) eq 'ARRAY') {
                   6963:         foreach my $field (@fields) {
                   6964:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6965:                 if ($field eq 'firstname') {
                   6966:                     $names{$field} = $first;
                   6967:                 } elsif ($field eq 'middlename') {
                   6968:                     $names{$field} = $middle;
                   6969:                 } elsif ($field eq 'lastname') {
                   6970:                     $names{$field} = $last;
                   6971:                 } elsif ($field eq 'generation') { 
                   6972:                     $names{$field} = $gene;
                   6973:                 } elsif ($field eq 'permanentemail') {
                   6974:                     $names{$field} = $email;
                   6975:                 } elsif ($field eq 'id') {
                   6976:                     $names{$field}  = $uid;
                   6977:                 }
                   6978:             }
                   6979:         }
                   6980:     }
1.388     www      6981:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6982:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6983:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6984:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6985:     if ($email) {
                   6986:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6987:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6988:     }
1.899     raeburn  6989:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6990:     if (defined($inststatus)) {
                   6991:         $names{'inststatus'} = '';
                   6992:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6993:         if (ref($usertypes) eq 'HASH') {
                   6994:             my @okstatuses; 
                   6995:             foreach my $item (split(/:/,$inststatus)) {
                   6996:                 if (defined($usertypes->{$item})) {
                   6997:                     push(@okstatuses,$item);  
                   6998:                 }
                   6999:             }
                   7000:             if (@okstatuses) {
                   7001:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7002:             }
                   7003:         }
                   7004:     }
1.1075    raeburn  7005:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7006:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7007:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7008:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7009:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7010:     } else {
                   7011:         $logmsg .= ' during self creation';
                   7012:     }
1.1075    raeburn  7013:     my $changed;
                   7014:     if ($newuser) {
                   7015:         $changed = 1;
                   7016:     } else {
                   7017:         foreach my $field (@fields) {
                   7018:             if ($names{$field} ne $oldnames{$field}) {
                   7019:                 $changed = 1;
                   7020:                 last;
                   7021:             }
                   7022:         }
                   7023:     }
                   7024:     unless ($changed) {
                   7025:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7026:         &logthis($logmsg);
                   7027:         return 'ok';
                   7028:     }
                   7029:     my $reply = &put('environment', \%names, $udom,$uname);
                   7030:     if ($reply ne 'ok') { 
                   7031:         return 'error: '.$reply;
                   7032:     }
1.1087    raeburn  7033:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7034:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7035:     }
1.1075    raeburn  7036:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7037:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7038:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7039:     &logthis($logmsg);
1.134     albertel 7040:     return 'ok';
1.80      www      7041: }
                   7042: 
1.81      www      7043: # -------------------------------------------------------------- Modify student
1.80      www      7044: 
1.81      www      7045: sub modifystudent {
                   7046:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7047:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7048:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7049:     if (!$cid) {
1.620     albertel 7050: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7051: 	    return 'not_in_class';
                   7052: 	}
1.80      www      7053:     }
                   7054: # --------------------------------------------------------------- Make the user
1.81      www      7055:     my $reply=&modifyuser
1.209     matthew  7056: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7057:          $desiredhome,$email,$inststatus);
1.80      www      7058:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7059:     # This will cause &modify_student_enrollment to get the uid from the
                   7060:     # students environment
                   7061:     $uid = undef if (!$forceid);
1.455     albertel 7062:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7063: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7064:     return $reply;
                   7065: }
                   7066: 
                   7067: sub modify_student_enrollment {
1.957     raeburn  7068:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7069:     my ($cdom,$cnum,$chome);
                   7070:     if (!$cid) {
1.620     albertel 7071: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7072: 	    return 'not_in_class';
                   7073: 	}
1.620     albertel 7074: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7075: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7076:     } else {
                   7077: 	($cdom,$cnum)=split(/_/,$cid);
                   7078:     }
1.620     albertel 7079:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7080:     if (!$chome) {
1.457     raeburn  7081: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7082:     }
1.455     albertel 7083:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7084:     # Make sure the user exists
1.81      www      7085:     my $uhome=&homeserver($uname,$udom);
                   7086:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7087: 	return 'error: no such user';
                   7088:     }
1.297     matthew  7089:     # Get student data if we were not given enough information
                   7090:     if (!defined($first)  || $first  eq '' || 
                   7091:         !defined($last)   || $last   eq '' || 
                   7092:         !defined($uid)    || $uid    eq '' || 
                   7093:         !defined($middle) || $middle eq '' || 
                   7094:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7095:         # They did not supply us with enough data to enroll the student, so
                   7096:         # we need to pick up more information.
1.297     matthew  7097:         my %tmp = &get('environment',
1.294     matthew  7098:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7099:                        ,$udom,$uname);
                   7100: 
1.800     albertel 7101:         #foreach my $key (keys(%tmp)) {
                   7102:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7103:         #}
1.294     matthew  7104:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7105:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7106:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7107:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7108:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7109:     }
1.556     albertel 7110:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7111:     my $reply=cput('classlist',
                   7112: 		   {"$uname:$udom" => 
1.515     raeburn  7113: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7114: 		   $cdom,$cnum);
1.81      www      7115:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7116: 	return 'error: '.$reply;
1.652     albertel 7117:     } else {
                   7118: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7119:     }
1.297     matthew  7120:     # Add student role to user
1.83      www      7121:     my $uurl='/'.$cid;
1.81      www      7122:     $uurl=~s/\_/\//g;
                   7123:     if ($usec) {
                   7124: 	$uurl.='/'.$usec;
                   7125:     }
1.957     raeburn  7126:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7127: }
                   7128: 
1.556     albertel 7129: sub format_name {
                   7130:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7131:     my $name;
                   7132:     if ($first ne 'lastname') {
                   7133: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7134:     } else {
                   7135: 	if ($lastname=~/\S/) {
                   7136: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7137: 	    $name=~s/\s+,/,/;
                   7138: 	} else {
                   7139: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7140: 	}
                   7141:     }
                   7142:     $name=~s/^\s+//;
                   7143:     $name=~s/\s+$//;
                   7144:     $name=~s/\s+/ /g;
                   7145:     return $name;
                   7146: }
                   7147: 
1.84      www      7148: # ------------------------------------------------- Write to course preferences
                   7149: 
                   7150: sub writecoursepref {
                   7151:     my ($courseid,%prefs)=@_;
                   7152:     $courseid=~s/^\///;
                   7153:     $courseid=~s/\_/\//g;
                   7154:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7155:     my $chome=homeserver($cnum,$cdomain);
                   7156:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7157: 	return 'error: no such course';
                   7158:     }
                   7159:     my $cstring='';
1.800     albertel 7160:     foreach my $pref (keys(%prefs)) {
                   7161: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7162:     }
1.84      www      7163:     $cstring=~s/\&$//;
                   7164:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7165: }
                   7166: 
                   7167: # ---------------------------------------------------------- Make/modify course
                   7168: 
                   7169: sub createcourse {
1.741     raeburn  7170:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7171:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7172:     $url=&declutter($url);
                   7173:     my $cid='';
1.1028    raeburn  7174:     if ($context eq 'requestcourses') {
                   7175:         my $can_create = 0;
                   7176:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7177:         if ($udom eq $ownerdom) {
                   7178:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7179:                                   $context)) {
                   7180:                 $can_create = 1;
                   7181:             }
                   7182:         } else {
                   7183:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7184:                                            $category);
                   7185:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7186:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7187:                 if (@curr > 0) {
                   7188:                     my @options = qw(approval validate autolimit);
                   7189:                     my $optregex = join('|',@options);
                   7190:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7191:                         $can_create = 1;
                   7192:                     }
                   7193:                 }
                   7194:             }
                   7195:         }
                   7196:         if ($can_create) {
                   7197:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7198:                 unless (&allowed('ccc',$udom)) {
                   7199:                     return 'refused'; 
                   7200:                 }
1.1017    raeburn  7201:             }
                   7202:         } else {
                   7203:             return 'refused';
                   7204:         }
1.1028    raeburn  7205:     } elsif (!&allowed('ccc',$udom)) {
                   7206:         return 'refused';
1.84      www      7207:     }
1.1011    raeburn  7208: # --------------------------------------------------------------- Get Unique ID
                   7209:     my $uname;
                   7210:     if ($cnum =~ /^$match_courseid$/) {
                   7211:         my $chome=&homeserver($cnum,$udom,'true');
                   7212:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7213:             $uname = $cnum;
                   7214:         } else {
1.1038    raeburn  7215:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7216:         }
                   7217:     } else {
1.1038    raeburn  7218:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7219:     }
                   7220:     return $uname if ($uname =~ /^error/);
                   7221: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7222:     if (!defined($course_server)) {
                   7223:         if (defined(&domain($udom,'primary'))) {
                   7224:             $course_server = &domain($udom,'primary');
                   7225:         } else {
                   7226:             $course_server = $env{'user.home'}; 
                   7227:         }
                   7228:     }
                   7229:     my %host_servers =
                   7230:         &Apache::lonnet::get_servers($udom,'library');
                   7231:     unless ($host_servers{$course_server}) {
                   7232:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7233:     }
1.84      www      7234: # ------------------------------------------------------------- Make the course
                   7235:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7236:                       $course_server);
1.84      www      7237:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7238:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7239:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7240: 	return 'error: no such course';
                   7241:     }
1.271     www      7242: # ----------------------------------------------------------------- Course made
1.516     raeburn  7243: # log existence
1.1029    raeburn  7244:     my $now = time;
1.918     raeburn  7245:     my $newcourse = {
                   7246:                     $udom.'_'.$uname => {
1.921     raeburn  7247:                                      description => $description,
                   7248:                                      inst_code   => $inst_code,
                   7249:                                      owner       => $course_owner,
                   7250:                                      type        => $crstype,
1.1029    raeburn  7251:                                      creator     => $env{'user.name'}.':'.
                   7252:                                                     $env{'user.domain'},
                   7253:                                      created     => $now,
                   7254:                                      context     => $context,
1.918     raeburn  7255:                                                 },
                   7256:                     };
1.921     raeburn  7257:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7258: # set toplevel url
1.271     www      7259:     my $topurl=$url;
                   7260:     unless ($nonstandard) {
                   7261: # ------------------------------------------ For standard courses, make top url
                   7262:         my $mapurl=&clutter($url);
1.278     www      7263:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7264:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7265: <map>
                   7266: <resource id="1" type="start"></resource>
                   7267: <resource id="2" src="$mapurl"></resource>
                   7268: <resource id="3" type="finish"></resource>
                   7269: <link index="1" from="1" to="2"></link>
                   7270: <link index="2" from="2" to="3"></link>
                   7271: </map>
                   7272: ENDINITMAP
                   7273:         $topurl=&declutter(
1.638     albertel 7274:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7275:                           );
                   7276:     }
                   7277: # ----------------------------------------------------------- Write preferences
1.84      www      7278:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7279:                      ('description'              => $description,
                   7280:                       'url'                      => $topurl,
                   7281:                       'internal.creator'         => $env{'user.name'}.':'.
                   7282:                                                     $env{'user.domain'},
                   7283:                       'internal.created'         => $now,
                   7284:                       'internal.creationcontext' => $context)
                   7285:                     );
1.84      www      7286:     return '/'.$udom.'/'.$uname;
                   7287: }
                   7288: 
1.1011    raeburn  7289: # ------------------------------------------------------------------- Create ID
                   7290: sub generate_coursenum {
1.1038    raeburn  7291:     my ($udom,$crstype) = @_;
1.1011    raeburn  7292:     my $domdesc = &domain($udom);
                   7293:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7294:     my $first;
                   7295:     if ($crstype eq 'Community') {
                   7296:         $first = '0';
                   7297:     } else {
                   7298:         $first = int(1+rand(9)); 
                   7299:     } 
                   7300:     my $uname=$first.
1.1011    raeburn  7301:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7302:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7303:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7304: # ----------------------------------------------- Make sure that does not exist
                   7305:     my $uhome=&homeserver($uname,$udom,'true');
                   7306:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7307:         if ($crstype eq 'Community') {
                   7308:             $first = '0';
                   7309:         } else {
                   7310:             $first = int(1+rand(9));
                   7311:         }
                   7312:         $uname=$first.
1.1011    raeburn  7313:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7314:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7315:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7316:         $uhome=&homeserver($uname,$udom,'true');
                   7317:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7318:             return 'error: unable to generate unique course-ID';
                   7319:         }
                   7320:     }
                   7321:     return $uname;
                   7322: }
                   7323: 
1.813     albertel 7324: sub is_course {
                   7325:     my ($cdom,$cnum) = @_;
                   7326:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7327: 				undef,'.');
1.813     albertel 7328:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7329:         return 1;
                   7330:     }
                   7331:     return 0;
                   7332: }
                   7333: 
1.1015    raeburn  7334: sub store_userdata {
                   7335:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7336:     my $result;
1.1016    raeburn  7337:     if ($datakey ne '') {
1.1013    raeburn  7338:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7339:             if ($udom eq '' || $uname eq '') {
                   7340:                 $udom = $env{'user.domain'};
                   7341:                 $uname = $env{'user.name'};
                   7342:             }
                   7343:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7344:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7345:                 $result = 'error: no_host';
                   7346:             } else {
                   7347:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7348:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7349: 
                   7350:                 my $namevalue='';
                   7351:                 foreach my $key (keys(%{$storehash})) {
                   7352:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7353:                 }
                   7354:                 $namevalue=~s/\&$//;
1.1105    raeburn  7355:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7356:                                   $namevalue,$uhome);
1.1013    raeburn  7357:             }
                   7358:         } else {
                   7359:             $result = 'error: data to store was not a hash reference'; 
                   7360:         }
                   7361:     } else {
                   7362:         $result= 'error: invalid requestkey'; 
                   7363:     }
                   7364:     return $result;
                   7365: }
                   7366: 
1.21      www      7367: # ---------------------------------------------------------- Assign Custom Role
                   7368: 
                   7369: sub assigncustomrole {
1.957     raeburn  7370:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7371:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7372:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7373: }
                   7374: 
                   7375: # ----------------------------------------------------------------- Revoke Role
                   7376: 
                   7377: sub revokerole {
1.957     raeburn  7378:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7379:     my $now=time;
1.965     raeburn  7380:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7381: }
                   7382: 
                   7383: # ---------------------------------------------------------- Revoke Custom Role
                   7384: 
                   7385: sub revokecustomrole {
1.957     raeburn  7386:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7387:     my $now=time;
1.357     www      7388:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7389:            $deleteflag,$selfenroll,$context);
1.17      www      7390: }
                   7391: 
1.533     banghart 7392: # ------------------------------------------------------------ Disk usage
1.535     albertel 7393: sub diskusage {
1.955     raeburn  7394:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7395:     $directorypath =~ s/\/$//;
                   7396:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7397:                        .&escape($getpropath).':'.&escape($uname).':'
                   7398:                        .&escape($udom),homeserver($uname,$udom));
                   7399:     if ($listing eq 'unknown_cmd') {
                   7400:         if ($getpropath) {
                   7401:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7402:         }
                   7403:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7404:     }
1.514     albertel 7405:     return $listing;
1.512     banghart 7406: }
                   7407: 
1.566     banghart 7408: sub is_locked {
1.1096    raeburn  7409:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7410:     my @check;
                   7411:     my $is_locked;
1.1093    raeburn  7412:     push (@check,$file_name);
1.613     albertel 7413:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7414: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7415:     my ($tmp)=keys(%locked);
                   7416:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7417:     
1.566     banghart 7418:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7419:         $is_locked = 'false';
                   7420:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7421:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7422:                $is_locked = 'true';
1.1096    raeburn  7423:                if (ref($which) eq 'ARRAY') {
                   7424:                    push(@{$which},$entry);
                   7425:                } else {
                   7426:                    last;
                   7427:                }
1.745     raeburn  7428:            }
                   7429:        }
1.566     banghart 7430:     } else {
                   7431:         $is_locked = 'false';
                   7432:     }
1.1093    raeburn  7433:     return $is_locked;
1.566     banghart 7434: }
                   7435: 
1.759     albertel 7436: sub declutter_portfile {
                   7437:     my ($file) = @_;
1.833     albertel 7438:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7439:     return $file;
                   7440: }
                   7441: 
1.559     banghart 7442: # ------------------------------------------------------------- Mark as Read Only
                   7443: 
                   7444: sub mark_as_readonly {
                   7445:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7446:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7447:     my ($tmp)=keys(%current_permissions);
                   7448:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7449:     foreach my $file (@{$files}) {
1.759     albertel 7450: 	$file = &declutter_portfile($file);
1.561     banghart 7451:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7452:     }
1.613     albertel 7453:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7454:     return;
                   7455: }
                   7456: 
1.572     banghart 7457: # ------------------------------------------------------------Save Selected Files
                   7458: 
                   7459: sub save_selected_files {
                   7460:     my ($user, $path, @files) = @_;
                   7461:     my $filename = $user."savedfiles";
1.573     banghart 7462:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7463:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7464:     foreach my $file (@files) {
1.620     albertel 7465:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7466:     }
                   7467:     foreach my $file (@other_files) {
1.574     banghart 7468:         print (OUT $file."\n");
1.572     banghart 7469:     }
1.574     banghart 7470:     close (OUT);
1.572     banghart 7471:     return 'ok';
                   7472: }
                   7473: 
1.574     banghart 7474: sub clear_selected_files {
                   7475:     my ($user) = @_;
                   7476:     my $filename = $user."savedfiles";
1.1117    foxr     7477:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7478:     print (OUT undef);
                   7479:     close (OUT);
                   7480:     return ("ok");    
                   7481: }
                   7482: 
1.572     banghart 7483: sub files_in_path {
                   7484:     my ($user, $path) = @_;
                   7485:     my $filename = $user."savedfiles";
                   7486:     my %return_files;
1.1117    foxr     7487:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7488:     while (my $line_in = <IN>) {
1.574     banghart 7489:         chomp ($line_in);
                   7490:         my @paths_and_file = split (m!/!, $line_in);
                   7491:         my $file_part = pop (@paths_and_file);
                   7492:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7493:         $path_part.='/';
                   7494:         my $path_and_file = $path_part.$file_part;
                   7495:         if ($path_part eq $path) {
                   7496:             $return_files{$file_part}= 'selected';
                   7497:         }
                   7498:     }
1.574     banghart 7499:     close (IN);
                   7500:     return (\%return_files);
1.572     banghart 7501: }
                   7502: 
                   7503: # called in portfolio select mode, to show files selected NOT in current directory
                   7504: sub files_not_in_path {
                   7505:     my ($user, $path) = @_;
                   7506:     my $filename = $user."savedfiles";
                   7507:     my @return_files;
                   7508:     my $path_part;
1.1117    foxr     7509:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7510:     while (my $line = <IN>) {
1.572     banghart 7511:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7512:         my @paths_and_file = split(m|/|, $line);
                   7513:         my $file_part = pop(@paths_and_file);
                   7514:         chomp($file_part);
                   7515:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7516:         $path_part .= '/';
                   7517:         my $path_and_file = $path_part.$file_part;
                   7518:         if ($path_part ne $path) {
1.800     albertel 7519:             push(@return_files, ($path_and_file));
1.572     banghart 7520:         }
                   7521:     }
1.800     albertel 7522:     close(OUT);
1.574     banghart 7523:     return (@return_files);
1.572     banghart 7524: }
                   7525: 
1.745     raeburn  7526: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7527: 
1.745     raeburn  7528: sub get_portfile_permissions {
                   7529:     my ($domain,$user) = @_;
1.613     albertel 7530:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7531:     my ($tmp)=keys(%current_permissions);
                   7532:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7533:     return \%current_permissions;
                   7534: }
                   7535: 
                   7536: #---------------------------------------------Get portfolio file access controls
                   7537: 
1.749     raeburn  7538: sub get_access_controls {
1.745     raeburn  7539:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7540:     my %access;
                   7541:     my $real_file = $file;
                   7542:     $file =~ s/\.meta$//;
1.745     raeburn  7543:     if (defined($file)) {
1.749     raeburn  7544:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7545:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7546:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7547:             }
                   7548:         }
1.745     raeburn  7549:     } else {
1.749     raeburn  7550:         foreach my $key (keys(%{$current_permissions})) {
                   7551:             if ($key =~ /\0accesscontrol$/) {
                   7552:                 if (defined($group)) {
                   7553:                     if ($key !~ m-^\Q$group\E/-) {
                   7554:                         next;
                   7555:                     }
                   7556:                 }
                   7557:                 my ($fullpath) = split(/\0/,$key);
                   7558:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7559:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7560:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7561:                     }
                   7562:                 }
                   7563:             }
                   7564:         }
                   7565:     }
                   7566:     return %access;
                   7567: }
                   7568: 
                   7569: sub modify_access_controls {
                   7570:     my ($file_name,$changes,$domain,$user)=@_;
                   7571:     my ($outcome,$deloutcome);
                   7572:     my %store_permissions;
                   7573:     my %new_values;
                   7574:     my %new_control;
                   7575:     my %translation;
                   7576:     my @deletions = ();
                   7577:     my $now = time;
                   7578:     if (exists($$changes{'activate'})) {
                   7579:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7580:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7581:             my $numnew = scalar(@newitems);
                   7582:             for (my $i=0; $i<$numnew; $i++) {
                   7583:                 my $newkey = $newitems[$i];
                   7584:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7585:                 if ($newkey =~ /^\d+:/) { 
                   7586:                     $newkey =~ s/^(\d+)/$newid/;
                   7587:                     $translation{$1} = $newid;
                   7588:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7589:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7590:                     $translation{$1} = $newid;
                   7591:                 }
1.749     raeburn  7592:                 $new_values{$file_name."\0".$newkey} = 
                   7593:                                           $$changes{'activate'}{$newitems[$i]};
                   7594:                 $new_control{$newkey} = $now;
                   7595:             }
                   7596:         }
                   7597:     }
                   7598:     my %todelete;
                   7599:     my %changed_items;
                   7600:     foreach my $action ('delete','update') {
                   7601:         if (exists($$changes{$action})) {
                   7602:             if (ref($$changes{$action}) eq 'HASH') {
                   7603:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7604:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7605:                     if ($action eq 'delete') { 
                   7606:                         $todelete{$itemnum} = 1;
                   7607:                     } else {
                   7608:                         $changed_items{$itemnum} = $key;
                   7609:                     }
                   7610:                 }
1.745     raeburn  7611:             }
                   7612:         }
1.749     raeburn  7613:     }
                   7614:     # get lock on access controls for file.
                   7615:     my $lockhash = {
                   7616:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7617:                                                        ':'.$env{'user.domain'},
                   7618:                    }; 
                   7619:     my $tries = 0;
                   7620:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7621:    
                   7622:     while (($gotlock ne 'ok') && $tries <3) {
                   7623:         $tries ++;
                   7624:         sleep 1;
                   7625:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7626:     }
                   7627:     if ($gotlock eq 'ok') {
                   7628:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7629:         my ($tmp)=keys(%curr_permissions);
                   7630:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7631:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7632:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7633:             if (ref($curr_controls) eq 'HASH') {
                   7634:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7635:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7636:                     if (defined($todelete{$itemnum})) {
                   7637:                         push(@deletions,$file_name."\0".$control_item);
                   7638:                     } else {
                   7639:                         if (defined($changed_items{$itemnum})) {
                   7640:                             $new_control{$changed_items{$itemnum}} = $now;
                   7641:                             push(@deletions,$file_name."\0".$control_item);
                   7642:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7643:                         } else {
                   7644:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7645:                         }
                   7646:                     }
1.745     raeburn  7647:                 }
                   7648:             }
                   7649:         }
1.970     raeburn  7650:         my ($group);
                   7651:         if (&is_course($domain,$user)) {
                   7652:             ($group,my $file) = split(/\//,$file_name,2);
                   7653:         }
1.749     raeburn  7654:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7655:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7656:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7657:         #  remove lock
                   7658:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7659:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7660:         my $sqlresult =
1.970     raeburn  7661:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7662:                                     $group);
1.749     raeburn  7663:     } else {
                   7664:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7665:     }
1.749     raeburn  7666:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7667: }
                   7668: 
1.827     raeburn  7669: sub make_public_indefinitely {
                   7670:     my ($requrl) = @_;
                   7671:     my $now = time;
                   7672:     my $action = 'activate';
                   7673:     my $aclnum = 0;
                   7674:     if (&is_portfolio_url($requrl)) {
                   7675:         my (undef,$udom,$unum,$file_name,$group) =
                   7676:             &parse_portfolio_url($requrl);
                   7677:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7678:         my %access_controls = &get_access_controls($current_perms,
                   7679:                                                    $group,$file_name);
                   7680:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7681:             my ($num,$scope,$end,$start) = 
                   7682:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7683:             if ($scope eq 'public') {
                   7684:                 if ($start <= $now && $end == 0) {
                   7685:                     $action = 'none';
                   7686:                 } else {
                   7687:                     $action = 'update';
                   7688:                     $aclnum = $num;
                   7689:                 }
                   7690:                 last;
                   7691:             }
                   7692:         }
                   7693:         if ($action eq 'none') {
                   7694:              return 'ok';
                   7695:         } else {
                   7696:             my %changes;
                   7697:             my $newend = 0;
                   7698:             my $newstart = $now;
                   7699:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7700:             $changes{$action}{$newkey} = {
                   7701:                 type => 'public',
                   7702:                 time => {
                   7703:                     start => $newstart,
                   7704:                     end   => $newend,
                   7705:                 },
                   7706:             };
                   7707:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7708:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7709:             return $outcome;
                   7710:         }
                   7711:     } else {
                   7712:         return 'invalid';
                   7713:     }
                   7714: }
                   7715: 
1.745     raeburn  7716: #------------------------------------------------------Get Marked as Read Only
                   7717: 
                   7718: sub get_marked_as_readonly {
                   7719:     my ($domain,$user,$what,$group) = @_;
                   7720:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7721:     my @readonly_files;
1.629     banghart 7722:     my $cmp1=$what;
                   7723:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7724:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7725:         if (defined($group)) {
                   7726:             if ($file_name !~ m-^\Q$group\E/-) {
                   7727:                 next;
                   7728:             }
                   7729:         }
1.561     banghart 7730:         if (ref($value) eq "ARRAY"){
                   7731:             foreach my $stored_what (@{$value}) {
1.629     banghart 7732:                 my $cmp2=$stored_what;
1.759     albertel 7733:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7734:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7735:                 }
1.629     banghart 7736:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7737:                     push(@readonly_files, $file_name);
1.745     raeburn  7738:                     last;
1.563     banghart 7739:                 } elsif (!defined($what)) {
                   7740:                     push(@readonly_files, $file_name);
1.745     raeburn  7741:                     last;
1.561     banghart 7742:                 }
                   7743:             }
1.745     raeburn  7744:         }
1.561     banghart 7745:     }
                   7746:     return @readonly_files;
                   7747: }
1.577     banghart 7748: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7749: 
1.577     banghart 7750: sub get_marked_as_readonly_hash {
1.745     raeburn  7751:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7752:     my %readonly_files;
1.745     raeburn  7753:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7754:         if (defined($group)) {
                   7755:             if ($file_name !~ m-^\Q$group\E/-) {
                   7756:                 next;
                   7757:             }
                   7758:         }
1.577     banghart 7759:         if (ref($value) eq "ARRAY"){
                   7760:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7761:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7762:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7763:                         if ($lock_descriptor eq 'graded') {
                   7764:                             $readonly_files{$file_name} = 'graded';
                   7765:                         } elsif ($lock_descriptor eq 'handback') {
                   7766:                             $readonly_files{$file_name} = 'handback';
                   7767:                         } else {
                   7768:                             if (!exists($readonly_files{$file_name})) {
                   7769:                                 $readonly_files{$file_name} = 'locked';
                   7770:                             }
                   7771:                         }
1.745     raeburn  7772:                     }
1.750     banghart 7773:                 } 
1.577     banghart 7774:             }
                   7775:         } 
                   7776:     }
                   7777:     return %readonly_files;
                   7778: }
1.559     banghart 7779: # ------------------------------------------------------------ Unmark as Read Only
                   7780: 
                   7781: sub unmark_as_readonly {
1.629     banghart 7782:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7783:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7784:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7785:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7786:     my $symb_crs = $what;
                   7787:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7788:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7789:     my ($tmp)=keys(%current_permissions);
                   7790:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7791:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7792:     foreach my $file (@readonly_files) {
1.759     albertel 7793: 	my $clean_file = &declutter_portfile($file);
                   7794: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7795: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7796:         my @new_locks;
                   7797:         my @del_keys;
                   7798:         if (ref($current_locks) eq "ARRAY"){
                   7799:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7800:                 my $compare=$locker;
1.749     raeburn  7801:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7802:                     $compare=join('',@{$locker});
1.746     raeburn  7803:                     if ($compare ne $symb_crs) {
                   7804:                         push(@new_locks, $locker);
                   7805:                     }
1.563     banghart 7806:                 }
                   7807:             }
1.650     albertel 7808:             if (scalar(@new_locks) > 0) {
1.563     banghart 7809:                 $current_permissions{$file} = \@new_locks;
                   7810:             } else {
                   7811:                 push(@del_keys, $file);
1.613     albertel 7812:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7813:                 delete($current_permissions{$file});
1.563     banghart 7814:             }
                   7815:         }
1.561     banghart 7816:     }
1.613     albertel 7817:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7818:     return;
                   7819: }
1.512     banghart 7820: 
1.17      www      7821: # ------------------------------------------------------------ Directory lister
                   7822: 
                   7823: sub dirlist {
1.955     raeburn  7824:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7825:     $uri=~s/^\///;
                   7826:     $uri=~s/\/$//;
1.253     stredwic 7827:     my ($udom, $uname);
1.955     raeburn  7828:     if ($getuserdir) {
1.253     stredwic 7829:         $udom = $userdomain;
                   7830:         $uname = $username;
1.955     raeburn  7831:     } else {
                   7832:         (undef,$udom,$uname)=split(/\//,$uri);
                   7833:         if(defined($userdomain)) {
                   7834:             $udom = $userdomain;
                   7835:         }
                   7836:         if(defined($username)) {
                   7837:             $uname = $username;
                   7838:         }
1.253     stredwic 7839:     }
1.955     raeburn  7840:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7841: 
1.955     raeburn  7842:     $dirRoot = $perlvar{'lonDocRoot'};
                   7843:     if (defined($getpropath)) {
                   7844:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7845:         $dirRoot =~ s/\/$//;
1.955     raeburn  7846:     } elsif (defined($getuserdir)) {
                   7847:         my $subdir=$uname.'__';
                   7848:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7849:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7850:                    ."/$udom/$subdir/$uname";
                   7851:     } elsif (defined($alternateRoot)) {
                   7852:         $dirRoot = $alternateRoot;
1.751     banghart 7853:     }
1.253     stredwic 7854: 
                   7855:     if($udom) {
                   7856:         if($uname) {
1.955     raeburn  7857:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7858:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7859:                               .':'.&escape($uname).':'.&escape($udom),
                   7860:                               &homeserver($uname,$udom));
                   7861:             if ($listing eq 'unknown_cmd') {
                   7862:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7863:                                   &homeserver($uname,$udom));
                   7864:             } else {
                   7865:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7866:             }
1.605     matthew  7867:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7868:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7869: 				  &homeserver($uname,$udom));
1.605     matthew  7870:                 @listing_results = split(/:/,$listing);
                   7871:             } else {
                   7872:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7873:             }
                   7874:             return @listing_results;
1.955     raeburn  7875:         } elsif(!$alternateRoot) {
1.800     albertel 7876:             my %allusers;
1.841     albertel 7877: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7878:  	    foreach my $tryserver (keys(%servers)) {
                   7879:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7880:                                   &escape($udom),$tryserver);
                   7881:                 if ($listing eq 'unknown_cmd') {
                   7882: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7883: 				      $udom, $tryserver);
                   7884:                 } else {
                   7885:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7886:                 }
1.841     albertel 7887: 		if ($listing eq 'unknown_cmd') {
                   7888: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7889: 				      $udom, $tryserver);
                   7890: 		    @listing_results = split(/:/,$listing);
                   7891: 		} else {
                   7892: 		    @listing_results =
                   7893: 			map { &unescape($_); } split(/:/,$listing);
                   7894: 		}
                   7895: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7896: 		    $listing_results[0] ne 'empty'       &&
                   7897: 		    $listing_results[0] ne 'con_lost') {
                   7898: 		    foreach my $line (@listing_results) {
                   7899: 			my ($entry) = split(/&/,$line,2);
                   7900: 			$allusers{$entry} = 1;
                   7901: 		    }
                   7902: 		}
1.253     stredwic 7903:             }
                   7904:             my $alluserstr='';
1.800     albertel 7905:             foreach my $user (sort(keys(%allusers))) {
                   7906:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7907:             }
                   7908:             $alluserstr=~s/:$//;
                   7909:             return split(/:/,$alluserstr);
                   7910:         } else {
1.800     albertel 7911:             return ('missing user name');
1.253     stredwic 7912:         }
1.955     raeburn  7913:     } elsif(!defined($getpropath)) {
1.841     albertel 7914:         my @all_domains = sort(&all_domains());
1.955     raeburn  7915:         foreach my $domain (@all_domains) {
                   7916:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7917:         }
                   7918:         return @all_domains;
                   7919:     } else {
1.800     albertel 7920:         return ('missing domain');
1.275     stredwic 7921:     }
                   7922: }
                   7923: 
                   7924: # --------------------------------------------- GetFileTimestamp
                   7925: # This function utilizes dirlist and returns the date stamp for
                   7926: # when it was last modified.  It will also return an error of -1
                   7927: # if an error occurs
                   7928: 
                   7929: sub GetFileTimestamp {
1.955     raeburn  7930:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7931:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7932:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7933:     my ($fileStat) = 
                   7934:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7935:                                  undef,$getuserdir);
1.275     stredwic 7936:     my @stats = split('&', $fileStat);
                   7937:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7938:         # @stats contains first the filename, then the stat output
                   7939:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7940:     } else {
                   7941:         return -1;
1.253     stredwic 7942:     }
1.26      www      7943: }
                   7944: 
1.712     albertel 7945: sub stat_file {
                   7946:     my ($uri) = @_;
1.787     albertel 7947:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7948: 
1.955     raeburn  7949:     my ($udom,$uname,$file);
1.712     albertel 7950:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7951: 	($udom,$uname,$file) =
1.811     albertel 7952: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7953: 	$file = 'userfiles/'.$file;
                   7954:     }
                   7955:     if ($uri =~ m-^/res/-) {
                   7956: 	($udom,$uname) = 
1.807     albertel 7957: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7958: 	$file = $uri;
                   7959:     }
                   7960: 
                   7961:     if (!$udom || !$uname || !$file) {
                   7962: 	# unable to handle the uri
                   7963: 	return ();
                   7964:     }
1.956     raeburn  7965:     my $getpropath;
                   7966:     if ($file =~ /^userfiles\//) {
                   7967:         $getpropath = 1;
                   7968:     }
1.955     raeburn  7969:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7970:     my @stats = split('&', $result);
1.721     banghart 7971:     
1.712     albertel 7972:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7973: 	shift(@stats); #filename is first
                   7974: 	return @stats;
                   7975:     }
                   7976:     return ();
                   7977: }
                   7978: 
1.26      www      7979: # -------------------------------------------------------- Value of a Condition
                   7980: 
1.713     albertel 7981: # gets the value of a specific preevaluated condition
                   7982: #    stored in the string  $env{user.state.<cid>}
                   7983: # or looks up a condition reference in the bighash and if if hasn't
                   7984: # already been evaluated recurses into docondval to get the value of
                   7985: # the condition, then memoizing it to 
                   7986: #   $env{user.state.<cid>.<condition>}
1.40      www      7987: sub directcondval {
                   7988:     my $number=shift;
1.620     albertel 7989:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7990: 	&Apache::lonuserstate::evalstate();
                   7991:     }
1.713     albertel 7992:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7993: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7994:     } elsif ($number =~ /^_/) {
                   7995: 	my $sub_condition;
                   7996: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7997: 		&GDBM_READER(),0640)) {
                   7998: 	    $sub_condition=$bighash{'conditions'.$number};
                   7999: 	    untie(%bighash);
                   8000: 	}
                   8001: 	my $value = &docondval($sub_condition);
1.949     raeburn  8002: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8003: 	return $value;
                   8004:     }
1.620     albertel 8005:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8006:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8007:     } else {
                   8008:        return 2;
                   8009:     }
                   8010: }
                   8011: 
1.713     albertel 8012: # get the collection of conditions for this resource
1.26      www      8013: sub condval {
                   8014:     my $condidx=shift;
1.54      www      8015:     my $allpathcond='';
1.713     albertel 8016:     foreach my $cond (split(/\|/,$condidx)) {
                   8017: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8018: 	    $allpathcond.=
                   8019: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8020: 	}
1.191     harris41 8021:     }
1.54      www      8022:     $allpathcond=~s/\|$//;
1.713     albertel 8023:     return &docondval($allpathcond);
                   8024: }
                   8025: 
                   8026: #evaluates an expression of conditions
                   8027: sub docondval {
                   8028:     my ($allpathcond) = @_;
                   8029:     my $result=0;
                   8030:     if ($env{'request.course.id'}
                   8031: 	&& defined($allpathcond)) {
                   8032: 	my $operand='|';
                   8033: 	my @stack;
                   8034: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8035: 	    if ($chunk eq '(') {
                   8036: 		push @stack,($operand,$result);
                   8037: 	    } elsif ($chunk eq ')') {
                   8038: 		my $before=pop @stack;
                   8039: 		if (pop @stack eq '&') {
                   8040: 		    $result=$result>$before?$before:$result;
                   8041: 		} else {
                   8042: 		    $result=$result>$before?$result:$before;
                   8043: 		}
                   8044: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8045: 		$operand=$chunk;
                   8046: 	    } else {
                   8047: 		my $new=directcondval($chunk);
                   8048: 		if ($operand eq '&') {
                   8049: 		    $result=$result>$new?$new:$result;
                   8050: 		} else {
                   8051: 		    $result=$result>$new?$result:$new;
                   8052: 		}
                   8053: 	    }
                   8054: 	}
1.26      www      8055:     }
                   8056:     return $result;
1.421     albertel 8057: }
                   8058: 
                   8059: # ---------------------------------------------------- Devalidate courseresdata
                   8060: 
                   8061: sub devalidatecourseresdata {
                   8062:     my ($coursenum,$coursedomain)=@_;
                   8063:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8064:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8065: }
                   8066: 
1.763     www      8067: 
1.200     www      8068: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8069: #
                   8070: #  Parameters:
                   8071: #      $coursenum    - Number of the course.
                   8072: #      $coursedomain - Domain at which the course was created.
                   8073: #  Returns:
                   8074: #     A hash of the course parameters along (I think) with timestamps
                   8075: #     and version info.
1.877     foxr     8076: 
1.624     albertel 8077: sub get_courseresdata {
                   8078:     my ($coursenum,$coursedomain)=@_;
1.200     www      8079:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8080:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8081:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8082:     my %dumpreply;
1.417     albertel 8083:     unless (defined($cached)) {
1.624     albertel 8084: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8085: 	$result=\%dumpreply;
1.251     albertel 8086: 	my ($tmp) = keys(%dumpreply);
                   8087: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8088: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8089: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8090: 	    return $tmp;
1.416     albertel 8091: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8092: 	    $result=undef;
1.599     albertel 8093: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8094: 	}
                   8095:     }
1.624     albertel 8096:     return $result;
                   8097: }
                   8098: 
1.633     albertel 8099: sub devalidateuserresdata {
                   8100:     my ($uname,$udom)=@_;
                   8101:     my $hashid="$udom:$uname";
                   8102:     &devalidate_cache_new('userres',$hashid);
                   8103: }
                   8104: 
1.624     albertel 8105: sub get_userresdata {
                   8106:     my ($uname,$udom)=@_;
                   8107:     #most student don\'t have any data set, check if there is some data
                   8108:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8109: 
                   8110:     my $hashid="$udom:$uname";
                   8111:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8112:     if (!defined($cached)) {
                   8113: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8114: 	$result=\%resourcedata;
                   8115: 	&do_cache_new('userres',$hashid,$result,600);
                   8116:     }
                   8117:     my ($tmp)=keys(%$result);
                   8118:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8119: 	return $result;
                   8120:     }
                   8121:     #error 2 occurs when the .db doesn't exist
                   8122:     if ($tmp!~/error: 2 /) {
1.672     albertel 8123: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8124: 		 " Trying to get resource data for ".
                   8125: 		 $uname." at ".$udom.": ".
                   8126: 		 $tmp."</font>");
                   8127:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8128: 	#&EXT_cache_set($udom,$uname);
                   8129: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8130: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8131:     }
                   8132:     return $tmp;
                   8133: }
1.879     foxr     8134: #----------------------------------------------- resdata - return resource data
                   8135: #  Purpose:
                   8136: #    Return resource data for either users or for a course.
                   8137: #  Parameters:
                   8138: #     $name      - Course/user name.
                   8139: #     $domain    - Name of the domain the user/course is registered on.
                   8140: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8141: #     @which     - Array of names of resources desired.
                   8142: #  Returns:
                   8143: #     The value of the first reasource in @which that is found in the
                   8144: #     resource hash.
                   8145: #  Exceptional Conditions:
                   8146: #     If the $type passed in is not valid (not the string 'course' or 
                   8147: #     'user', an undefined  reference is returned.
                   8148: #     If none of the resources are found, an undef is returned
1.624     albertel 8149: sub resdata {
                   8150:     my ($name,$domain,$type,@which)=@_;
                   8151:     my $result;
                   8152:     if ($type eq 'course') {
                   8153: 	$result=&get_courseresdata($name,$domain);
                   8154:     } elsif ($type eq 'user') {
                   8155: 	$result=&get_userresdata($name,$domain);
                   8156:     }
                   8157:     if (!ref($result)) { return $result; }    
1.251     albertel 8158:     foreach my $item (@which) {
1.927     albertel 8159: 	if (defined($result->{$item->[0]})) {
                   8160: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8161: 	}
1.250     albertel 8162:     }
1.291     albertel 8163:     return undef;
1.200     www      8164: }
                   8165: 
1.379     matthew  8166: #
                   8167: # EXT resource caching routines
                   8168: #
                   8169: 
                   8170: sub clear_EXT_cache_status {
1.383     albertel 8171:     &delenv('cache.EXT.');
1.379     matthew  8172: }
                   8173: 
                   8174: sub EXT_cache_status {
                   8175:     my ($target_domain,$target_user) = @_;
1.383     albertel 8176:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8177:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8178:         # We know already the user has no data
                   8179:         return 1;
                   8180:     } else {
                   8181:         return 0;
                   8182:     }
                   8183: }
                   8184: 
                   8185: sub EXT_cache_set {
                   8186:     my ($target_domain,$target_user) = @_;
1.383     albertel 8187:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8188:     #&appenv({$cachename => time});
1.379     matthew  8189: }
                   8190: 
1.28      www      8191: # --------------------------------------------------------- Value of a Variable
1.58      www      8192: sub EXT {
1.715     albertel 8193: 
1.395     albertel 8194:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8195:     unless ($varname) { return ''; }
1.218     albertel 8196:     #get real user name/domain, courseid and symb
                   8197:     my $courseid;
1.359     albertel 8198:     my $publicuser;
1.427     www      8199:     if ($symbparm) {
                   8200: 	$symbparm=&get_symb_from_alias($symbparm);
                   8201:     }
1.218     albertel 8202:     if (!($uname && $udom)) {
1.790     albertel 8203:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8204:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8205:     } else {
1.620     albertel 8206: 	$courseid=$env{'request.course.id'};
1.218     albertel 8207:     }
1.48      www      8208:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8209:     my $rest;
1.320     albertel 8210:     if (defined($therest[0])) {
1.48      www      8211:        $rest=join('.',@therest);
                   8212:     } else {
                   8213:        $rest='';
                   8214:     }
1.320     albertel 8215: 
1.57      www      8216:     my $qualifierrest=$qualifier;
                   8217:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8218:     my $spacequalifierrest=$space;
                   8219:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8220:     if ($realm eq 'user') {
1.48      www      8221: # --------------------------------------------------------------- user.resource
                   8222: 	if ($space eq 'resource') {
1.651     albertel 8223: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8224: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8225: 		 &&
1.744     albertel 8226: 		 ($symbparm eq &symbread()) ) {	
                   8227: 		# if we are in the middle of processing the resource the
                   8228: 		# get the value we are planning on committing
                   8229:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8230:                     return $Apache::lonhomework::results{$qualifierrest};
                   8231:                 } else {
                   8232:                     return $Apache::lonhomework::history{$qualifierrest};
                   8233:                 }
1.335     albertel 8234: 	    } else {
1.359     albertel 8235: 		my %restored;
1.620     albertel 8236: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8237: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8238: 		} else {
                   8239: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8240: 		}
1.335     albertel 8241: 		return $restored{$qualifierrest};
                   8242: 	    }
1.48      www      8243: # ----------------------------------------------------------------- user.access
                   8244:         } elsif ($space eq 'access') {
1.218     albertel 8245: 	    # FIXME - not supporting calls for a specific user
1.48      www      8246:             return &allowed($qualifier,$rest);
                   8247: # ------------------------------------------ user.preferences, user.environment
                   8248:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8249: 	    if (($uname eq $env{'user.name'}) &&
                   8250: 		($udom eq $env{'user.domain'})) {
                   8251: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8252: 	    } else {
1.359     albertel 8253: 		my %returnhash;
                   8254: 		if (!$publicuser) {
                   8255: 		    %returnhash=&userenvironment($udom,$uname,
                   8256: 						 $qualifierrest);
                   8257: 		}
1.218     albertel 8258: 		return $returnhash{$qualifierrest};
                   8259: 	    }
1.48      www      8260: # ----------------------------------------------------------------- user.course
                   8261:         } elsif ($space eq 'course') {
1.218     albertel 8262: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8263:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8264: # ------------------------------------------------------------------- user.role
                   8265:         } elsif ($space eq 'role') {
1.218     albertel 8266: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8267:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8268:             if ($qualifier eq 'value') {
                   8269: 		return $role;
                   8270:             } elsif ($qualifier eq 'extent') {
                   8271:                 return $where;
                   8272:             }
                   8273: # ----------------------------------------------------------------- user.domain
                   8274:         } elsif ($space eq 'domain') {
1.218     albertel 8275:             return $udom;
1.48      www      8276: # ------------------------------------------------------------------- user.name
                   8277:         } elsif ($space eq 'name') {
1.218     albertel 8278:             return $uname;
1.48      www      8279: # ---------------------------------------------------- Any other user namespace
1.29      www      8280:         } else {
1.359     albertel 8281: 	    my %reply;
                   8282: 	    if (!$publicuser) {
                   8283: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8284: 	    }
                   8285: 	    return $reply{$qualifierrest};
1.48      www      8286:         }
1.236     www      8287:     } elsif ($realm eq 'query') {
                   8288: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8289:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8290: 						[$spacequalifierrest]);
1.620     albertel 8291: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8292:    } elsif ($realm eq 'request') {
1.48      www      8293: # ------------------------------------------------------------- request.browser
                   8294:         if ($space eq 'browser') {
1.430     www      8295: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8296: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8297: 		    return 1;
                   8298: 		} else {
                   8299: 		    return 0;
                   8300: 		}
                   8301: 	    } else {
1.620     albertel 8302: 		return $env{'browser.'.$qualifier};
1.430     www      8303: 	    }
1.57      www      8304: # ------------------------------------------------------------ request.filename
                   8305:         } else {
1.620     albertel 8306:             return $env{'request.'.$spacequalifierrest};
1.29      www      8307:         }
1.28      www      8308:     } elsif ($realm eq 'course') {
1.48      www      8309: # ---------------------------------------------------------- course.description
1.620     albertel 8310:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8311:     } elsif ($realm eq 'resource') {
1.165     www      8312: 
1.620     albertel 8313: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8314: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8315: 	}
1.693     albertel 8316: 
                   8317: 	if ($space eq 'title') {
                   8318: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8319: 	    return &gettitle($symbparm);
                   8320: 	}
                   8321: 	
                   8322: 	if ($space eq 'map') {
                   8323: 	    my ($map) = &decode_symb($symbparm);
                   8324: 	    return &symbread($map);
                   8325: 	}
1.905     albertel 8326: 	if ($space eq 'filename') {
                   8327: 	    if ($symbparm) {
                   8328: 		return &clutter((&decode_symb($symbparm))[2]);
                   8329: 	    }
                   8330: 	    return &hreflocation('',$env{'request.filename'});
                   8331: 	}
1.693     albertel 8332: 
                   8333: 	my ($section, $group, @groups);
1.593     albertel 8334: 	my ($courselevelm,$courselevel);
1.539     albertel 8335: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8336: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8337: 
1.218     albertel 8338: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8339: 
1.60      www      8340: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8341: 	    my $symbp=$symbparm;
1.735     albertel 8342: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8343: 
                   8344: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8345: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8346: 
1.620     albertel 8347: 	    if (($env{'user.name'} eq $uname) &&
                   8348: 		($env{'user.domain'} eq $udom)) {
                   8349: 		$section=$env{'request.course.sec'};
1.733     raeburn  8350:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8351:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8352: 	    } else {
1.539     albertel 8353: 		if (! defined($usection)) {
1.551     albertel 8354: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8355: 		} else {
                   8356: 		    $section = $usection;
                   8357: 		}
1.733     raeburn  8358:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8359: 	    }
                   8360: 
                   8361: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8362: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8363: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8364: 
1.593     albertel 8365: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8366: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8367: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8368: 
1.60      www      8369: # ----------------------------------------------------------- first, check user
1.624     albertel 8370: 
                   8371: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8372: 				       ([$courselevelr,'resource'],
                   8373: 					[$courselevelm,'map'     ],
                   8374: 					[$courselevel, 'course'  ]));
1.931     albertel 8375: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8376: 
1.594     albertel 8377: # ------------------------------------------------ second, check some of course
1.684     raeburn  8378:             my $coursereply;
1.691     raeburn  8379:             if (@groups > 0) {
                   8380:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8381:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8382:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8383:             }
1.96      www      8384: 
1.684     raeburn  8385: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8386: 				  $env{'course.'.$courseid.'.domain'},
                   8387: 				  'course',
                   8388: 				  ([$seclevelr,   'resource'],
                   8389: 				   [$seclevelm,   'map'     ],
                   8390: 				   [$seclevel,    'course'  ],
                   8391: 				   [$courselevelr,'resource']));
                   8392: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8393: 
1.60      www      8394: # ------------------------------------------------------ third, check map parms
1.218     albertel 8395: 	    my %parmhash=();
                   8396: 	    my $thisparm='';
                   8397: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8398: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8399: 		    &GDBM_READER(),0640)) {
1.218     albertel 8400: 		$thisparm=$parmhash{$symbparm};
                   8401: 		untie(%parmhash);
                   8402: 	    }
1.927     albertel 8403: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8404: 	}
1.594     albertel 8405: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8406: 
1.218     albertel 8407: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8408: 	my $filename;
                   8409: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8410: 	if ($symbparm) {
1.409     www      8411: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8412: 	} else {
1.620     albertel 8413: 	    $filename=$env{'request.filename'};
1.282     albertel 8414: 	}
                   8415: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8416: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8417: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8418: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8419: 
1.927     albertel 8420: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8421: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8422: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8423: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8424: 				     $env{'course.'.$courseid.'.domain'},
                   8425: 				     'course',
1.927     albertel 8426: 				     ([$courselevelm,'map'   ],
                   8427: 				      [$courselevel, 'course']));
                   8428: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8429: 	}
1.145     www      8430: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8431: 	unless ($space eq '0') {
1.336     albertel 8432: 	    my @parts=split(/_/,$space);
                   8433: 	    my $id=pop(@parts);
                   8434: 	    my $part=join('_',@parts);
                   8435: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8436: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8437: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8438: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8439: 	}
1.395     albertel 8440: 	if ($recurse) { return undef; }
                   8441: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8442: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8443: # ---------------------------------------------------- Any other user namespace
                   8444:     } elsif ($realm eq 'environment') {
                   8445: # ----------------------------------------------------------------- environment
1.620     albertel 8446: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8447: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8448: 	} else {
1.770     albertel 8449: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8450: 		return '';
                   8451: 	    }
1.219     albertel 8452: 	    my %returnhash=&userenvironment($udom,$uname,
                   8453: 					    $spacequalifierrest);
                   8454: 	    return $returnhash{$spacequalifierrest};
                   8455: 	}
1.28      www      8456:     } elsif ($realm eq 'system') {
1.48      www      8457: # ----------------------------------------------------------------- system.time
                   8458: 	if ($space eq 'time') {
                   8459: 	    return time;
                   8460:         }
1.696     albertel 8461:     } elsif ($realm eq 'server') {
                   8462: # ----------------------------------------------------------------- system.time
                   8463: 	if ($space eq 'name') {
                   8464: 	    return $ENV{'SERVER_NAME'};
                   8465:         }
1.28      www      8466:     }
1.48      www      8467:     return '';
1.61      www      8468: }
                   8469: 
1.927     albertel 8470: sub get_reply {
                   8471:     my ($reply_value) = @_;
1.940     raeburn  8472:     if (ref($reply_value) eq 'ARRAY') {
                   8473:         if (wantarray) {
                   8474: 	    return @$reply_value;
                   8475:         }
                   8476:         return $reply_value->[0];
                   8477:     } else {
                   8478:         return $reply_value;
1.927     albertel 8479:     }
                   8480: }
                   8481: 
1.691     raeburn  8482: sub check_group_parms {
                   8483:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8484:     my @groupitems = ();
                   8485:     my $resultitem;
1.927     albertel 8486:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8487:     foreach my $group (@{$groups}) {
                   8488:         foreach my $level (@levels) {
1.927     albertel 8489:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8490:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8491:         }
                   8492:     }
                   8493:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8494:                             $env{'course.'.$courseid.'.domain'},
                   8495:                                      'course',@groupitems);
                   8496:     return $coursereply;
                   8497: }
                   8498: 
                   8499: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8500:     my ($courseid,@groups) = @_;
                   8501:     @groups = sort(@groups);
1.691     raeburn  8502:     return @groups;
                   8503: }
                   8504: 
1.395     albertel 8505: sub packages_tab_default {
                   8506:     my ($uri,$varname)=@_;
                   8507:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8508: 
                   8509:     my (@extension,@specifics,$do_default);
                   8510:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8511: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8512: 	if ($pack_type eq 'default') {
                   8513: 	    $do_default=1;
                   8514: 	} elsif ($pack_type eq 'extension') {
                   8515: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8516: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8517: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8518: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8519: 	}
                   8520:     }
                   8521:     # first look for a package that matches the requested part id
                   8522:     foreach my $package (@specifics) {
                   8523: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8524: 	next if ($pack_part ne $part);
                   8525: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8526: 	    return $packagetab{"$pack_type&$name&default"};
                   8527: 	}
                   8528:     }
                   8529:     # look for any possible matching non extension_ package
                   8530:     foreach my $package (@specifics) {
                   8531: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8532: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8533: 	    return $packagetab{"$pack_type&$name&default"};
                   8534: 	}
1.585     albertel 8535: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8536: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8537: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8538: 	}
                   8539:     }
1.738     albertel 8540:     # look for any posible extension_ match
                   8541:     foreach my $package (@extension) {
                   8542: 	my ($package,$pack_type)=@{$package};
                   8543: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8544: 	    return $packagetab{"$pack_type&$name&default"};
                   8545: 	}
                   8546: 	if (defined($packagetab{$package."&$name&default"})) {
                   8547: 	    return $packagetab{$package."&$name&default"};
                   8548: 	}
                   8549:     }
                   8550:     # look for a global default setting
                   8551:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8552: 	return $packagetab{"default&$name&default"};
                   8553:     }
1.395     albertel 8554:     return undef;
                   8555: }
                   8556: 
1.334     albertel 8557: sub add_prefix_and_part {
                   8558:     my ($prefix,$part)=@_;
                   8559:     my $keyroot;
                   8560:     if (defined($prefix) && $prefix !~ /^__/) {
                   8561: 	# prefix that has a part already
                   8562: 	$keyroot=$prefix;
                   8563:     } elsif (defined($prefix)) {
                   8564: 	# prefix that is missing a part
                   8565: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8566:     } else {
                   8567: 	# no prefix at all
                   8568: 	if (defined($part)) { $keyroot='_'.$part; }
                   8569:     }
                   8570:     return $keyroot;
                   8571: }
                   8572: 
1.71      www      8573: # ---------------------------------------------------------------- Get metadata
                   8574: 
1.599     albertel 8575: my %metaentry;
1.1070    www      8576: my %importedpartids;
1.71      www      8577: sub metadata {
1.176     www      8578:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8579:     $uri=&declutter($uri);
1.288     albertel 8580:     # if it is a non metadata possible uri return quickly
1.529     albertel 8581:     if (($uri eq '') || 
                   8582: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8583: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8584:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8585: 	return undef;
                   8586:     }
                   8587:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8588: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8589: 	return undef;
1.288     albertel 8590:     }
1.73      www      8591:     my $filename=$uri;
                   8592:     $uri=~s/\.meta$//;
1.172     www      8593: #
                   8594: # Is the metadata already cached?
1.177     www      8595: # Look at timestamp of caching
1.172     www      8596: # Everything is cached by the main uri, libraries are never directly cached
                   8597: #
1.428     albertel 8598:     if (!defined($liburi)) {
1.599     albertel 8599: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8600: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8601:     }
                   8602:     {
1.1069    www      8603: # Imported parts would go here
1.1070    www      8604:         my %importedids=();
                   8605:         my @origfileimportpartids=();
1.1069    www      8606:         my $importedparts=0;
1.172     www      8607: #
                   8608: # Is this a recursive call for a library?
                   8609: #
1.599     albertel 8610: #	if (! exists($metacache{$uri})) {
                   8611: #	    $metacache{$uri}={};
                   8612: #	}
1.924     albertel 8613: 	my $cachetime = 60*60;
1.171     www      8614:         if ($liburi) {
                   8615: 	    $liburi=&declutter($liburi);
                   8616:             $filename=$liburi;
1.401     bowersj2 8617:         } else {
1.599     albertel 8618: 	    &devalidate_cache_new('meta',$uri);
                   8619: 	    undef(%metaentry);
1.401     bowersj2 8620: 	}
1.140     www      8621:         my %metathesekeys=();
1.73      www      8622:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8623: 	my $metastring;
1.924     albertel 8624: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8625: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8626: 	    $metastring = 
1.929     albertel 8627: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8628: 					  ('grade_target' => 'meta'));
                   8629: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8630: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8631:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8632: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8633: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8634: 	    $metastring=&getfile($file);
1.489     albertel 8635: 	}
1.208     albertel 8636:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8637:         my $token;
1.140     www      8638:         undef %metathesekeys;
1.71      www      8639:         while ($token=$parser->get_token) {
1.339     albertel 8640: 	    if ($token->[0] eq 'S') {
                   8641: 		if (defined($token->[2]->{'package'})) {
1.172     www      8642: #
                   8643: # This is a package - get package info
                   8644: #
1.339     albertel 8645: 		    my $package=$token->[2]->{'package'};
                   8646: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8647: 		    if (defined($token->[2]->{'id'})) { 
                   8648: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8649: 		    }
1.599     albertel 8650: 		    if ($metaentry{':packages'}) {
                   8651: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8652: 		    } else {
1.599     albertel 8653: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8654: 		    }
1.736     albertel 8655: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8656: 			my $part=$keyroot;
                   8657: 			$part=~s/^\_//;
1.736     albertel 8658: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8659: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8660: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8661: 			    # ignore package.tab specified default values
                   8662:                             # here &package_tab_default() will fetch those
                   8663: 			    if ($subp eq 'default') { next; }
1.736     albertel 8664: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8665: 			    my $unikey;
                   8666: 			    if ($pack =~ /_0$/) {
                   8667: 				$unikey='parameter_0_'.$name;
                   8668: 				$part=0;
                   8669: 			    } else {
                   8670: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8671: 			    }
1.339     albertel 8672: 			    if ($subp eq 'display') {
                   8673: 				$value.=' [Part: '.$part.']';
                   8674: 			    }
1.599     albertel 8675: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8676: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8677: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8678: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8679: 			    }
1.599     albertel 8680: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8681: 				$metaentry{':'.$unikey}=
                   8682: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8683: 			    }
1.339     albertel 8684: 			}
                   8685: 		    }
                   8686: 		} else {
1.172     www      8687: #
                   8688: # This is not a package - some other kind of start tag
1.339     albertel 8689: #
                   8690: 		    my $entry=$token->[1];
1.1068    www      8691: 		    my $unikey='';
1.175     www      8692: 
1.339     albertel 8693: 		    if ($entry eq 'import') {
1.175     www      8694: #
                   8695: # Importing a library here
1.339     albertel 8696: #
1.1067    www      8697:                         my $location=$parser->get_text('/import');
                   8698:                         my $dir=$filename;
                   8699:                         $dir=~s|[^/]*$||;
                   8700:                         $location=&filelocation($dir,$location);
1.1069    www      8701:                        
1.1068    www      8702:                         my $importmode=$token->[2]->{'importmode'};
                   8703:                         if ($importmode eq 'problem') {
1.1069    www      8704: # Import as problem/response
1.1068    www      8705:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8706:                         } elsif ($importmode eq 'part') {
                   8707: # Import as part(s)
1.1069    www      8708:                            $importedparts=1;
                   8709: # We need to get the original file and the imported file to get the part order correct
                   8710: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8711: # Load and inspect original file
1.1070    www      8712:                            if ($#origfileimportpartids<0) {
                   8713:                               undef(%importedpartids);
                   8714:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8715:                               my $origfile=&getfile($origfilelocation);
                   8716:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8717:                            }
                   8718: 
1.1069    www      8719: # Load and inspect imported file
                   8720:                            my $impfile=&getfile($location);
                   8721:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8722:                            if ($#impfilepartids>=0) {
                   8723: # This problem had parts
1.1070    www      8724:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8725:                            } else {
                   8726: # Importing by turning a single problem into a problem part
                   8727: # It gets the import-tags ID as part-ID
                   8728:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8729:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8730:                            }
1.1068    www      8731:                         } else {
                   8732: # Normal import
                   8733:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8734:                            if (defined($token->[2]->{'id'})) {
                   8735:                               $unikey.='_'.$token->[2]->{'id'};
                   8736:                            }
1.1067    www      8737:                         }
                   8738: 
1.339     albertel 8739: 			if ($depthcount<20) {
1.736     albertel 8740: 			    my $metadata = 
                   8741: 				&metadata($uri,'keys', $location,$unikey,
                   8742: 					  $depthcount+1);
                   8743: 			    foreach my $meta (split(',',$metadata)) {
                   8744: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8745: 				$metathesekeys{$meta}=1;
1.339     albertel 8746: 			    }
1.1068    www      8747: 			
                   8748:                         }
1.1067    www      8749: 		    } else {
                   8750: #
                   8751: # Not importing, some other kind of non-package, non-library start tag
                   8752: # 
                   8753:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8754:                         if (defined($token->[2]->{'id'})) {
                   8755:                             $unikey.='_'.$token->[2]->{'id'};
                   8756:                         }
1.339     albertel 8757: 			if (defined($token->[2]->{'name'})) { 
                   8758: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8759: 			}
                   8760: 			$metathesekeys{$unikey}=1;
1.736     albertel 8761: 			foreach my $param (@{$token->[3]}) {
                   8762: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8763: 				$token->[2]->{$param};
1.339     albertel 8764: 			}
                   8765: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8766: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8767: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8768: 		 # only ws inside the tag, and not in default, so use default
                   8769: 		 # as value
1.599     albertel 8770: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8771: 			} elsif ( $internaltext =~ /\S/ ) {
                   8772: 		  # something interesting inside the tag
                   8773: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8774: 			} else {
1.908     albertel 8775: 		  # no interesting values, don't set a default
1.339     albertel 8776: 			}
1.172     www      8777: # end of not-a-package not-a-library import
1.339     albertel 8778: 		    }
1.172     www      8779: # end of not-a-package start tag
1.339     albertel 8780: 		}
1.172     www      8781: # the next is the end of "start tag"
1.339     albertel 8782: 	    }
                   8783: 	}
1.483     albertel 8784: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8785: 	$extension = lc($extension);
                   8786: 	if ($extension eq 'htm') { $extension='html'; }
                   8787: 
1.737     albertel 8788: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8789: 	    #no specific packages #how's our extension
                   8790: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8791: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8792: 					 \%metathesekeys);
                   8793: 	}
1.883     albertel 8794: 
                   8795: 	if (!exists($metaentry{':packages'})
                   8796: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8797: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8798: 		#no specific packages well let's get default then
                   8799: 		if ($key!~/^default&/) { next; }
1.488     albertel 8800: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8801: 					     \%metathesekeys);
                   8802: 	    }
                   8803: 	}
1.338     www      8804: # are there custom rights to evaluate
1.599     albertel 8805: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8806: 
1.338     www      8807:     #
                   8808:     # Importing a rights file here
1.339     albertel 8809:     #
                   8810: 	    unless ($depthcount) {
1.599     albertel 8811: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8812: 		my $dir=$filename;
                   8813: 		$dir=~s|[^/]*$||;
                   8814: 		$location=&filelocation($dir,$location);
1.736     albertel 8815: 		my $rights_metadata =
                   8816: 		    &metadata($uri,'keys',$location,'_rights',
                   8817: 			      $depthcount+1);
                   8818: 		foreach my $rights (split(',',$rights_metadata)) {
                   8819: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8820: 		    $metathesekeys{$rights}=1;
1.339     albertel 8821: 		}
                   8822: 	    }
                   8823: 	}
1.737     albertel 8824: 	# uniqifiy package listing
                   8825: 	my %seen;
                   8826: 	my @uniq_packages =
                   8827: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8828: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8829: 
1.1070    www      8830:         if ($importedparts) {
                   8831: # We had imported parts and need to rebuild partorder
                   8832:            $metaentry{':partorder'}='';
                   8833:            $metathesekeys{'partorder'}=1;
                   8834:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8835:                if ($origfileimportpartids[$index] eq 'part') {
                   8836: # original part, part of the problem
                   8837:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8838:                } else {
                   8839: # we have imported parts at this position
                   8840:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8841:                }
                   8842:            }
                   8843:            $metaentry{':partorder'}=~s/^\,//;
                   8844:         }
                   8845: 
1.737     albertel 8846: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8847: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8848: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8849: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8850: # this is the end of "was not already recently cached
1.71      www      8851:     }
1.599     albertel 8852:     return $metaentry{':'.$what};
1.261     albertel 8853: }
                   8854: 
1.488     albertel 8855: sub metadata_create_package_def {
1.483     albertel 8856:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8857:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8858:     if ($subp eq 'default') { next; }
                   8859:     
1.599     albertel 8860:     if (defined($metaentry{':packages'})) {
                   8861: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8862:     } else {
1.599     albertel 8863: 	$metaentry{':packages'}=$package;
1.483     albertel 8864:     }
                   8865:     my $value=$packagetab{$key};
                   8866:     my $unikey;
                   8867:     $unikey='parameter_0_'.$name;
1.599     albertel 8868:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8869:     $$metathesekeys{$unikey}=1;
1.599     albertel 8870:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8871: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8872:     }
1.599     albertel 8873:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8874: 	$metaentry{':'.$unikey}=
                   8875: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8876:     }
                   8877: }
                   8878: 
1.261     albertel 8879: sub metadata_generate_part0 {
                   8880:     my ($metadata,$metacache,$uri) = @_;
                   8881:     my %allnames;
1.737     albertel 8882:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8883: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8884: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8885: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8886: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8887: 	    $allnames{$name}=$part;
                   8888: 	  }
                   8889: 	}
                   8890:     }
                   8891:     foreach my $name (keys(%allnames)) {
                   8892:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8893:       my $key=":parameter_0_$name";
1.261     albertel 8894:       $$metacache{"$key.part"}='0';
                   8895:       $$metacache{"$key.name"}=$name;
1.428     albertel 8896:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8897: 					   $allnames{$name}.'_'.$name.
                   8898: 					   '.type'};
1.428     albertel 8899:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8900: 			     '.display'};
1.644     www      8901:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8902:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8903:       $$metacache{"$key.display"}=$olddis;
                   8904:     }
1.71      www      8905: }
                   8906: 
1.764     albertel 8907: # ------------------------------------------------------ Devalidate title cache
                   8908: 
                   8909: sub devalidate_title_cache {
                   8910:     my ($url)=@_;
                   8911:     if (!$env{'request.course.id'}) { return; }
                   8912:     my $symb=&symbread($url);
                   8913:     if (!$symb) { return; }
                   8914:     my $key=$env{'request.course.id'}."\0".$symb;
                   8915:     &devalidate_cache_new('title',$key);
                   8916: }
                   8917: 
1.1014    droeschl 8918: # ------------------------------------------------- Get the title of a course
                   8919: 
                   8920: sub current_course_title {
                   8921:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8922: }
1.301     www      8923: # ------------------------------------------------- Get the title of a resource
                   8924: 
                   8925: sub gettitle {
                   8926:     my $urlsymb=shift;
                   8927:     my $symb=&symbread($urlsymb);
1.534     albertel 8928:     if ($symb) {
1.620     albertel 8929: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8930: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8931: 	if (defined($cached)) { 
                   8932: 	    return $result;
                   8933: 	}
1.534     albertel 8934: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8935: 	my $title='';
1.907     albertel 8936: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8937: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8938: 	} else {
                   8939: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8940: 		    &GDBM_READER(),0640)) {
                   8941: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8942: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8943: 		untie(%bighash);
                   8944: 	    }
1.534     albertel 8945: 	}
                   8946: 	$title=~s/\&colon\;/\:/gs;
                   8947: 	if ($title) {
1.599     albertel 8948: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8949: 	}
                   8950: 	$urlsymb=$url;
                   8951:     }
                   8952:     my $title=&metadata($urlsymb,'title');
                   8953:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8954:     return $title;
1.301     www      8955: }
1.613     albertel 8956: 
1.614     albertel 8957: sub get_slot {
                   8958:     my ($which,$cnum,$cdom)=@_;
                   8959:     if (!$cnum || !$cdom) {
1.790     albertel 8960: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8961: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8962: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8963:     }
1.703     albertel 8964:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8965:     my %slotinfo;
                   8966:     if (exists($remembered{$key})) {
                   8967: 	$slotinfo{$which} = $remembered{$key};
                   8968:     } else {
                   8969: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8970: 	&Apache::lonhomework::showhash(%slotinfo);
                   8971: 	my ($tmp)=keys(%slotinfo);
                   8972: 	if ($tmp=~/^error:/) { return (); }
                   8973: 	$remembered{$key} = $slotinfo{$which};
                   8974:     }
1.616     albertel 8975:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8976: 	return %{$slotinfo{$which}};
                   8977:     }
                   8978:     return $slotinfo{$which};
1.614     albertel 8979: }
1.31      www      8980: # ------------------------------------------------- Update symbolic store links
                   8981: 
                   8982: sub symblist {
                   8983:     my ($mapname,%newhash)=@_;
1.438     www      8984:     $mapname=&deversion(&declutter($mapname));
1.31      www      8985:     my %hash;
1.620     albertel 8986:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8987:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8988:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8989: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8990: 		next if ($url eq 'last_known'
                   8991: 			 && $env{'form.no_update_last_known'});
                   8992: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8993: 						    $newhash{$url}->[1],
                   8994: 						    $newhash{$url}->[0]);
1.191     harris41 8995:             }
1.31      www      8996:             if (untie(%hash)) {
                   8997: 		return 'ok';
                   8998:             }
                   8999:         }
                   9000:     }
                   9001:     return 'error';
1.212     www      9002: }
                   9003: 
                   9004: # --------------------------------------------------------------- Verify a symb
                   9005: 
                   9006: sub symbverify {
1.510     www      9007:     my ($symb,$thisurl)=@_;
                   9008:     my $thisfn=$thisurl;
1.439     www      9009:     $thisfn=&declutter($thisfn);
1.215     www      9010: # direct jump to resource in page or to a sequence - will construct own symbs
                   9011:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9012: # check URL part
1.409     www      9013:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9014: 
1.431     www      9015:     unless ($url eq $thisfn) { return 0; }
1.213     www      9016: 
1.216     www      9017:     $symb=&symbclean($symb);
1.510     www      9018:     $thisurl=&deversion($thisurl);
1.439     www      9019:     $thisfn=&deversion($thisfn);
1.213     www      9020: 
                   9021:     my %bighash;
                   9022:     my $okay=0;
1.431     www      9023: 
1.620     albertel 9024:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9025:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9026:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9027:             $thisurl =~ s/\?.+$//;
                   9028:         }
1.510     www      9029:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9030:         unless ($ids) {
                   9031:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9032:             $ids=$bighash{$idkey};
1.216     www      9033:         }
                   9034:         if ($ids) {
                   9035: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9036: 	    foreach my $id (split(/\,/,$ids)) {
                   9037: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9038:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9039:                    $symb =~ s/\?.+$//;
                   9040:                }
1.216     www      9041:                if (
                   9042:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9043:    eq $symb) { 
1.620     albertel 9044: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9045: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9046:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9047: 		       $okay=1; 
                   9048: 		   }
                   9049: 	       }
1.216     www      9050: 	   }
                   9051:         }
1.213     www      9052: 	untie(%bighash);
                   9053:     }
                   9054:     return $okay;
1.31      www      9055: }
                   9056: 
1.210     www      9057: # --------------------------------------------------------------- Clean-up symb
                   9058: 
                   9059: sub symbclean {
                   9060:     my $symb=shift;
1.568     albertel 9061:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9062: # remove version from map
                   9063:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9064: 
1.210     www      9065: # remove version from URL
                   9066:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9067: 
1.507     www      9068: # remove wrapper
                   9069: 
1.510     www      9070:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9071:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9072:     return $symb;
1.409     www      9073: }
                   9074: 
                   9075: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9076: 
                   9077: sub encode_symb {
                   9078:     my ($map,$resid,$url)=@_;
                   9079:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9080: }
1.409     www      9081: 
                   9082: sub decode_symb {
1.568     albertel 9083:     my $symb=shift;
                   9084:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9085:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9086:     return (&fixversion($map),$resid,&fixversion($url));
                   9087: }
                   9088: 
                   9089: sub fixversion {
                   9090:     my $fn=shift;
1.609     banghart 9091:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9092:     my %bighash;
                   9093:     my $uri=&clutter($fn);
1.620     albertel 9094:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9095: # is this cached?
1.599     albertel 9096:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9097:     if (defined($cached)) { return $result; }
                   9098: # unfortunately not cached, or expired
1.620     albertel 9099:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9100: 	    &GDBM_READER(),0640)) {
                   9101:  	if ($bighash{'version_'.$uri}) {
                   9102:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9103:  	    unless (($version eq 'mostrecent') || 
                   9104: 		    ($version==&getversion($uri))) {
1.440     www      9105:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9106:  	    }
                   9107:  	}
                   9108:  	untie %bighash;
1.413     www      9109:     }
1.599     albertel 9110:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9111: }
                   9112: 
                   9113: sub deversion {
                   9114:     my $url=shift;
                   9115:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9116:     return $url;
1.210     www      9117: }
                   9118: 
1.31      www      9119: # ------------------------------------------------------ Return symb list entry
                   9120: 
                   9121: sub symbread {
1.249     www      9122:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9123:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9124:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9125: # no filename provided? try from environment
1.44      www      9126:     unless ($thisfn) {
1.620     albertel 9127:         if ($env{'request.symb'}) {
                   9128: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9129: 	}
1.620     albertel 9130: 	$thisfn=$env{'request.filename'};
1.44      www      9131:     }
1.569     albertel 9132:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9133: # is that filename actually a symb? Verify, clean, and return
                   9134:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9135: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9136: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9137: 	}
1.242     www      9138:     }
1.44      www      9139:     $thisfn=declutter($thisfn);
1.31      www      9140:     my %hash;
1.37      www      9141:     my %bighash;
                   9142:     my $syval='';
1.620     albertel 9143:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9144:         my $targetfn = $thisfn;
1.609     banghart 9145:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9146:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9147:         }
1.687     albertel 9148: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9149: 	    $targetfn=$1;
                   9150: 	}
1.620     albertel 9151:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9152:                       &GDBM_READER(),0640)) {
1.481     raeburn  9153: 	    $syval=$hash{$targetfn};
1.37      www      9154:             untie(%hash);
                   9155:         }
                   9156: # ---------------------------------------------------------- There was an entry
                   9157:         if ($syval) {
1.601     albertel 9158: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9159: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9160: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9161: 		    #return $env{$cache_str}='';
1.601     albertel 9162: 		#}    
                   9163: 		#$syval.=$1;
                   9164: 	    #}
1.37      www      9165:         } else {
                   9166: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9167:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9168:                             &GDBM_READER(),0640)) {
1.37      www      9169: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9170:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9171:               unless ($ids) { 
                   9172:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9173:               }
                   9174:               unless ($ids) {
                   9175: # alias?
                   9176: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9177:               }
1.37      www      9178:               if ($ids) {
                   9179: # ------------------------------------------------------------------- Has ID(s)
                   9180:                  my @possibilities=split(/\,/,$ids);
1.39      www      9181:                  if ($#possibilities==0) {
                   9182: # ----------------------------------------------- There is only one possibility
1.37      www      9183: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9184: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9185: 						    $resid,$thisfn);
1.249     www      9186:                  } elsif (!$donotrecurse) {
1.39      www      9187: # ------------------------------------------ There is more than one possibility
                   9188:                      my $realpossible=0;
1.800     albertel 9189:                      foreach my $id (@possibilities) {
                   9190: 			 my $file=$bighash{'src_'.$id};
1.39      www      9191:                          if (&allowed('bre',$file)) {
1.800     albertel 9192:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9193:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9194: 				$realpossible++;
1.626     albertel 9195:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9196: 						    $resid,$thisfn);
1.39      www      9197:                             }
                   9198: 			 }
1.191     harris41 9199:                      }
1.39      www      9200: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9201:                  } else {
                   9202:                      $syval='';
1.37      www      9203:                  }
                   9204: 	      }
                   9205:               untie(%bighash)
1.481     raeburn  9206:            }
1.31      www      9207:         }
1.62      www      9208:         if ($syval) {
1.620     albertel 9209: 	    return $env{$cache_str}=$syval;
1.62      www      9210:         }
1.31      www      9211:     }
1.949     raeburn  9212:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9213:     return $env{$cache_str}='';
1.31      www      9214: }
                   9215: 
                   9216: # ---------------------------------------------------------- Return random seed
                   9217: 
1.32      www      9218: sub numval {
                   9219:     my $txt=shift;
                   9220:     $txt=~tr/A-J/0-9/;
                   9221:     $txt=~tr/a-j/0-9/;
                   9222:     $txt=~tr/K-T/0-9/;
                   9223:     $txt=~tr/k-t/0-9/;
                   9224:     $txt=~tr/U-Z/0-5/;
                   9225:     $txt=~tr/u-z/0-5/;
                   9226:     $txt=~s/\D//g;
1.564     albertel 9227:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9228:     return int($txt);
1.368     albertel 9229: }
                   9230: 
1.484     albertel 9231: sub numval2 {
                   9232:     my $txt=shift;
                   9233:     $txt=~tr/A-J/0-9/;
                   9234:     $txt=~tr/a-j/0-9/;
                   9235:     $txt=~tr/K-T/0-9/;
                   9236:     $txt=~tr/k-t/0-9/;
                   9237:     $txt=~tr/U-Z/0-5/;
                   9238:     $txt=~tr/u-z/0-5/;
                   9239:     $txt=~s/\D//g;
                   9240:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9241:     my $total;
                   9242:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9243:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9244:     return int($total);
                   9245: }
                   9246: 
1.575     albertel 9247: sub numval3 {
                   9248:     use integer;
                   9249:     my $txt=shift;
                   9250:     $txt=~tr/A-J/0-9/;
                   9251:     $txt=~tr/a-j/0-9/;
                   9252:     $txt=~tr/K-T/0-9/;
                   9253:     $txt=~tr/k-t/0-9/;
                   9254:     $txt=~tr/U-Z/0-5/;
                   9255:     $txt=~tr/u-z/0-5/;
                   9256:     $txt=~s/\D//g;
                   9257:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9258:     my $total;
                   9259:     foreach my $val (@txts) { $total+=$val; }
                   9260:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9261:     return $total;
                   9262: }
                   9263: 
1.675     albertel 9264: sub digest {
                   9265:     my ($data)=@_;
                   9266:     my $digest=&Digest::MD5::md5($data);
                   9267:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9268:     my ($e,$f);
                   9269:     {
                   9270:         use integer;
                   9271:         $e=($a+$b);
                   9272:         $f=($c+$d);
                   9273:         if ($_64bit) {
                   9274:             $e=(($e<<32)>>32);
                   9275:             $f=(($f<<32)>>32);
                   9276:         }
                   9277:     }
                   9278:     if (wantarray) {
                   9279: 	return ($e,$f);
                   9280:     } else {
                   9281: 	my $g;
                   9282: 	{
                   9283: 	    use integer;
                   9284: 	    $g=($e+$f);
                   9285: 	    if ($_64bit) {
                   9286: 		$g=(($g<<32)>>32);
                   9287: 	    }
                   9288: 	}
                   9289: 	return $g;
                   9290:     }
                   9291: }
                   9292: 
1.368     albertel 9293: sub latest_rnd_algorithm_id {
1.675     albertel 9294:     return '64bit5';
1.366     albertel 9295: }
1.32      www      9296: 
1.503     albertel 9297: sub get_rand_alg {
                   9298:     my ($courseid)=@_;
1.790     albertel 9299:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9300:     if ($courseid) {
1.620     albertel 9301: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9302:     }
                   9303:     return &latest_rnd_algorithm_id();
                   9304: }
                   9305: 
1.562     albertel 9306: sub validCODE {
                   9307:     my ($CODE)=@_;
                   9308:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9309:     return 0;
                   9310: }
                   9311: 
1.491     albertel 9312: sub getCODE {
1.620     albertel 9313:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9314:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9315: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9316: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9317: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9318:     }
                   9319:     return undef;
                   9320: }
                   9321: 
1.31      www      9322: sub rndseed {
1.155     albertel 9323:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9324:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9325:     if (!defined($symb)) {
1.366     albertel 9326: 	unless ($symb=$wsymb) { return time; }
                   9327:     }
                   9328:     if (!$courseid) { $courseid=$wcourseid; }
                   9329:     if (!$domain) { $domain=$wdomain; }
                   9330:     if (!$username) { $username=$wusername }
1.503     albertel 9331:     my $which=&get_rand_alg();
1.1110    www      9332: 
1.491     albertel 9333:     if (defined(&getCODE())) {
1.675     albertel 9334: 	if ($which eq '64bit5') {
                   9335: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9336: 	} elsif ($which eq '64bit4') {
1.575     albertel 9337: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9338: 	} else {
                   9339: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9340: 	}
1.675     albertel 9341:     } elsif ($which eq '64bit5') {
                   9342: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9343:     } elsif ($which eq '64bit4') {
                   9344: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9345:     } elsif ($which eq '64bit3') {
                   9346: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9347:     } elsif ($which eq '64bit2') {
                   9348: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9349:     } elsif ($which eq '64bit') {
                   9350: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9351:     }
                   9352:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9353: }
                   9354: 
                   9355: sub rndseed_32bit {
                   9356:     my ($symb,$courseid,$domain,$username)=@_;
                   9357:     {
                   9358: 	use integer;
                   9359: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9360: 	my $symbseed=numval($symb) << 22;
                   9361: 	my $namechck=unpack("%32C*",$username) << 17;
                   9362: 	my $nameseed=numval($username) << 12;
                   9363: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9364: 	my $courseseed=unpack("%32C*",$courseid);
                   9365: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9366: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9367: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9368: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9369: 	return $num;
                   9370:     }
                   9371: }
                   9372: 
                   9373: sub rndseed_64bit {
                   9374:     my ($symb,$courseid,$domain,$username)=@_;
                   9375:     {
                   9376: 	use integer;
                   9377: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9378: 	my $symbseed=numval($symb) << 10;
                   9379: 	my $namechck=unpack("%32S*",$username);
                   9380: 	
                   9381: 	my $nameseed=numval($username) << 21;
                   9382: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9383: 	my $courseseed=unpack("%32S*",$courseid);
                   9384: 	
                   9385: 	my $num1=$symbchck+$symbseed+$namechck;
                   9386: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9387: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9388: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9389: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9390: 	return "$num1,$num2";
1.155     albertel 9391:     }
1.366     albertel 9392: }
                   9393: 
1.443     albertel 9394: sub rndseed_64bit2 {
                   9395:     my ($symb,$courseid,$domain,$username)=@_;
                   9396:     {
                   9397: 	use integer;
                   9398: 	# strings need to be an even # of cahracters long, it it is odd the
                   9399:         # last characters gets thrown away
                   9400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9401: 	my $symbseed=numval($symb) << 10;
                   9402: 	my $namechck=unpack("%32S*",$username.' ');
                   9403: 	
                   9404: 	my $nameseed=numval($username) << 21;
1.501     albertel 9405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9406: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9407: 	
                   9408: 	my $num1=$symbchck+$symbseed+$namechck;
                   9409: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9410: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9411: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9412: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9413: 	return "$num1,$num2";
                   9414:     }
                   9415: }
                   9416: 
                   9417: sub rndseed_64bit3 {
                   9418:     my ($symb,$courseid,$domain,$username)=@_;
                   9419:     {
                   9420: 	use integer;
                   9421: 	# strings need to be an even # of cahracters long, it it is odd the
                   9422:         # last characters gets thrown away
                   9423: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9424: 	my $symbseed=numval2($symb) << 10;
                   9425: 	my $namechck=unpack("%32S*",$username.' ');
                   9426: 	
                   9427: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9428: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9429: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9430: 	
                   9431: 	my $num1=$symbchck+$symbseed+$namechck;
                   9432: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9433: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9434: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9435: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9436: 	
1.503     albertel 9437: 	return "$num1:$num2";
1.443     albertel 9438:     }
                   9439: }
                   9440: 
1.575     albertel 9441: sub rndseed_64bit4 {
                   9442:     my ($symb,$courseid,$domain,$username)=@_;
                   9443:     {
                   9444: 	use integer;
                   9445: 	# strings need to be an even # of cahracters long, it it is odd the
                   9446:         # last characters gets thrown away
                   9447: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9448: 	my $symbseed=numval3($symb) << 10;
                   9449: 	my $namechck=unpack("%32S*",$username.' ');
                   9450: 	
                   9451: 	my $nameseed=numval3($username) << 21;
                   9452: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9453: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9454: 	
                   9455: 	my $num1=$symbchck+$symbseed+$namechck;
                   9456: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9457: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9458: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9459: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9460: 	
1.575     albertel 9461: 	return "$num1:$num2";
                   9462:     }
                   9463: }
                   9464: 
1.675     albertel 9465: sub rndseed_64bit5 {
                   9466:     my ($symb,$courseid,$domain,$username)=@_;
                   9467:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9468:     return "$num1:$num2";
                   9469: }
                   9470: 
1.366     albertel 9471: sub rndseed_CODE_64bit {
                   9472:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9473:     {
1.366     albertel 9474: 	use integer;
1.443     albertel 9475: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9476: 	my $symbseed=numval2($symb);
1.491     albertel 9477: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9478: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9479: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9480: 	my $num1=$symbseed+$CODEchck;
                   9481: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9482: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9483: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9484: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9485: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9486: 	return "$num1:$num2";
1.366     albertel 9487:     }
                   9488: }
                   9489: 
1.575     albertel 9490: sub rndseed_CODE_64bit4 {
                   9491:     my ($symb,$courseid,$domain,$username)=@_;
                   9492:     {
                   9493: 	use integer;
                   9494: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9495: 	my $symbseed=numval3($symb);
                   9496: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9497: 	my $CODEseed=numval3(&getCODE());
                   9498: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9499: 	my $num1=$symbseed+$CODEchck;
                   9500: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9501: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9502: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9503: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9504: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9505: 	return "$num1:$num2";
                   9506:     }
                   9507: }
                   9508: 
1.675     albertel 9509: sub rndseed_CODE_64bit5 {
                   9510:     my ($symb,$courseid,$domain,$username)=@_;
                   9511:     my $code = &getCODE();
                   9512:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9513:     return "$num1:$num2";
                   9514: }
                   9515: 
1.366     albertel 9516: sub setup_random_from_rndseed {
                   9517:     my ($rndseed)=@_;
1.503     albertel 9518:     if ($rndseed =~/([,:])/) {
                   9519: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9520: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9521:     } else {
                   9522: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9523:     }
1.36      albertel 9524: }
                   9525: 
1.474     albertel 9526: sub latest_receipt_algorithm_id {
1.835     albertel 9527:     return 'receipt3';
1.474     albertel 9528: }
                   9529: 
1.480     www      9530: sub recunique {
                   9531:     my $fucourseid=shift;
                   9532:     my $unique;
1.835     albertel 9533:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9534: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9535: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9536:     } else {
                   9537: 	$unique=$perlvar{'lonReceipt'};
                   9538:     }
                   9539:     return unpack("%32C*",$unique);
                   9540: }
                   9541: 
                   9542: sub recprefix {
                   9543:     my $fucourseid=shift;
                   9544:     my $prefix;
1.835     albertel 9545:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9546: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9547: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9548:     } else {
                   9549: 	$prefix=$perlvar{'lonHostID'};
                   9550:     }
                   9551:     return unpack("%32C*",$prefix);
                   9552: }
                   9553: 
1.76      www      9554: sub ireceipt {
1.474     albertel 9555:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9556: 
                   9557:     my $return =&recprefix($fucourseid).'-';
                   9558: 
                   9559:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9560: 	$env{'request.state'} eq 'construct') {
                   9561: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9562: 	return $return;
                   9563:     }
                   9564: 
1.76      www      9565:     my $cuname=unpack("%32C*",$funame);
                   9566:     my $cudom=unpack("%32C*",$fudom);
                   9567:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9568:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9569:     my $cunique=&recunique($fucourseid);
1.474     albertel 9570:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9571:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9572: 
1.790     albertel 9573: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9574: 			       
                   9575: 	$return.= ($cunique%$cuname+
                   9576: 		   $cunique%$cudom+
                   9577: 		   $cusymb%$cuname+
                   9578: 		   $cusymb%$cudom+
                   9579: 		   $cucourseid%$cuname+
                   9580: 		   $cucourseid%$cudom+
                   9581: 		   $cpart%$cuname+
                   9582: 		   $cpart%$cudom);
                   9583:     } else {
                   9584: 	$return.= ($cunique%$cuname+
                   9585: 		   $cunique%$cudom+
                   9586: 		   $cusymb%$cuname+
                   9587: 		   $cusymb%$cudom+
                   9588: 		   $cucourseid%$cuname+
                   9589: 		   $cucourseid%$cudom);
                   9590:     }
                   9591:     return $return;
1.76      www      9592: }
                   9593: 
                   9594: sub receipt {
1.474     albertel 9595:     my ($part)=@_;
1.790     albertel 9596:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9597:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9598: }
1.260     ng       9599: 
1.790     albertel 9600: sub whichuser {
                   9601:     my ($passedsymb)=@_;
                   9602:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9603:     if (defined($env{'form.grade_symb'})) {
                   9604: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9605: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9606: 	if (!$allowed &&
                   9607: 	    exists($env{'request.course.sec'}) &&
                   9608: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9609: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9610: 			      '/'.$env{'request.course.sec'});
                   9611: 	}
                   9612: 	if ($allowed) {
                   9613: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9614: 	    $courseid=$tmp_courseid;
                   9615: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9616: 	    ($name)=&get_env_multiple('form.grade_username');
                   9617: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9618: 	}
                   9619:     }
                   9620:     if (!$passedsymb) {
                   9621: 	$symb=&symbread();
                   9622:     } else {
                   9623: 	$symb=$passedsymb;
                   9624:     }
                   9625:     $courseid=$env{'request.course.id'};
                   9626:     $domain=$env{'user.domain'};
                   9627:     $name=$env{'user.name'};
                   9628:     if ($name eq 'public' && $domain eq 'public') {
                   9629: 	if (!defined($env{'form.username'})) {
                   9630: 	    $env{'form.username'}.=time.rand(10000000);
                   9631: 	}
                   9632: 	$name.=$env{'form.username'};
                   9633:     }
                   9634:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9635: 
                   9636: }
                   9637: 
1.36      albertel 9638: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9639: # returns either the contents of the file or 
                   9640: # -1 if the file doesn't exist
1.481     raeburn  9641: #
                   9642: # if the target is a file that was uploaded via DOCS, 
                   9643: # a check will be made to see if a current copy exists on the local server,
                   9644: # if it does this will be served, otherwise a copy will be retrieved from
                   9645: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9646: # the local server.   
1.472     albertel 9647: 
1.36      albertel 9648: sub getfile {
1.538     albertel 9649:     my ($file) = @_;
1.609     banghart 9650:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9651:     &repcopy($file);
                   9652:     return &readfile($file);
                   9653: }
                   9654: 
                   9655: sub repcopy_userfile {
                   9656:     my ($file)=@_;
1.609     banghart 9657:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9658:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9659:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9660: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9661:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9662:     if (-e "$file") {
1.828     www      9663: # we already have a local copy, check it out
1.538     albertel 9664: 	my @fileinfo = stat($file);
1.828     www      9665: 	my $rtncode;
                   9666: 	my $info;
1.538     albertel 9667: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9668: 	if ($lwpresp ne 'ok') {
1.828     www      9669: # there is no such file anymore, even though we had a local copy
1.482     albertel 9670: 	    if ($rtncode eq '404') {
1.538     albertel 9671: 		unlink($file);
1.482     albertel 9672: 	    }
                   9673: 	    return -1;
                   9674: 	}
                   9675: 	if ($info < $fileinfo[9]) {
1.828     www      9676: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9677: 	    return 'ok';
1.828     www      9678: 	} else {
                   9679: # the file is outdated, get rid of it
                   9680: 	    unlink($file);
1.482     albertel 9681: 	}
1.828     www      9682:     }
                   9683: # one way or the other, at this point, we don't have the file
                   9684: # construct the correct path for the file
                   9685:     my @parts = ($cdom,$cnum); 
                   9686:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9687: 	push @parts, split(/\//,$1);
                   9688:     }
                   9689:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9690:     foreach my $part (@parts) {
                   9691: 	$path .= '/'.$part;
                   9692: 	if (!-e $path) {
                   9693: 	    mkdir($path,0770);
1.482     albertel 9694: 	}
                   9695:     }
1.828     www      9696: # now the path exists for sure
                   9697: # get a user agent
                   9698:     my $ua=new LWP::UserAgent;
                   9699:     my $transferfile=$file.'.in.transfer';
                   9700: # FIXME: this should flock
                   9701:     if (-e $transferfile) { return 'ok'; }
                   9702:     my $request;
                   9703:     $uri=~s/^\///;
1.980     raeburn  9704:     my $homeserver = &homeserver($cnum,$cdom);
                   9705:     my $protocol = $protocol{$homeserver};
                   9706:     $protocol = 'http' if ($protocol ne 'https');
                   9707:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9708:     my $response=$ua->request($request,$transferfile);
                   9709: # did it work?
                   9710:     if ($response->is_error()) {
                   9711: 	unlink($transferfile);
                   9712: 	&logthis("Userfile repcopy failed for $uri");
                   9713: 	return -1;
                   9714:     }
                   9715: # worked, rename the transfer file
                   9716:     rename($transferfile,$file);
1.607     raeburn  9717:     return 'ok';
1.481     raeburn  9718: }
                   9719: 
1.517     albertel 9720: sub tokenwrapper {
                   9721:     my $uri=shift;
1.980     raeburn  9722:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9723:     $uri=~s|^/||;
1.620     albertel 9724:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9725:     my $token=$1;
1.552     albertel 9726:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9727:     if ($udom && $uname && $file) {
                   9728: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9729:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9730:         my $homeserver = &homeserver($uname,$udom);
                   9731:         my $protocol = $protocol{$homeserver};
                   9732:         $protocol = 'http' if ($protocol ne 'https');
                   9733:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9734:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9735:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9736:     } else {
                   9737:         return '/adm/notfound.html';
                   9738:     }
                   9739: }
                   9740: 
1.828     www      9741: # call with reqtype HEAD: get last modification time
                   9742: # call with reqtype GET: get the file contents
                   9743: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9744: #
1.481     raeburn  9745: sub getuploaded {
                   9746:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9747:     $uri=~s/^\///;
1.980     raeburn  9748:     my $homeserver = &homeserver($cnum,$cdom);
                   9749:     my $protocol = $protocol{$homeserver};
                   9750:     $protocol = 'http' if ($protocol ne 'https');
                   9751:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9752:     my $ua=new LWP::UserAgent;
                   9753:     my $request=new HTTP::Request($reqtype,$uri);
                   9754:     my $response=$ua->request($request);
                   9755:     $$rtncode = $response->code;
1.482     albertel 9756:     if (! $response->is_success()) {
                   9757: 	return 'failed';
                   9758:     }      
                   9759:     if ($reqtype eq 'HEAD') {
1.486     www      9760: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9761:     } elsif ($reqtype eq 'GET') {
                   9762: 	$$info = $response->content;
1.472     albertel 9763:     }
1.482     albertel 9764:     return 'ok';
1.36      albertel 9765: }
                   9766: 
1.481     raeburn  9767: sub readfile {
                   9768:     my $file = shift;
                   9769:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9770:     my $fh;
                   9771:     open($fh,"<$file");
                   9772:     my $a='';
1.800     albertel 9773:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9774:     return $a;
                   9775: }
                   9776: 
1.36      albertel 9777: sub filelocation {
1.590     banghart 9778:     my ($dir,$file) = @_;
                   9779:     my $location;
                   9780:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9781: 
                   9782:     if ($file =~ m-^/adm/-) {
                   9783: 	$file=~s-^/adm/wrapper/-/-;
                   9784: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9785:     }
1.882     albertel 9786: 
1.590     banghart 9787:     if ($file=~m:^/~:) { # is a contruction space reference
                   9788:         $location = $file;
                   9789:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9790:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9791: 	# is a correct contruction space reference
                   9792:         $location = $file;
1.956     raeburn  9793:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9794:         $location = $file;
1.609     banghart 9795:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9796:         my ($udom,$uname,$filename)=
1.811     albertel 9797:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9798:         my $home=&homeserver($uname,$udom);
                   9799:         my $is_me=0;
                   9800:         my @ids=&current_machine_ids();
                   9801:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9802:         if ($is_me) {
1.1117    foxr     9803:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9804:         } else {
                   9805:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9806:   	      $udom.'/'.$uname.'/'.$filename;
                   9807:         }
1.882     albertel 9808:     } elsif ($file =~ m-^/adm/-) {
                   9809: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9810:     } else {
                   9811:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9812:         $file=~s:^/res/:/:;
                   9813:         if ( !( $file =~ m:^/:) ) {
                   9814:             $location = $dir. '/'.$file;
                   9815:         } else {
                   9816:             $location = '/home/httpd/html/res'.$file;
                   9817:         }
1.59      albertel 9818:     }
1.590     banghart 9819:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9820:     while ($location=~m{/\.\./}) {
                   9821: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9822: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9823: 	} else {
                   9824: 	    $location=~ s{/\.\./}{/}g;
                   9825: 	}
                   9826:     } #remove dir/..
1.590     banghart 9827:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9828:     return $location;
1.46      www      9829: }
1.36      albertel 9830: 
1.46      www      9831: sub hreflocation {
                   9832:     my ($dir,$file)=@_;
1.980     raeburn  9833:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9834: 	$file=filelocation($dir,$file);
1.700     albertel 9835:     } elsif ($file=~m-^/adm/-) {
                   9836: 	$file=~s-^/adm/wrapper/-/-;
                   9837: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9838:     }
                   9839:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9840: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9841:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9842: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9843:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9844: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9845: 	    -/uploaded/$1/$2/-x;
1.46      www      9846:     }
1.913     albertel 9847:     if ($file=~ m{^/userfiles/}) {
                   9848: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9849:     }
1.462     albertel 9850:     return $file;
1.465     albertel 9851: }
                   9852: 
                   9853: sub current_machine_domains {
1.853     albertel 9854:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9855: }
                   9856: 
                   9857: sub machine_domains {
                   9858:     my ($hostname) = @_;
1.465     albertel 9859:     my @domains;
1.838     albertel 9860:     my %hostname = &all_hostnames();
1.465     albertel 9861:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9862: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9863: 	if ($hostname eq $name) {
1.844     albertel 9864: 	    push(@domains,&host_domain($id));
1.465     albertel 9865: 	}
                   9866:     }
                   9867:     return @domains;
                   9868: }
                   9869: 
                   9870: sub current_machine_ids {
1.853     albertel 9871:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9872: }
                   9873: 
                   9874: sub machine_ids {
                   9875:     my ($hostname) = @_;
                   9876:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9877:     my @ids;
1.888     albertel 9878:     my %name_to_host = &all_names();
1.889     albertel 9879:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9880: 	return @{ $name_to_host{$hostname} };
                   9881:     }
                   9882:     return;
1.31      www      9883: }
                   9884: 
1.824     raeburn  9885: sub additional_machine_domains {
                   9886:     my @domains;
                   9887:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9888:     while( my $line = <$fh>) {
                   9889:         $line =~ s/\s//g;
                   9890:         push(@domains,$line);
                   9891:     }
                   9892:     return @domains;
                   9893: }
                   9894: 
                   9895: sub default_login_domain {
                   9896:     my $domain = $perlvar{'lonDefDomain'};
                   9897:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9898:     foreach my $posdom (&current_machine_domains(),
                   9899:                         &additional_machine_domains()) {
                   9900:         if (lc($posdom) eq lc($testdomain)) {
                   9901:             $domain=$posdom;
                   9902:             last;
                   9903:         }
                   9904:     }
                   9905:     return $domain;
                   9906: }
                   9907: 
1.31      www      9908: # ------------------------------------------------------------- Declutters URLs
                   9909: 
                   9910: sub declutter {
                   9911:     my $thisfn=shift;
1.569     albertel 9912:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9913:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9914:     $thisfn=~s/^\///;
1.697     albertel 9915:     $thisfn=~s|^adm/wrapper/||;
                   9916:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9917:     $thisfn=~s/^res\///;
1.1032    raeburn  9918:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9919:         $thisfn=~s/\?.+$//;
                   9920:     }
1.268     www      9921:     return $thisfn;
                   9922: }
                   9923: 
                   9924: # ------------------------------------------------------------- Clutter up URLs
                   9925: 
                   9926: sub clutter {
                   9927:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9928:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9929: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9930:        $thisfn='/res'.$thisfn; 
                   9931:     }
1.1031    raeburn  9932:     if ($thisfn !~m|^/adm|) {
                   9933: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9934: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9935: 	} else {
                   9936: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9937: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9938: 	    if ($embstyle eq 'ssi'
                   9939: 		|| ($embstyle eq 'hdn')
                   9940: 		|| ($embstyle eq 'rat')
                   9941: 		|| ($embstyle eq 'prv')
                   9942: 		|| ($embstyle eq 'ign')) {
                   9943: 		#do nothing with these
                   9944: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9945: 		|| ($embstyle eq 'emb')
                   9946: 		|| ($embstyle eq 'wrp')) {
                   9947: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9948: 	    } elsif ($embstyle eq 'unk'
                   9949: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9950: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9951: 	    } else {
1.718     www      9952: #		&logthis("Got a blank emb style");
1.695     albertel 9953: 	    }
1.694     albertel 9954: 	}
                   9955:     }
1.31      www      9956:     return $thisfn;
1.12      www      9957: }
                   9958: 
1.787     albertel 9959: sub clutter_with_no_wrapper {
                   9960:     my $uri = &clutter(shift);
                   9961:     if ($uri =~ m-^/adm/-) {
                   9962: 	$uri =~ s-^/adm/wrapper/-/-;
                   9963: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9964:     }
                   9965:     return $uri;
                   9966: }
                   9967: 
1.557     albertel 9968: sub freeze_escape {
                   9969:     my ($value)=@_;
                   9970:     if (ref($value)) {
                   9971: 	$value=&nfreeze($value);
                   9972: 	return '__FROZEN__'.&escape($value);
                   9973:     }
                   9974:     return &escape($value);
                   9975: }
                   9976: 
1.11      www      9977: 
1.557     albertel 9978: sub thaw_unescape {
                   9979:     my ($value)=@_;
                   9980:     if ($value =~ /^__FROZEN__/) {
                   9981: 	substr($value,0,10,undef);
                   9982: 	$value=&unescape($value);
                   9983: 	return &thaw($value);
                   9984:     }
                   9985:     return &unescape($value);
                   9986: }
                   9987: 
1.436     albertel 9988: sub correct_line_ends {
                   9989:     my ($result)=@_;
                   9990:     $$result =~s/\r\n/\n/mg;
                   9991:     $$result =~s/\r/\n/mg;
1.415     albertel 9992: }
1.1       albertel 9993: # ================================================================ Main Program
                   9994: 
1.184     www      9995: sub goodbye {
1.204     albertel 9996:    &logthis("Starting Shut down");
1.443     albertel 9997: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9998:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9999: #converted
1.599     albertel 10000: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10001:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10002: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10003: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10004: #1.1 only
1.870     albertel 10005: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10006: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10007: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10008: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10009:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10010:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10011:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10012:    &flushcourselogs();
                   10013:    &logthis("Shutting down");
                   10014: }
                   10015: 
1.852     albertel 10016: sub get_dns {
1.869     albertel 10017:     my ($url,$func,$ignore_cache) = @_;
                   10018:     if (!$ignore_cache) {
                   10019: 	my ($content,$cached)=
                   10020: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10021: 	if ($cached) {
                   10022: 	    &$func($content);
                   10023: 	    return;
                   10024: 	}
                   10025:     }
                   10026: 
                   10027:     my %alldns;
1.852     albertel 10028:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10029:     foreach my $dns (<$config>) {
                   10030: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10031:         my $line = $1;
                   10032:         my ($host,$protocol) = split(/:/,$line);
                   10033:         if ($protocol ne 'https') {
                   10034:             $protocol = 'http';
                   10035:         }
                   10036: 	$alldns{$host} = $protocol;
1.869     albertel 10037:     }
                   10038:     while (%alldns) {
                   10039: 	my ($dns) = keys(%alldns);
1.852     albertel 10040: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10041: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10042: 	my $response=$ua->request($request);
1.979     raeburn  10043:         delete($alldns{$dns});
1.852     albertel 10044: 	next if ($response->is_error());
                   10045: 	my @content = split("\n",$response->content);
1.869     albertel 10046: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10047: 	&$func(\@content);
1.869     albertel 10048: 	return;
1.852     albertel 10049:     }
                   10050:     close($config);
1.871     albertel 10051:     my $which = (split('/',$url))[3];
                   10052:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10053:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10054:     my @content = <$config>;
                   10055:     &$func(\@content);
                   10056:     return;
1.852     albertel 10057: }
1.327     albertel 10058: # ------------------------------------------------------------ Read domain file
                   10059: {
1.852     albertel 10060:     my $loaded;
1.846     albertel 10061:     my %domain;
                   10062: 
1.852     albertel 10063:     sub parse_domain_tab {
                   10064: 	my ($lines) = @_;
                   10065: 	foreach my $line (@$lines) {
                   10066: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10067: 
1.846     albertel 10068: 	    chomp($line);
1.852     albertel 10069: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10070: 	    my %this_domain;
                   10071: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10072: 			       'lang_def', 'city', 'longi', 'lati',
                   10073: 			       'primary') {
                   10074: 		$this_domain{$field} = shift(@elements);
                   10075: 	    }
                   10076: 	    $domain{$name} = \%this_domain;
1.852     albertel 10077: 	}
                   10078:     }
1.864     albertel 10079: 
                   10080:     sub reset_domain_info {
                   10081: 	undef($loaded);
                   10082: 	undef(%domain);
                   10083:     }
                   10084: 
1.852     albertel 10085:     sub load_domain_tab {
1.869     albertel 10086: 	my ($ignore_cache) = @_;
                   10087: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10088: 	my $fh;
                   10089: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10090: 	    my @lines = <$fh>;
                   10091: 	    &parse_domain_tab(\@lines);
1.448     albertel 10092: 	}
1.852     albertel 10093: 	close($fh);
                   10094: 	$loaded = 1;
1.327     albertel 10095:     }
1.846     albertel 10096: 
                   10097:     sub domain {
1.852     albertel 10098: 	&load_domain_tab() if (!$loaded);
                   10099: 
1.846     albertel 10100: 	my ($name,$what) = @_;
                   10101: 	return if ( !exists($domain{$name}) );
                   10102: 
                   10103: 	if (!$what) {
                   10104: 	    return $domain{$name}{'description'};
                   10105: 	}
                   10106: 	return $domain{$name}{$what};
                   10107:     }
1.974     raeburn  10108: 
                   10109:     sub domain_info {
                   10110:         &load_domain_tab() if (!$loaded);
                   10111:         return %domain;
                   10112:     }
                   10113: 
1.327     albertel 10114: }
                   10115: 
                   10116: 
1.1       albertel 10117: # ------------------------------------------------------------- Read hosts file
                   10118: {
1.838     albertel 10119:     my %hostname;
1.844     albertel 10120:     my %hostdom;
1.845     albertel 10121:     my %libserv;
1.852     albertel 10122:     my $loaded;
1.888     albertel 10123:     my %name_to_host;
1.1074    raeburn  10124:     my %internetdom;
1.1107    raeburn  10125:     my %LC_dns_serv;
1.852     albertel 10126: 
                   10127:     sub parse_hosts_tab {
                   10128: 	my ($file) = @_;
                   10129: 	foreach my $configline (@$file) {
                   10130: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10131:             chomp($configline);
                   10132: 	    if ($configline =~ /^\^/) {
                   10133:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10134:                     $LC_dns_serv{$1} = 1;
                   10135:                 }
                   10136:                 next;
                   10137:             }
1.1074    raeburn  10138: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10139: 	    $name=~s/\s//g;
                   10140: 	    if ($id && $domain && $role && $name) {
                   10141: 		$hostname{$id}=$name;
1.888     albertel 10142: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10143: 		$hostdom{$id}=$domain;
                   10144: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10145:                 if (defined($protocol)) {
                   10146:                     if ($protocol eq 'https') {
                   10147:                         $protocol{$id} = $protocol;
                   10148:                     } else {
                   10149:                         $protocol{$id} = 'http'; 
                   10150:                     }
1.968     raeburn  10151:                 } else {
1.969     raeburn  10152:                     $protocol{$id} = 'http';
1.968     raeburn  10153:                 }
1.1074    raeburn  10154:                 if (defined($intdom)) {
                   10155:                     $internetdom{$id} = $intdom;
                   10156:                 }
1.852     albertel 10157: 	    }
                   10158: 	}
                   10159:     }
1.864     albertel 10160:     
                   10161:     sub reset_hosts_info {
1.897     albertel 10162: 	&purge_remembered();
1.864     albertel 10163: 	&reset_domain_info();
                   10164: 	&reset_hosts_ip_info();
1.892     albertel 10165: 	undef(%name_to_host);
1.864     albertel 10166: 	undef(%hostname);
                   10167: 	undef(%hostdom);
                   10168: 	undef(%libserv);
                   10169: 	undef($loaded);
                   10170:     }
1.1       albertel 10171: 
1.852     albertel 10172:     sub load_hosts_tab {
1.869     albertel 10173: 	my ($ignore_cache) = @_;
                   10174: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10175: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10176: 	my @config = <$config>;
                   10177: 	&parse_hosts_tab(\@config);
                   10178: 	close($config);
                   10179: 	$loaded=1;
1.1       albertel 10180:     }
1.852     albertel 10181: 
1.838     albertel 10182:     sub hostname {
1.852     albertel 10183: 	&load_hosts_tab() if (!$loaded);
                   10184: 
1.838     albertel 10185: 	my ($lonid) = @_;
                   10186: 	return $hostname{$lonid};
                   10187:     }
1.845     albertel 10188: 
1.838     albertel 10189:     sub all_hostnames {
1.852     albertel 10190: 	&load_hosts_tab() if (!$loaded);
                   10191: 
1.838     albertel 10192: 	return %hostname;
                   10193:     }
1.845     albertel 10194: 
1.888     albertel 10195:     sub all_names {
                   10196: 	&load_hosts_tab() if (!$loaded);
                   10197: 
                   10198: 	return %name_to_host;
                   10199:     }
                   10200: 
1.974     raeburn  10201:     sub all_host_domain {
                   10202:         &load_hosts_tab() if (!$loaded);
                   10203:         return %hostdom;
                   10204:     }
                   10205: 
1.845     albertel 10206:     sub is_library {
1.852     albertel 10207: 	&load_hosts_tab() if (!$loaded);
                   10208: 
1.845     albertel 10209: 	return exists($libserv{$_[0]});
                   10210:     }
                   10211: 
                   10212:     sub all_library {
1.852     albertel 10213: 	&load_hosts_tab() if (!$loaded);
                   10214: 
1.845     albertel 10215: 	return %libserv;
                   10216:     }
                   10217: 
1.1062    droeschl 10218:     sub unique_library {
                   10219: 	#2x reverse removes all hostnames that appear more than once
                   10220:         my %unique = reverse &all_library();
                   10221:         return reverse %unique;
                   10222:     }
                   10223: 
1.841     albertel 10224:     sub get_servers {
1.852     albertel 10225: 	&load_hosts_tab() if (!$loaded);
                   10226: 
1.841     albertel 10227: 	my ($domain,$type) = @_;
                   10228: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10229: 	                                          : %hostname;
                   10230: 	my %result;
1.842     albertel 10231: 	if (ref($domain) eq 'ARRAY') {
                   10232: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10233: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10234: 		    $result{$host} = $hostname;
                   10235: 		}
                   10236: 	    }
                   10237: 	} else {
                   10238: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10239: 		if ($hostdom{$host} eq $domain) {
                   10240: 		    $result{$host} = $hostname;
                   10241: 		}
1.841     albertel 10242: 	    }
                   10243: 	}
                   10244: 	return %result;
                   10245:     }
1.845     albertel 10246: 
1.1062    droeschl 10247:     sub get_unique_servers {
                   10248:         my %unique = reverse &get_servers(@_);
                   10249: 	return reverse %unique;
                   10250:     }
                   10251: 
1.844     albertel 10252:     sub host_domain {
1.852     albertel 10253: 	&load_hosts_tab() if (!$loaded);
                   10254: 
1.844     albertel 10255: 	my ($lonid) = @_;
                   10256: 	return $hostdom{$lonid};
                   10257:     }
                   10258: 
1.841     albertel 10259:     sub all_domains {
1.852     albertel 10260: 	&load_hosts_tab() if (!$loaded);
                   10261: 
1.841     albertel 10262: 	my %seen;
                   10263: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10264: 	return @uniq;
                   10265:     }
1.1074    raeburn  10266: 
                   10267:     sub internet_dom {
                   10268:         &load_hosts_tab() if (!$loaded);
                   10269: 
                   10270:         my ($lonid) = @_;
                   10271:         return $internetdom{$lonid};
                   10272:     }
1.1107    raeburn  10273: 
                   10274:     sub is_LC_dns {
                   10275:         &load_hosts_tab() if (!$loaded);
                   10276: 
                   10277:         my ($hostname) = @_;
                   10278:         return exists($LC_dns_serv{$hostname});
                   10279:     }
                   10280: 
1.1       albertel 10281: }
                   10282: 
1.847     albertel 10283: { 
                   10284:     my %iphost;
1.856     albertel 10285:     my %name_to_ip;
                   10286:     my %lonid_to_ip;
1.869     albertel 10287: 
1.847     albertel 10288:     sub get_hosts_from_ip {
                   10289: 	my ($ip) = @_;
                   10290: 	my %iphosts = &get_iphost();
                   10291: 	if (ref($iphosts{$ip})) {
                   10292: 	    return @{$iphosts{$ip}};
                   10293: 	}
                   10294: 	return;
1.839     albertel 10295:     }
1.864     albertel 10296:     
                   10297:     sub reset_hosts_ip_info {
                   10298: 	undef(%iphost);
                   10299: 	undef(%name_to_ip);
                   10300: 	undef(%lonid_to_ip);
                   10301:     }
1.856     albertel 10302: 
                   10303:     sub get_host_ip {
                   10304: 	my ($lonid) = @_;
                   10305: 	if (exists($lonid_to_ip{$lonid})) {
                   10306: 	    return $lonid_to_ip{$lonid};
                   10307: 	}
                   10308: 	my $name=&hostname($lonid);
                   10309:    	my $ip = gethostbyname($name);
                   10310: 	return if (!$ip || length($ip) ne 4);
                   10311: 	$ip=inet_ntoa($ip);
                   10312: 	$name_to_ip{$name}   = $ip;
                   10313: 	$lonid_to_ip{$lonid} = $ip;
                   10314: 	return $ip;
                   10315:     }
1.847     albertel 10316:     
                   10317:     sub get_iphost {
1.869     albertel 10318: 	my ($ignore_cache) = @_;
1.894     albertel 10319: 
1.869     albertel 10320: 	if (!$ignore_cache) {
                   10321: 	    if (%iphost) {
                   10322: 		return %iphost;
                   10323: 	    }
                   10324: 	    my ($ip_info,$cached)=
                   10325: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10326: 	    if ($cached) {
                   10327: 		%iphost      = %{$ip_info->[0]};
                   10328: 		%name_to_ip  = %{$ip_info->[1]};
                   10329: 		%lonid_to_ip = %{$ip_info->[2]};
                   10330: 		return %iphost;
                   10331: 	    }
                   10332: 	}
1.894     albertel 10333: 
                   10334: 	# get yesterday's info for fallback
                   10335: 	my %old_name_to_ip;
                   10336: 	my ($ip_info,$cached)=
                   10337: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10338: 	if ($cached) {
                   10339: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10340: 	}
                   10341: 
1.888     albertel 10342: 	my %name_to_host = &all_names();
                   10343: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10344: 	    my $ip;
                   10345: 	    if (!exists($name_to_ip{$name})) {
                   10346: 		$ip = gethostbyname($name);
                   10347: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10348: 		    if (defined($old_name_to_ip{$name})) {
                   10349: 			$ip = $old_name_to_ip{$name};
                   10350: 			&logthis("Can't find $name defaulting to old $ip");
                   10351: 		    } else {
                   10352: 			&logthis("Name $name no IP found");
                   10353: 			next;
                   10354: 		    }
                   10355: 		} else {
                   10356: 		    $ip=inet_ntoa($ip);
1.847     albertel 10357: 		}
                   10358: 		$name_to_ip{$name} = $ip;
                   10359: 	    } else {
                   10360: 		$ip = $name_to_ip{$name};
1.653     albertel 10361: 	    }
1.888     albertel 10362: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10363: 		$lonid_to_ip{$id} = $ip;
                   10364: 	    }
                   10365: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10366: 	}
1.869     albertel 10367: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10368: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10369: 				      48*60*60);
1.869     albertel 10370: 
1.847     albertel 10371: 	return %iphost;
1.598     albertel 10372:     }
                   10373: 
1.992     raeburn  10374:     #
                   10375:     #  Given a DNS returns the loncapa host name for that DNS 
                   10376:     # 
                   10377:     sub host_from_dns {
                   10378:         my ($dns) = @_;
                   10379:         my @hosts;
                   10380:         my $ip;
                   10381: 
1.993     raeburn  10382:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10383:             $ip = $name_to_ip{$dns};
                   10384:         }
                   10385:         if (!$ip) {
                   10386:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10387:             if (length($ip) == 4) { 
                   10388: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10389:             }
                   10390:         }
                   10391:         if ($ip) {
                   10392: 	    @hosts = get_hosts_from_ip($ip);
                   10393: 	    return $hosts[0];
                   10394:         }
                   10395:         return undef;
1.986     foxr     10396:     }
1.992     raeburn  10397: 
1.1074    raeburn  10398:     sub get_internet_names {
                   10399:         my ($lonid) = @_;
                   10400:         return if ($lonid eq '');
                   10401:         my ($idnref,$cached)=
                   10402:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10403:         if ($cached) {
                   10404:             return $idnref;
                   10405:         }
                   10406:         my $ip = &get_host_ip($lonid);
                   10407:         my @hosts = &get_hosts_from_ip($ip);
                   10408:         my %iphost = &get_iphost();
                   10409:         my (@idns,%seen);
                   10410:         foreach my $id (@hosts) {
                   10411:             my $dom = &host_domain($id);
                   10412:             my $prim_id = &domain($dom,'primary');
                   10413:             my $prim_ip = &get_host_ip($prim_id);
                   10414:             next if ($seen{$prim_ip});
                   10415:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10416:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10417:                     my $intdom = &internet_dom($id);
                   10418:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10419:                         push(@idns,$intdom);
                   10420:                     }
                   10421:                 }
                   10422:             }
                   10423:             $seen{$prim_ip} = 1;
                   10424:         }
                   10425:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10426:     }
                   10427: 
1.986     foxr     10428: }
                   10429: 
1.1079    raeburn  10430: sub all_loncaparevs {
                   10431:     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);
                   10432: }
                   10433: 
1.862     albertel 10434: BEGIN {
                   10435: 
                   10436: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10437:     unless ($readit) {
                   10438: {
                   10439:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10440:     %perlvar = (%perlvar,%{$configvars});
                   10441: }
                   10442: 
                   10443: 
1.1       albertel 10444: # ------------------------------------------------------ Read spare server file
                   10445: {
1.448     albertel 10446:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10447: 
                   10448:     while (my $configline=<$config>) {
                   10449:        chomp($configline);
1.284     matthew  10450:        if ($configline) {
1.784     albertel 10451: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10452: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10453: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10454:        }
                   10455:     }
1.448     albertel 10456:     close($config);
1.1       albertel 10457: }
1.11      www      10458: # ------------------------------------------------------------ Read permissions
                   10459: {
1.448     albertel 10460:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10461: 
                   10462:     while (my $configline=<$config>) {
1.448     albertel 10463: 	chomp($configline);
                   10464: 	if ($configline) {
                   10465: 	    my ($role,$perm)=split(/ /,$configline);
                   10466: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10467: 	}
1.11      www      10468:     }
1.448     albertel 10469:     close($config);
1.11      www      10470: }
                   10471: 
                   10472: # -------------------------------------------- Read plain texts for permissions
                   10473: {
1.448     albertel 10474:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10475: 
                   10476:     while (my $configline=<$config>) {
1.448     albertel 10477: 	chomp($configline);
                   10478: 	if ($configline) {
1.742     raeburn  10479: 	    my ($short,@plain)=split(/:/,$configline);
                   10480:             %{$prp{$short}} = ();
                   10481: 	    if (@plain > 0) {
                   10482:                 $prp{$short}{'std'} = $plain[0];
                   10483:                 for (my $i=1; $i<@plain; $i++) {
                   10484:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10485:                 }
                   10486:             }
1.448     albertel 10487: 	}
1.135     www      10488:     }
1.448     albertel 10489:     close($config);
1.135     www      10490: }
                   10491: 
                   10492: # ---------------------------------------------------------- Read package table
                   10493: {
1.448     albertel 10494:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10495: 
                   10496:     while (my $configline=<$config>) {
1.483     albertel 10497: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10498: 	chomp($configline);
                   10499: 	my ($short,$plain)=split(/:/,$configline);
                   10500: 	my ($pack,$name)=split(/\&/,$short);
                   10501: 	if ($plain ne '') {
                   10502: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10503: 	    $packagetab{$short}=$plain; 
                   10504: 	}
1.11      www      10505:     }
1.448     albertel 10506:     close($config);
1.329     matthew  10507: }
                   10508: 
1.1073    raeburn  10509: # ---------------------------------------------------------- Read loncaparev table
                   10510: {
                   10511:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10512:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10513:             while (my $configline=<$config>) {
                   10514:                 chomp($configline);
                   10515:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10516:                 $loncaparevs{$hostid}=$loncaparev;
                   10517:             }
                   10518:             close($config);
                   10519:         }
                   10520:     }
                   10521: }
                   10522: 
1.1074    raeburn  10523: # ---------------------------------------------------------- Read serverhostID table
                   10524: {
                   10525:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10526:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10527:             while (my $configline=<$config>) {
                   10528:                 chomp($configline);
                   10529:                 my ($name,$id)=split(/:/,$configline);
                   10530:                 $serverhomeIDs{$name}=$id;
                   10531:             }
                   10532:             close($config);
                   10533:         }
                   10534:     }
                   10535: }
                   10536: 
1.1079    raeburn  10537: {
                   10538:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10539:     if (-e $file) {
                   10540:         my $parser = HTML::LCParser->new($file);
                   10541:         while (my $token = $parser->get_token()) {
                   10542:             if ($token->[0] eq 'S') {
                   10543:                 my $item = $token->[1];
                   10544:                 my $name = $token->[2]{'name'};
                   10545:                 my $value = $token->[2]{'value'};
                   10546:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10547:                     my $release = $parser->get_text();
                   10548:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10549:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10550:                 }
                   10551:             }
                   10552:         }
                   10553:     }
1.1073    raeburn  10554: }
                   10555: 
1.329     matthew  10556: # ------------- set up temporary directory
                   10557: {
1.1117    foxr     10558:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10559: 
1.11      www      10560: }
                   10561: 
1.794     albertel 10562: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10563: 				'compress_threshold'=> 20_000,
                   10564:  			        });
1.185     www      10565: 
1.281     www      10566: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10567: $dumpcount=0;
1.958     www      10568: $locknum=0;
1.22      www      10569: 
1.163     harris41 10570: &logtouch();
1.672     albertel 10571: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10572: $readit=1;
1.564     albertel 10573:     {
                   10574: 	use integer;
                   10575: 	my $test=(2**32)+1;
1.568     albertel 10576: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10577: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10578:     }
1.195     www      10579: }
1.1       albertel 10580: }
1.179     www      10581: 
1.1       albertel 10582: 1;
1.191     harris41 10583: __END__
                   10584: 
1.243     albertel 10585: =pod
                   10586: 
1.191     harris41 10587: =head1 NAME
                   10588: 
1.243     albertel 10589: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10590: 
                   10591: =head1 SYNOPSIS
                   10592: 
1.243     albertel 10593: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10594: 
                   10595:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10596: 
1.243     albertel 10597: Common parameters:
                   10598: 
                   10599: =over 4
                   10600: 
                   10601: =item *
                   10602: 
                   10603: $uname : an internal username (if $cname expecting a course Id specifically)
                   10604: 
                   10605: =item *
                   10606: 
                   10607: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10608: 
                   10609: =item *
                   10610: 
                   10611: $symb : a resource instance identifier
                   10612: 
                   10613: =item *
                   10614: 
                   10615: $namespace : the name of a .db file that contains the data needed or
                   10616: being set.
                   10617: 
                   10618: =back
                   10619: 
1.394     bowersj2 10620: =head1 OVERVIEW
1.191     harris41 10621: 
1.394     bowersj2 10622: lonnet provides subroutines which interact with the
                   10623: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10624: about classes, users, and resources.
1.243     albertel 10625: 
                   10626: For many of these objects you can also use this to store data about
                   10627: them or modify them in various ways.
1.191     harris41 10628: 
1.394     bowersj2 10629: =head2 Symbs
1.191     harris41 10630: 
1.394     bowersj2 10631: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10632: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10633: map, the resource number of the resource in the map, and the URL of
                   10634: the resource itself. The latter is somewhat redundant, but might help
                   10635: if maps change.
                   10636: 
                   10637: An example is
                   10638: 
                   10639:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10640: 
                   10641: The respective map entry is
                   10642: 
                   10643:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10644:   title="Problem 2">
                   10645:  </resource>
                   10646: 
                   10647: Symbs are used by the random number generator, as well as to store and
                   10648: restore data specific to a certain instance of for example a problem.
                   10649: 
                   10650: =head2 Storing And Retrieving Data
                   10651: 
                   10652: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10653: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10654: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10655: is is the non-critical message twin of cstore. These functions are for
                   10656: handlers to store a perl hash to a user's permanent data space in an
                   10657: easy manner, and to retrieve it again on another call. It is expected
                   10658: that a handler would use this once at the beginning to retrieve data,
                   10659: and then again once at the end to send only the new data back.
                   10660: 
                   10661: The data is stored in the user's data directory on the user's
                   10662: homeserver under the ID of the course.
                   10663: 
                   10664: The hash that is returned by restore will have all of the previous
                   10665: value for all of the elements of the hash.
                   10666: 
                   10667: Example:
                   10668: 
                   10669:  #creating a hash
                   10670:  my %hash;
                   10671:  $hash{'foo'}='bar';
                   10672: 
                   10673:  #storing it
                   10674:  &Apache::lonnet::cstore(\%hash);
                   10675: 
                   10676:  #changing a value
                   10677:  $hash{'foo'}='notbar';
                   10678: 
                   10679:  #adding a new value
                   10680:  $hash{'bar'}='foo';
                   10681:  &Apache::lonnet::cstore(\%hash);
                   10682: 
                   10683:  #retrieving the hash
                   10684:  my %history=&Apache::lonnet::restore();
                   10685: 
                   10686:  #print the hash
                   10687:  foreach my $key (sort(keys(%history))) {
                   10688:    print("\%history{$key} = $history{$key}");
                   10689:  }
                   10690: 
                   10691: Will print out:
1.191     harris41 10692: 
1.394     bowersj2 10693:  %history{1:foo} = bar
                   10694:  %history{1:keys} = foo:timestamp
                   10695:  %history{1:timestamp} = 990455579
                   10696:  %history{2:bar} = foo
                   10697:  %history{2:foo} = notbar
                   10698:  %history{2:keys} = foo:bar:timestamp
                   10699:  %history{2:timestamp} = 990455580
                   10700:  %history{bar} = foo
                   10701:  %history{foo} = notbar
                   10702:  %history{timestamp} = 990455580
                   10703:  %history{version} = 2
                   10704: 
                   10705: Note that the special hash entries C<keys>, C<version> and
                   10706: C<timestamp> were added to the hash. C<version> will be equal to the
                   10707: total number of versions of the data that have been stored. The
                   10708: C<timestamp> attribute will be the UNIX time the hash was
                   10709: stored. C<keys> is available in every historical section to list which
                   10710: keys were added or changed at a specific historical revision of a
                   10711: hash.
                   10712: 
                   10713: B<Warning>: do not store the hash that restore returns directly. This
                   10714: will cause a mess since it will restore the historical keys as if the
                   10715: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10716: 
1.394     bowersj2 10717: Calling convention:
1.191     harris41 10718: 
1.394     bowersj2 10719:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10720:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10721: 
1.394     bowersj2 10722: For more detailed information, see lonnet specific documentation.
1.191     harris41 10723: 
1.394     bowersj2 10724: =head1 RETURN MESSAGES
1.191     harris41 10725: 
1.394     bowersj2 10726: =over 4
1.191     harris41 10727: 
1.394     bowersj2 10728: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10729: 
1.394     bowersj2 10730: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10731: when the connection is brought back up
1.191     harris41 10732: 
1.394     bowersj2 10733: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10734: for later delivery
1.191     harris41 10735: 
1.967     bisitz   10736: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10737: 
1.394     bowersj2 10738: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10739: that was requested
1.191     harris41 10740: 
1.243     albertel 10741: =back
1.191     harris41 10742: 
1.243     albertel 10743: =head1 PUBLIC SUBROUTINES
1.191     harris41 10744: 
1.243     albertel 10745: =head2 Session Environment Functions
1.191     harris41 10746: 
1.243     albertel 10747: =over 4
1.191     harris41 10748: 
1.394     bowersj2 10749: =item * 
                   10750: X<appenv()>
1.949     raeburn  10751: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10752: the user envirnoment file, and will be restored for each access this
1.620     albertel 10753: user makes during this session, also modifies the %env for the current
1.949     raeburn  10754: process. Optional rolesarrayref - if defined contains a reference to an array
                   10755: of roles which are exempt from the restriction on modifying user.role entries 
                   10756: in the user's environment.db and in %env.    
1.191     harris41 10757: 
                   10758: =item *
1.394     bowersj2 10759: X<delenv()>
1.987     raeburn  10760: B<delenv($delthis,$regexp)>: removes all items from the session
                   10761: environment file that begin with $delthis. If the 
                   10762: optional second arg - $regexp - is true, $delthis is treated as a 
                   10763: regular expression, otherwise \Q$delthis\E is used. 
                   10764: The values are also deleted from the current processes %env.
1.191     harris41 10765: 
1.795     albertel 10766: =item * get_env_multiple($name) 
                   10767: 
                   10768: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10769: values may be defined and end up as an array ref.
                   10770: 
                   10771: returns an array of values
                   10772: 
1.243     albertel 10773: =back
                   10774: 
                   10775: =head2 User Information
1.191     harris41 10776: 
1.243     albertel 10777: =over 4
1.191     harris41 10778: 
                   10779: =item *
1.394     bowersj2 10780: X<queryauthenticate()>
                   10781: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10782: authentication scheme
                   10783: 
                   10784: =item *
1.394     bowersj2 10785: X<authenticate()>
1.1073    raeburn  10786: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10787: authenticate user from domain's lib servers (first use the current
                   10788: one). C<$upass> should be the users password.
1.1073    raeburn  10789: $checkdefauth is optional (value is 1 if a check should be made to
                   10790:    authenticate user using default authentication method, and allow
                   10791:    account creation if username does not have account in the domain).
                   10792: $clientcancheckhost is optional (value is 1 if checking whether the
                   10793:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10794: 
                   10795: =item *
1.394     bowersj2 10796: X<homeserver()>
                   10797: B<homeserver($uname,$udom)>: find the server which has
                   10798: the user's directory and files (there must be only one), this caches
                   10799: the answer, and also caches if there is a borken connection.
1.191     harris41 10800: 
                   10801: =item *
1.394     bowersj2 10802: X<idget()>
                   10803: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10804: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10805: username, and only 1 username per ID in a specific domain) (returns
                   10806: hash: id=>name,id=>name)
1.191     harris41 10807: 
                   10808: =item *
1.394     bowersj2 10809: X<idrget()>
                   10810: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10811: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10812: 
                   10813: =item *
1.394     bowersj2 10814: X<idput()>
                   10815: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10816: 
                   10817: =item *
1.394     bowersj2 10818: X<rolesinit()>
                   10819: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10820: 
                   10821: =item *
1.551     albertel 10822: X<getsection()>
                   10823: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10824: course $cname, return section name/number or '' for "not in course"
                   10825: and '-1' for "no section"
                   10826: 
                   10827: =item *
1.394     bowersj2 10828: X<userenvironment()>
                   10829: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10830: passed in @what from the requested user's environment, returns a hash
                   10831: 
1.858     raeburn  10832: =item * 
                   10833: X<userlog_query()>
1.859     albertel 10834: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10835: activity.log file. %filters defines filters applied when parsing the
                   10836: log file. These can be start or end timestamps, or the type of action
                   10837: - log to look for Login or Logout events, check for Checkin or
                   10838: Checkout, role for role selection. The response is in the form
                   10839: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10840: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10841: 
1.243     albertel 10842: =back
                   10843: 
                   10844: =head2 User Roles
                   10845: 
                   10846: =over 4
                   10847: 
                   10848: =item *
                   10849: 
1.810     raeburn  10850: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10851:  F: full access
                   10852:  U,I,K: authentication modes (cxx only)
                   10853:  '': forbidden
                   10854:  1: user needs to choose course
                   10855:  2: browse allowed
1.766     albertel 10856:  A: passphrase authentication needed
1.243     albertel 10857: 
                   10858: =item *
                   10859: 
                   10860: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10861: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10862: and course level
                   10863: 
                   10864: =item *
                   10865: 
1.988     raeburn  10866: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10867: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10868: $type is Course (default) or Community.
1.988     raeburn  10869: If $forcedefault evaluates to true, text returned will be default 
                   10870: text for $type. Otherwise, if this is a course, the text returned 
                   10871: will be a custom name for the role (if defined in the course's 
                   10872: environment).  If no custom name is defined the default is returned.
                   10873:    
1.832     raeburn  10874: =item *
                   10875: 
1.935     raeburn  10876: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10877: All arguments are optional. Returns a hash of a roles, either for
                   10878: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10879: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10880: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10881: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10882: For each key, value is set to colon-separated start and end times for
                   10883: the role.  If no username and domain are specified, will default to
1.934     raeburn  10884: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10885: of role statuses (active, future or previous), roles 
                   10886: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10887: to restrict the list of roles reported. If no array ref is 
                   10888: provided for types, will default to return only active roles.
1.834     albertel 10889: 
1.243     albertel 10890: =back
                   10891: 
                   10892: =head2 User Modification
                   10893: 
                   10894: =over 4
                   10895: 
                   10896: =item *
                   10897: 
1.957     raeburn  10898: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10899: user for the level given by URL.  Optional start and end dates (leave empty
                   10900: string or zero for "no date")
1.191     harris41 10901: 
                   10902: =item *
                   10903: 
1.243     albertel 10904: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10905: change a users, password, possible return values are: ok,
                   10906: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10907: refused
1.191     harris41 10908: 
                   10909: =item *
                   10910: 
1.243     albertel 10911: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10912: 
                   10913: =item *
                   10914: 
1.1058    raeburn  10915: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10916:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10917: 
                   10918: will update user information (firstname,middlename,lastname,generation,
                   10919: permanentemail), and if forceid is true, student/employee ID also.
                   10920: A user's institutional affiliation(s) can also be updated.
                   10921: User information fields will not be overwritten with empty entries 
                   10922: unless the field is included in the $candelete array reference.
                   10923: This array is included when a single user is modified via "Manage Users",
                   10924: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10925: 
                   10926: =item *
                   10927: 
1.286     matthew  10928: modifystudent
                   10929: 
1.957     raeburn  10930: modify a student's enrollment and identification information.
1.286     matthew  10931: The course id is resolved based on the current users environment.  
                   10932: This means the envoking user must be a course coordinator or otherwise
                   10933: associated with a course.
                   10934: 
1.297     matthew  10935: This call is essentially a wrapper for lonnet::modifyuser and
                   10936: lonnet::modify_student_enrollment
1.286     matthew  10937: 
                   10938: Inputs: 
                   10939: 
                   10940: =over 4
                   10941: 
1.957     raeburn  10942: =item B<$udom> Student's loncapa domain
1.286     matthew  10943: 
1.957     raeburn  10944: =item B<$uname> Student's loncapa login name
1.286     matthew  10945: 
1.964     bisitz   10946: =item B<$uid> Student/Employee ID
1.286     matthew  10947: 
1.957     raeburn  10948: =item B<$umode> Student's authentication mode
1.286     matthew  10949: 
1.957     raeburn  10950: =item B<$upass> Student's password
1.286     matthew  10951: 
1.957     raeburn  10952: =item B<$first> Student's first name
1.286     matthew  10953: 
1.957     raeburn  10954: =item B<$middle> Student's middle name
1.286     matthew  10955: 
1.957     raeburn  10956: =item B<$last> Student's last name
1.286     matthew  10957: 
1.957     raeburn  10958: =item B<$gene> Student's generation
1.286     matthew  10959: 
1.957     raeburn  10960: =item B<$usec> Student's section in course
1.286     matthew  10961: 
                   10962: =item B<$end> Unix time of the roles expiration
                   10963: 
                   10964: =item B<$start> Unix time of the roles start date
                   10965: 
                   10966: =item B<$forceid> If defined, allow $uid to be changed
                   10967: 
                   10968: =item B<$desiredhome> server to use as home server for student
                   10969: 
1.957     raeburn  10970: =item B<$email> Student's permanent e-mail address
                   10971: 
                   10972: =item B<$type> Type of enrollment (auto or manual)
                   10973: 
1.963     raeburn  10974: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10975: 
                   10976: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10977: 
1.963     raeburn  10978: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10979: 
1.963     raeburn  10980: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10981: 
1.963     raeburn  10982: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10983: 
1.286     matthew  10984: =back
1.297     matthew  10985: 
                   10986: =item *
                   10987: 
                   10988: modify_student_enrollment
                   10989: 
                   10990: Change a students enrollment status in a class.  The environment variable
                   10991: 'role.request.course' must be defined for this function to proceed.
                   10992: 
                   10993: Inputs:
                   10994: 
                   10995: =over 4
                   10996: 
                   10997: =item $udom, students domain
                   10998: 
                   10999: =item $uname, students name
                   11000: 
                   11001: =item $uid, students user id
                   11002: 
                   11003: =item $first, students first name
                   11004: 
                   11005: =item $middle
                   11006: 
                   11007: =item $last
                   11008: 
                   11009: =item $gene
                   11010: 
                   11011: =item $usec
                   11012: 
                   11013: =item $end
                   11014: 
                   11015: =item $start
                   11016: 
1.957     raeburn  11017: =item $type
                   11018: 
                   11019: =item $locktype
                   11020: 
                   11021: =item $cid
                   11022: 
                   11023: =item $selfenroll
                   11024: 
                   11025: =item $context
                   11026: 
1.297     matthew  11027: =back
                   11028: 
1.191     harris41 11029: 
                   11030: =item *
                   11031: 
1.243     albertel 11032: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11033: custom role; give a custom role to a user for the level given by URL.  Specify
                   11034: name and domain of role author, and role name
1.191     harris41 11035: 
                   11036: =item *
                   11037: 
1.243     albertel 11038: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11039: 
                   11040: =item *
                   11041: 
1.243     albertel 11042: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11043: 
                   11044: =back
                   11045: 
                   11046: =head2 Course Infomation
                   11047: 
                   11048: =over 4
1.191     harris41 11049: 
                   11050: =item *
                   11051: 
1.1118    foxr     11052: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11053: specified course id, including all environment settings for the
                   11054: course, the description of the course will be in the hash under the
                   11055: key 'description'
1.191     harris41 11056: 
1.1118    foxr     11057: $options is an optional parameter that if supplied is a hash reference that controls
                   11058: what how this function works.  It has the following key/values:
                   11059: 
                   11060: =over 4
                   11061: 
                   11062: =item freshen_cache
                   11063: 
                   11064: If defined, and the environment cache for the course is valid, it is 
                   11065: returned in the returned hash.
                   11066: 
                   11067: =item one_time
                   11068: 
                   11069: If defined, the last cache time is set to _now_
                   11070: 
                   11071: =item user
                   11072: 
                   11073: If defined, the supplied username is used instead of the current user.
                   11074: 
                   11075: 
                   11076: =back
                   11077: 
1.191     harris41 11078: =item *
                   11079: 
1.624     albertel 11080: resdata($name,$domain,$type,@which) : request for current parameter
                   11081: setting for a specific $type, where $type is either 'course' or 'user',
                   11082: @what should be a list of parameters to ask about. This routine caches
                   11083: answers for 5 minutes.
1.243     albertel 11084: 
1.877     foxr     11085: =item *
                   11086: 
                   11087: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11088: data base, returning a hash that is keyed by the resource name and has
                   11089: values that are the resource value.  I believe that the timestamps and
                   11090: versions are also returned.
                   11091: 
                   11092: 
1.243     albertel 11093: =back
                   11094: 
                   11095: =head2 Course Modification
                   11096: 
                   11097: =over 4
1.191     harris41 11098: 
                   11099: =item *
                   11100: 
1.243     albertel 11101: writecoursepref($courseid,%prefs) : write preferences (environment
                   11102: database) for a course
1.191     harris41 11103: 
                   11104: =item *
                   11105: 
1.1011    raeburn  11106: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11107: 
                   11108: =item *
                   11109: 
1.1038    raeburn  11110: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11111: 
                   11112: =back
                   11113: 
                   11114: =head2 Resource Subroutines
                   11115: 
                   11116: =over 4
1.191     harris41 11117: 
                   11118: =item *
                   11119: 
1.243     albertel 11120: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11121: 
                   11122: =item *
                   11123: 
1.243     albertel 11124: repcopy($filename) : subscribes to the requested file, and attempts to
                   11125: replicate from the owning library server, Might return
1.607     raeburn  11126: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11127: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11128: resource. Expects the local filesystem pathname
                   11129: (/home/httpd/html/res/....)
                   11130: 
                   11131: =back
                   11132: 
                   11133: =head2 Resource Information
                   11134: 
                   11135: =over 4
1.191     harris41 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11140: a vairety of different possible values, $varname should be a request
                   11141: string, and the other parameters can be used to specify who and what
                   11142: one is asking about.
                   11143: 
                   11144: Possible values for $varname are environment.lastname (or other item
                   11145: from the envirnment hash), user.name (or someother aspect about the
                   11146: user), resource.0.maxtries (or some other part and parameter of a
                   11147: resource)
1.204     albertel 11148: 
                   11149: =item *
                   11150: 
1.243     albertel 11151: directcondval($number) : get current value of a condition; reads from a state
                   11152: string
1.204     albertel 11153: 
                   11154: =item *
                   11155: 
1.243     albertel 11156: condval($condidx) : value of condition index based on state
1.204     albertel 11157: 
                   11158: =item *
                   11159: 
1.243     albertel 11160: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11161: resource's metadata, $what should be either a specific key, or either
                   11162: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11163: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11164: 
                   11165: this function automatically caches all requests
1.191     harris41 11166: 
                   11167: =item *
                   11168: 
1.243     albertel 11169: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11170: network of library servers; returns file handle of where SQL and regex results
                   11171: will be stored for query
1.191     harris41 11172: 
                   11173: =item *
                   11174: 
1.243     albertel 11175: symbread($filename) : return symbolic list entry (filename argument optional);
                   11176: returns the data handle
1.191     harris41 11177: 
                   11178: =item *
                   11179: 
1.243     albertel 11180: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11181: a possible symb for the URL in $thisfn, and if is an encryypted
                   11182: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11183: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11184: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11185: 
1.191     harris41 11186: 
                   11187: =item *
                   11188: 
1.243     albertel 11189: symbclean($symb) : removes versions numbers from a symb, returns the
                   11190: cleaned symb
1.191     harris41 11191: 
                   11192: =item *
                   11193: 
1.243     albertel 11194: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11195: course map, user must be in a course for it to work.
1.191     harris41 11196: 
                   11197: =item *
                   11198: 
1.243     albertel 11199: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11200: 
                   11201: =item *
                   11202: 
1.243     albertel 11203: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11204: a random seed, all arguments are optional, if they aren't sent it uses the
                   11205: environment to derive them. Note: if symb isn't sent and it can't get one
                   11206: from &symbread it will use the current time as its return value
1.191     harris41 11207: 
                   11208: =item *
                   11209: 
1.243     albertel 11210: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11211: unfakeable, receipt
1.191     harris41 11212: 
                   11213: =item *
                   11214: 
1.620     albertel 11215: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11216: 
                   11217: =item *
                   11218: 
1.243     albertel 11219: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11220: 
                   11221: =item *
                   11222: 
1.243     albertel 11223: 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 11224: 
                   11225: =item *
                   11226: 
1.243     albertel 11227: 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 11228: 
                   11229: =item *
                   11230: 
1.243     albertel 11231: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11232: 
                   11233: =item *
                   11234: 
1.243     albertel 11235: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11236: forcing spreadsheet to reevaluate the resource scores next time.
                   11237: 
                   11238: =back
                   11239: 
                   11240: =head2 Storing/Retreiving Data
                   11241: 
                   11242: =over 4
1.191     harris41 11243: 
                   11244: =item *
                   11245: 
1.243     albertel 11246: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11247: for this url; hashref needs to be given and should be a \%hashname; the
                   11248: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11249: be derived from the env
1.191     harris41 11250: 
                   11251: =item *
                   11252: 
1.243     albertel 11253: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11254: uses critical subroutine
1.191     harris41 11255: 
                   11256: =item *
                   11257: 
1.243     albertel 11258: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11259: all args are optional
1.191     harris41 11260: 
                   11261: =item *
                   11262: 
1.717     albertel 11263: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11264: dumps the complete (or key matching regexp) namespace into a hash
                   11265: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11266: normally &store()ed into
                   11267: 
                   11268: $range should be either an integer '100' (give me the first 100
                   11269:                                            matching records)
                   11270:               or be  two integers sperated by a - with no spaces
                   11271:                  '30-50' (give me the 30th through the 50th matching
                   11272:                           records)
                   11273: 
                   11274: 
                   11275: =item *
                   11276: 
                   11277: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11278: replaces a &store() version of data with a replacement set of data
                   11279: for a particular resource in a namespace passed in the $storehash hash 
                   11280: reference
                   11281: 
                   11282: =item *
                   11283: 
1.243     albertel 11284: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11285: works very similar to store/cstore, but all data is stored in a
                   11286: temporary location and can be reset using tmpreset, $storehash should
                   11287: be a hash reference, returns nothing on success
1.191     harris41 11288: 
                   11289: =item *
                   11290: 
1.243     albertel 11291: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11292: similar to restore, but all data is stored in a temporary location and
                   11293: can be reset using tmpreset. Returns a hash of values on success,
                   11294: error string otherwise.
1.191     harris41 11295: 
                   11296: =item *
                   11297: 
1.243     albertel 11298: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11299: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11300: 
                   11301: =item *
                   11302: 
1.243     albertel 11303: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11304: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11305: 
                   11306: =item *
                   11307: 
1.243     albertel 11308: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11309: namesp ($udom and $uname are optional)
1.191     harris41 11310: 
                   11311: =item *
                   11312: 
1.702     albertel 11313: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11314: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11315: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11316: 
1.702     albertel 11317: $range should be either an integer '100' (give me the first 100
                   11318:                                            matching records)
                   11319:               or be  two integers sperated by a - with no spaces
                   11320:                  '30-50' (give me the 30th through the 50th matching
                   11321:                           records)
1.449     matthew  11322: =item *
                   11323: 
                   11324: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11325: $store can be a scalar, an array reference, or if the amount to be 
                   11326: incremented is > 1, a hash reference.
                   11327: 
                   11328: ($udom and $uname are optional)
1.191     harris41 11329: 
                   11330: =item *
                   11331: 
1.243     albertel 11332: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11333: ($udom and $uname are optional)
1.191     harris41 11334: 
                   11335: =item *
                   11336: 
1.243     albertel 11337: cput($namespace,$storehash,$udom,$uname) : critical put
                   11338: ($udom and $uname are optional)
1.191     harris41 11339: 
                   11340: =item *
                   11341: 
1.748     albertel 11342: newput($namespace,$storehash,$udom,$uname) :
                   11343: 
                   11344: Attempts to store the items in the $storehash, but only if they don't
                   11345: currently exist, if this succeeds you can be certain that you have 
                   11346: successfully created a new key value pair in the $namespace db.
                   11347: 
                   11348: 
                   11349: Args:
                   11350:  $namespace: name of database to store values to
                   11351:  $storehash: hashref to store to the db
                   11352:  $udom: (optional) domain of user containing the db
                   11353:  $uname: (optional) name of user caontaining the db
                   11354: 
                   11355: Returns:
                   11356:  'ok' -> succeeded in storing all keys of $storehash
                   11357:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11358:                         least <key> already existed in the db (other
                   11359:                         requested keys may also already exist)
1.967     bisitz   11360:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11361:  'con_lost' -> unable to contact request server
                   11362:  'refused' -> action was not allowed by remote machine
                   11363: 
                   11364: 
                   11365: =item *
                   11366: 
1.243     albertel 11367: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11368: reference filled in from namesp (encrypts the return communication)
                   11369: ($udom and $uname are optional)
1.191     harris41 11370: 
                   11371: =item *
                   11372: 
1.243     albertel 11373: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11374: critical subroutine
                   11375: 
1.806     raeburn  11376: =item *
                   11377: 
1.860     raeburn  11378: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11379: array reference filled in from namespace found in domain level on either
                   11380: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11381: 
                   11382: =item *
                   11383: 
1.860     raeburn  11384: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11385: domain level either on specified domain server ($uhome) or primary domain 
                   11386: server ($udom and $uhome are optional)
1.806     raeburn  11387: 
1.943     raeburn  11388: =item * 
                   11389: 
                   11390: get_domain_defaults($target_domain) : returns hash with defaults for
                   11391: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11392: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11393: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11394: Values are retrieved from cache (if current), or from domain's configuration.db
                   11395: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11396: or lonTabs/domain.tab. 
                   11397: 
                   11398: %domdefaults = &get_auth_defaults($target_domain);
                   11399: 
1.243     albertel 11400: =back
                   11401: 
                   11402: =head2 Network Status Functions
                   11403: 
                   11404: =over 4
1.191     harris41 11405: 
                   11406: =item *
                   11407: 
                   11408: dirlist($uri) : return directory list based on URI
                   11409: 
                   11410: =item *
                   11411: 
1.243     albertel 11412: spareserver() : find server with least workload from spare.tab
                   11413: 
1.986     foxr     11414: 
                   11415: =item *
                   11416: 
                   11417: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11418: if there is no corresponding loncapa host.
                   11419: 
1.243     albertel 11420: =back
                   11421: 
1.986     foxr     11422: 
1.243     albertel 11423: =head2 Apache Request
                   11424: 
                   11425: =over 4
1.191     harris41 11426: 
                   11427: =item *
                   11428: 
1.243     albertel 11429: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11430: localhost, posts hash
                   11431: 
                   11432: =back
                   11433: 
                   11434: =head2 Data to String to Data
                   11435: 
                   11436: =over 4
1.191     harris41 11437: 
                   11438: =item *
                   11439: 
1.243     albertel 11440: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11441: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11442: 
                   11443: =item *
                   11444: 
1.243     albertel 11445: hashref2str($hashref) : convert a hashref into a string complete with
                   11446: escaping and '=' and '&' separators, supports elements that are
                   11447: arrayrefs and hashrefs
1.191     harris41 11448: 
                   11449: =item *
                   11450: 
1.243     albertel 11451: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11452: with escaping and '&' separators, supports elements that are arrayrefs
                   11453: and hashrefs
1.191     harris41 11454: 
                   11455: =item *
                   11456: 
1.243     albertel 11457: str2hash($string) : convert string to hash using unescaping and
                   11458: splitting on '=' and '&', supports elements that are arrayrefs and
                   11459: hashrefs
1.191     harris41 11460: 
                   11461: =item *
                   11462: 
1.243     albertel 11463: str2array($string) : convert string to hash using unescaping and
                   11464: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11465: 
                   11466: =back
                   11467: 
                   11468: =head2 Logging Routines
                   11469: 
                   11470: 
                   11471: These routines allow one to make log messages in the lonnet.log and
                   11472: lonnet.perm logfiles.
1.191     harris41 11473: 
1.1119    foxr     11474: =over 4
                   11475: 
1.191     harris41 11476: =item *
                   11477: 
1.243     albertel 11478: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11479: 
                   11480: =item *
                   11481: 
1.243     albertel 11482: logthis() : append message to the normal lonnet.log file, it gets
                   11483: preiodically rolled over and deleted.
1.191     harris41 11484: 
                   11485: =item *
                   11486: 
1.243     albertel 11487: logperm() : append a permanent message to lonnet.perm.log, this log
                   11488: file never gets deleted by any automated portion of the system, only
                   11489: messages of critical importance should go in here.
                   11490: 
1.1119    foxr     11491: 
1.243     albertel 11492: =back
                   11493: 
                   11494: =head2 General File Helper Routines
                   11495: 
                   11496: =over 4
1.191     harris41 11497: 
                   11498: =item *
                   11499: 
1.481     raeburn  11500: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11501: (a) files in /uploaded
                   11502:   (i) If a local copy of the file exists - 
                   11503:       compares modification date of local copy with last-modified date for 
                   11504:       definitive version stored on home server for course. If local copy is 
                   11505:       stale, requests a new version from the home server and stores it. 
                   11506:       If the original has been removed from the home server, then local copy 
                   11507:       is unlinked.
                   11508:   (ii) If local copy does not exist -
                   11509:       requests the file from the home server and stores it. 
                   11510:   
                   11511:   If $caller is 'uploadrep':  
                   11512:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11513:     for request for files originally uploaded via DOCS. 
                   11514:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11515:   
                   11516:   Otherwise:
                   11517:      This indicates a call from the content generation phase of the request.
                   11518:      -  returns the entire contents of the file or -1.
                   11519:      
                   11520: (b) files in /res
                   11521:    - returns the entire contents of a file or -1; 
                   11522:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11523: 
1.712     albertel 11524: 
                   11525: =item *
                   11526: 
                   11527: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11528:                   reference
                   11529: 
                   11530: returns either a stat() list of data about the file or an empty list
                   11531: if the file doesn't exist or couldn't find out about it (connection
                   11532: problems or user unknown)
                   11533: 
1.191     harris41 11534: =item *
                   11535: 
1.243     albertel 11536: filelocation($dir,$file) : returns file system location of a file
                   11537: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11538: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11539: and a file of ../bob will become /a/bob)
1.191     harris41 11540: 
                   11541: =item *
                   11542: 
                   11543: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11544: filelocation except for hrefs
                   11545: 
                   11546: =item *
                   11547: 
                   11548: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11549: 
1.243     albertel 11550: =back
                   11551: 
1.608     albertel 11552: =head2 Usererfile file routines (/uploaded*)
                   11553: 
                   11554: =over 4
                   11555: 
                   11556: =item *
                   11557: 
                   11558: userfileupload(): main rotine for putting a file in a user or course's
                   11559:                   filespace, arguments are,
                   11560: 
1.620     albertel 11561:  formname - required - this is the name of the element in $env where the
1.608     albertel 11562:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11563:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11564:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11565:  context - if coursedoc, store the file in the course of the active role
                   11566:              of the current user; 
                   11567:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11568:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11569:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11570:          if undefined, it will be placed in "unknown"
                   11571: 
                   11572:  (This routine calls clean_filename() to remove any dangerous
                   11573:  characters from the filename, and then calls finuserfileupload() to
                   11574:  complete the transaction)
                   11575: 
                   11576:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11577:  and /adm/notfound.html if unsuccessful
                   11578: 
                   11579: =item *
                   11580: 
                   11581: clean_filename(): routine for cleaing a filename up for storage in
                   11582:                  userfile space, argument is:
                   11583: 
                   11584:  filename - proposed filename
                   11585: 
                   11586: returns: the new clean filename
                   11587: 
                   11588: =item *
                   11589: 
1.1090    raeburn  11590: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11591: userspace, probably shouldn't be called directly
                   11592: 
                   11593:   docuname: username or courseid of destination for the file
                   11594:   docudom: domain of user/course of destination for the file
                   11595:   formname: same as for userfileupload()
1.1090    raeburn  11596:   fname: filename (including subdirectories) for the file
                   11597:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11598:   allfiles: reference to hash used to store objects found by parser
                   11599:   codebase: reference to hash used for codebases of java objects found by parser
                   11600:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11601:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11602:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11603:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11604:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11605:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11606:   mimetype: reference to scalar to accommodate mime type determined
                   11607:             from File::MMagic if $parser = parse.
1.608     albertel 11608: 
                   11609:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11610:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11611:  was 'overwrite').
                   11612:  
1.608     albertel 11613: 
                   11614: =item *
                   11615: 
                   11616: renameuserfile(): renames an existing userfile to a new name
                   11617: 
                   11618:   Args:
                   11619:    docuname: username or courseid of destination for the file
                   11620:    docudom: domain of user/course of destination for the file
                   11621:    old: current file name (including any subdirs under userfiles)
                   11622:    new: desired file name (including any subdirs under userfiles)
                   11623: 
                   11624: =item *
                   11625: 
                   11626: mkdiruserfile(): creates a directory is a userfiles dir
                   11627: 
                   11628:   Args:
                   11629:    docuname: username or courseid of destination for the file
                   11630:    docudom: domain of user/course of destination for the file
                   11631:    dir: dir to create (including any subdirs under userfiles)
                   11632: 
                   11633: =item *
                   11634: 
                   11635: removeuserfile(): removes a file that exists in userfiles
                   11636: 
                   11637:   Args:
                   11638:    docuname: username or courseid of destination for the file
                   11639:    docudom: domain of user/course of destination for the file
                   11640:    fname: filname to delete (including any subdirs under userfiles)
                   11641: 
                   11642: =item *
                   11643: 
                   11644: removeuploadedurl(): convience function for removeuserfile()
                   11645: 
                   11646:   Args:
                   11647:    url:  a full /uploaded/... url to delete
                   11648: 
1.747     albertel 11649: =item * 
                   11650: 
                   11651: get_portfile_permissions():
                   11652:   Args:
                   11653:     domain: domain of user or course contain the portfolio files
                   11654:     user: name of user or num of course contain the portfolio files
                   11655:   Returns:
                   11656:     hashref of a dump of the proper file_permissions.db
                   11657:    
                   11658: 
                   11659: =item * 
                   11660: 
                   11661: get_access_controls():
                   11662: 
                   11663: Args:
                   11664:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11665:   group: (optional) the group you want the files associated with
                   11666:   file: (optional) the file you want access info on
                   11667: 
                   11668: Returns:
1.749     raeburn  11669:     a hash (keys are file names) of hashes containing
                   11670:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11671:         values are XML containing access control settings (see below) 
1.747     albertel 11672: 
                   11673: Internal notes:
                   11674: 
1.749     raeburn  11675:  access controls are stored in file_permissions.db as key=value pairs.
                   11676:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11677:         where scope -> public,guest,course,group,domains or users.
                   11678:               end -> UNIX time for end of access (0 -> no end date)
                   11679:               start -> UNIX time for start of access
                   11680: 
                   11681:     value -> XML description of access control
                   11682:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11683:             <start></start>
                   11684:             <end></end>
                   11685: 
                   11686:             <password></password>  for scope type = guest
                   11687: 
                   11688:             <domain></domain>     for scope type = course or group
                   11689:             <number></number>
                   11690:             <roles id="">
                   11691:              <role></role>
                   11692:              <access></access>
                   11693:              <section></section>
                   11694:              <group></group>
                   11695:             </roles>
                   11696: 
                   11697:             <dom></dom>         for scope type = domains
                   11698: 
                   11699:             <users>             for scope type = users
                   11700:              <user>
                   11701:               <uname></uname>
                   11702:               <udom></udom>
                   11703:              </user>
                   11704:             </users>
                   11705:            </scope> 
                   11706:               
                   11707:  Access data is also aggregated for each file in an additional key=value pair:
                   11708:  key -> path to file/file_name\0accesscontrol 
                   11709:  value -> reference to hash
                   11710:           hash contains key = value pairs
                   11711:           where key = uniqueID:scope_end_start
                   11712:                 value = UNIX time record was last updated
                   11713: 
                   11714:           Used to improve speed of look-ups of access controls for each file.  
                   11715:  
                   11716:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11717: 
                   11718: modify_access_controls():
                   11719: 
                   11720: Modifies access controls for a portfolio file
                   11721: Args
                   11722: 1. file name
                   11723: 2. reference to hash of required changes,
                   11724: 3. domain
                   11725: 4. username
                   11726:   where domain,username are the domain of the portfolio owner 
                   11727:   (either a user or a course) 
                   11728: 
                   11729: Returns:
                   11730: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11731: 2. result of deletions ('ok' or 'error', with error message).
                   11732: 3. reference to hash of any new or updated access controls.
                   11733: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11734:    key = integer (inbound ID)
                   11735:    value = uniqueID  
1.747     albertel 11736: 
1.608     albertel 11737: =back
                   11738: 
1.243     albertel 11739: =head2 HTTP Helper Routines
                   11740: 
                   11741: =over 4
                   11742: 
1.191     harris41 11743: =item *
                   11744: 
                   11745: escape() : unpack non-word characters into CGI-compatible hex codes
                   11746: 
                   11747: =item *
                   11748: 
                   11749: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11750: 
1.243     albertel 11751: =back
                   11752: 
                   11753: =head1 PRIVATE SUBROUTINES
                   11754: 
                   11755: =head2 Underlying communication routines (Shouldn't call)
                   11756: 
                   11757: =over 4
                   11758: 
                   11759: =item *
                   11760: 
                   11761: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11762: 
                   11763: =item *
                   11764: 
                   11765: reply() : uses subreply to send a message to remote machine, logs all failures
                   11766: 
                   11767: =item *
                   11768: 
                   11769: critical() : passes a critical message to another server; if cannot
                   11770: get through then place message in connection buffer directory and
                   11771: returns con_delayed, if incapable of saving message, returns
                   11772: con_failed
                   11773: 
                   11774: =item *
                   11775: 
                   11776: reconlonc() : tries to reconnect lonc client processes.
                   11777: 
                   11778: =back
                   11779: 
                   11780: =head2 Resource Access Logging
                   11781: 
                   11782: =over 4
                   11783: 
                   11784: =item *
                   11785: 
                   11786: flushcourselogs() : flush (save) buffer logs and access logs
                   11787: 
                   11788: =item *
                   11789: 
                   11790: courselog($what) : save message for course in hash
                   11791: 
                   11792: =item *
                   11793: 
                   11794: courseacclog($what) : save message for course using &courselog().  Perform
                   11795: special processing for specific resource types (problems, exams, quizzes, etc).
                   11796: 
1.191     harris41 11797: =item *
                   11798: 
                   11799: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11800: as a PerlChildExitHandler
1.243     albertel 11801: 
                   11802: =back
                   11803: 
                   11804: =head2 Other
                   11805: 
                   11806: =over 4
                   11807: 
                   11808: =item *
                   11809: 
                   11810: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11811: 
                   11812: =back
                   11813: 
                   11814: =cut
1.877     foxr     11815: 

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