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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1119  ! foxr        4: # $Id: lonnet.pm,v 1.1118 2011/07/18 10:25:55 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') {
                   1038:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                   1039:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1040:                     $canhost = 0;
                   1041:                 } else {
                   1042:                     $canhost = 1;
                   1043:                 }
                   1044:             }
                   1045:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1046:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1047:                     $canhost = 1;
                   1048:                 } else {
                   1049:                     $canhost = 0;
                   1050:                 }
                   1051:             }
                   1052:         }
                   1053:     }
                   1054:     return $canhost;
                   1055: }
                   1056: 
1.1083    raeburn  1057: sub spare_can_host {
                   1058:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1059:     my $canhost=1;
                   1060:     my @intdoms;
                   1061:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1062:     if (ref($internet_names) eq 'ARRAY') {
                   1063:         @intdoms = @{$internet_names};
                   1064:     }
                   1065:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1066:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1067:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1068:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1069:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1070:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1071:                                      $remotesessions,
                   1072:                                      $defdomdefaults{'hostedsessions'});
                   1073:     }
                   1074:     return $canhost;
                   1075: }
                   1076: 
1.1       albertel 1077: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1078: 
1.599     albertel 1079: my %homecache;
1.1       albertel 1080: sub homeserver {
1.230     stredwic 1081:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1082:     my $index="$uname:$udom";
1.426     albertel 1083: 
1.599     albertel 1084:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1085: 
                   1086:     my %servers = &get_servers($udom,'library');
                   1087:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1088:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1089: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1090: 
                   1091: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1092: 	if ($answer eq 'found') {
                   1093: 	    delete($badServerCache{$tryserver}); 
                   1094: 	    return $homecache{$index}=$tryserver;
                   1095: 	} elsif ($answer eq 'no_host') {
                   1096: 	    $badServerCache{$tryserver}=1;
                   1097: 	}
1.1       albertel 1098:     }    
                   1099:     return 'no_host';
1.70      www      1100: }
                   1101: 
                   1102: # ------------------------------------- Find the usernames behind a list of IDs
                   1103: 
                   1104: sub idget {
                   1105:     my ($udom,@ids)=@_;
                   1106:     my %returnhash=();
                   1107:     
1.841     albertel 1108:     my %servers = &get_servers($udom,'library');
                   1109:     foreach my $tryserver (keys(%servers)) {
                   1110: 	my $idlist=join('&',@ids);
                   1111: 	$idlist=~tr/A-Z/a-z/; 
                   1112: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1113: 	my @answer=();
                   1114: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1115: 	    @answer=split(/\&/,$reply);
                   1116: 	}                    ;
                   1117: 	my $i;
                   1118: 	for ($i=0;$i<=$#ids;$i++) {
                   1119: 	    if ($answer[$i]) {
                   1120: 		$returnhash{$ids[$i]}=$answer[$i];
                   1121: 	    } 
                   1122: 	}
                   1123:     } 
1.70      www      1124:     return %returnhash;
                   1125: }
                   1126: 
                   1127: # ------------------------------------- Find the IDs behind a list of usernames
                   1128: 
                   1129: sub idrget {
                   1130:     my ($udom,@unames)=@_;
                   1131:     my %returnhash=();
1.800     albertel 1132:     foreach my $uname (@unames) {
                   1133:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1134:     }
1.70      www      1135:     return %returnhash;
                   1136: }
                   1137: 
                   1138: # ------------------------------- Store away a list of names and associated IDs
                   1139: 
                   1140: sub idput {
                   1141:     my ($udom,%ids)=@_;
                   1142:     my %servers=();
1.800     albertel 1143:     foreach my $uname (keys(%ids)) {
                   1144: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1145:         my $uhom=&homeserver($uname,$udom);
1.70      www      1146:         if ($uhom ne 'no_host') {
1.800     albertel 1147:             my $id=&escape($ids{$uname});
1.70      www      1148:             $id=~tr/A-Z/a-z/;
1.800     albertel 1149:             my $esc_unam=&escape($uname);
1.70      www      1150: 	    if ($servers{$uhom}) {
1.800     albertel 1151: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1152:             } else {
1.800     albertel 1153:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1154:             }
                   1155:         }
1.191     harris41 1156:     }
1.800     albertel 1157:     foreach my $server (keys(%servers)) {
                   1158:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1159:     }
1.344     www      1160: }
                   1161: 
1.1023    raeburn  1162: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1163: sub dump_dom {
1.1023    raeburn  1164:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1165:     if (!$udom) {
                   1166:         $udom=$env{'user.domain'};
                   1167:     }
                   1168:     my %returnhash;
1.1023    raeburn  1169:     if ($udom) {
                   1170:         my $uname = &get_domainconfiguser($udom);
                   1171:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1172:     }
                   1173:     return %returnhash;
                   1174: }
                   1175: 
1.1023    raeburn  1176: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1177: 
                   1178: sub get_dom {
1.860     raeburn  1179:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1180:     my $items='';
                   1181:     foreach my $item (@$storearr) {
                   1182:         $items.=&escape($item).'&';
                   1183:     }
                   1184:     $items=~s/\&$//;
1.860     raeburn  1185:     if (!$udom) {
                   1186:         $udom=$env{'user.domain'};
                   1187:         if (defined(&domain($udom,'primary'))) {
                   1188:             $uhome=&domain($udom,'primary');
                   1189:         } else {
1.874     albertel 1190:             undef($uhome);
1.860     raeburn  1191:         }
                   1192:     } else {
                   1193:         if (!$uhome) {
                   1194:             if (defined(&domain($udom,'primary'))) {
                   1195:                 $uhome=&domain($udom,'primary');
                   1196:             }
                   1197:         }
                   1198:     }
                   1199:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1200:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1201:         my %returnhash;
1.875     albertel 1202:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1203:             return %returnhash;
                   1204:         }
1.806     raeburn  1205:         my @pairs=split(/\&/,$rep);
                   1206:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1207:             return @pairs;
                   1208:         }
                   1209:         my $i=0;
                   1210:         foreach my $item (@$storearr) {
                   1211:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1212:             $i++;
                   1213:         }
                   1214:         return %returnhash;
                   1215:     } else {
1.880     banghart 1216:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1217:     }
                   1218: }
                   1219: 
                   1220: # -------------------------------------------- put items in domain db files 
                   1221: 
                   1222: sub put_dom {
1.860     raeburn  1223:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1224:     if (!$udom) {
                   1225:         $udom=$env{'user.domain'};
                   1226:         if (defined(&domain($udom,'primary'))) {
                   1227:             $uhome=&domain($udom,'primary');
                   1228:         } else {
1.874     albertel 1229:             undef($uhome);
1.860     raeburn  1230:         }
                   1231:     } else {
                   1232:         if (!$uhome) {
                   1233:             if (defined(&domain($udom,'primary'))) {
                   1234:                 $uhome=&domain($udom,'primary');
                   1235:             }
                   1236:         }
                   1237:     } 
                   1238:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1239:         my $items='';
                   1240:         foreach my $item (keys(%$storehash)) {
                   1241:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1242:         }
                   1243:         $items=~s/\&$//;
                   1244:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1245:     } else {
1.860     raeburn  1246:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1247:     }
                   1248: }
                   1249: 
1.1023    raeburn  1250: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1251: sub newput_dom {
1.1023    raeburn  1252:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1253:     my $result;
                   1254:     if (!$udom) {
                   1255:         $udom=$env{'user.domain'};
                   1256:     }
1.1023    raeburn  1257:     if ($udom) {
                   1258:         my $uname = &get_domainconfiguser($udom);
                   1259:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1260:     }
                   1261:     return $result;
                   1262: }
                   1263: 
1.1023    raeburn  1264: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1265: sub del_dom {
1.1023    raeburn  1266:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1267:     if (ref($storearr) eq 'ARRAY') {
                   1268:         if (!$udom) {
                   1269:             $udom=$env{'user.domain'};
                   1270:         }
1.1023    raeburn  1271:         if ($udom) {
                   1272:             my $uname = &get_domainconfiguser($udom); 
                   1273:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1274:         }
                   1275:     }
                   1276: }
                   1277: 
1.1023    raeburn  1278: # ----------------------------------construct domainconfig user for a domain 
                   1279: sub get_domainconfiguser {
                   1280:     my ($udom) = @_;
                   1281:     return $udom.'-domainconfig';
                   1282: }
                   1283: 
1.837     raeburn  1284: sub retrieve_inst_usertypes {
                   1285:     my ($udom) = @_;
                   1286:     my (%returnhash,@order);
1.989     raeburn  1287:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1288:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1289:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1290:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1291:         @order = @{$domdefs{'inststatusorder'}};
                   1292:     } else {
                   1293:         if (defined(&domain($udom,'primary'))) {
                   1294:             my $uhome=&domain($udom,'primary');
                   1295:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1296:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1297:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1298:                 return (\%returnhash,\@order);
                   1299:             }
                   1300:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1301:             my @pairs=split(/\&/,$hashitems);
                   1302:             foreach my $item (@pairs) {
                   1303:                 my ($key,$value)=split(/=/,$item,2);
                   1304:                 $key = &unescape($key);
                   1305:                 next if ($key =~ /^error: 2 /);
                   1306:                 $returnhash{$key}=&thaw_unescape($value);
                   1307:             }
                   1308:             my @esc_order = split(/\&/,$orderitems);
                   1309:             foreach my $item (@esc_order) {
                   1310:                 push(@order,&unescape($item));
                   1311:             }
                   1312:         } else {
                   1313:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1314:         }
                   1315:     }
                   1316:     return (\%returnhash,\@order);
                   1317: }
                   1318: 
1.868     raeburn  1319: sub is_domainimage {
                   1320:     my ($url) = @_;
                   1321:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1322:         if (&domain($1) ne '') {
                   1323:             return '1';
                   1324:         }
                   1325:     }
                   1326:     return;
                   1327: }
                   1328: 
1.899     raeburn  1329: sub inst_directory_query {
                   1330:     my ($srch) = @_;
                   1331:     my $udom = $srch->{'srchdomain'};
                   1332:     my %results;
                   1333:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1334:     my $outcome;
1.899     raeburn  1335:     if ($homeserver ne '') {
1.904     albertel 1336: 	my $queryid=&reply("querysend:instdirsearch:".
                   1337: 			   &escape($srch->{'srchby'}).':'.
                   1338: 			   &escape($srch->{'srchterm'}).':'.
                   1339: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1340: 	my $host=&hostname($homeserver);
                   1341: 	if ($queryid !~/^\Q$host\E\_/) {
                   1342: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1343: 	    return;
                   1344: 	}
                   1345: 	my $response = &get_query_reply($queryid);
                   1346: 	my $maxtries = 5;
                   1347: 	my $tries = 1;
                   1348: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1349: 	    $response = &get_query_reply($queryid);
                   1350: 	    $tries ++;
                   1351: 	}
                   1352: 
                   1353:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1354:             if ($response eq 'unavailable') {
                   1355:                 $outcome = $response;
                   1356:             } else {
                   1357:                 $outcome = 'ok';
                   1358:                 my @matches = split(/\n/,$response);
                   1359:                 foreach my $match (@matches) {
                   1360:                     my ($key,$value) = split(/=/,$match);
                   1361:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1362:                 }
1.899     raeburn  1363:             }
                   1364:         }
                   1365:     }
1.909     raeburn  1366:     return ($outcome,%results);
1.899     raeburn  1367: }
                   1368: 
                   1369: sub usersearch {
                   1370:     my ($srch) = @_;
                   1371:     my $dom = $srch->{'srchdomain'};
                   1372:     my %results;
                   1373:     my %libserv = &all_library();
                   1374:     my $query = 'usersearch';
                   1375:     foreach my $tryserver (keys(%libserv)) {
                   1376:         if (&host_domain($tryserver) eq $dom) {
                   1377:             my $host=&hostname($tryserver);
                   1378:             my $queryid=
1.911     raeburn  1379:                 &reply("querysend:".&escape($query).':'.
                   1380:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1381:                        &escape($srch->{'srchtype'}).':'.
                   1382:                        &escape($srch->{'srchterm'}),$tryserver);
                   1383:             if ($queryid !~/^\Q$host\E\_/) {
                   1384:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1385:                 next;
1.899     raeburn  1386:             }
                   1387:             my $reply = &get_query_reply($queryid);
                   1388:             my $maxtries = 1;
                   1389:             my $tries = 1;
                   1390:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1391:                 $reply = &get_query_reply($queryid);
                   1392:                 $tries ++;
                   1393:             }
                   1394:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1395:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1396:             } else {
1.911     raeburn  1397:                 my @matches;
                   1398:                 if ($reply =~ /\n/) {
                   1399:                     @matches = split(/\n/,$reply);
                   1400:                 } else {
                   1401:                     @matches = split(/\&/,$reply);
                   1402:                 }
1.899     raeburn  1403:                 foreach my $match (@matches) {
                   1404:                     my ($uname,$udom,%userhash);
1.911     raeburn  1405:                     foreach my $entry (split(/:/,$match)) {
                   1406:                         my ($key,$value) =
                   1407:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1408:                         $userhash{$key} = $value;
                   1409:                         if ($key eq 'username') {
                   1410:                             $uname = $value;
                   1411:                         } elsif ($key eq 'domain') {
                   1412:                             $udom = $value;
1.911     raeburn  1413:                         }
1.899     raeburn  1414:                     }
                   1415:                     $results{$uname.':'.$udom} = \%userhash;
                   1416:                 }
                   1417:             }
                   1418:         }
                   1419:     }
                   1420:     return %results;
                   1421: }
                   1422: 
1.912     raeburn  1423: sub get_instuser {
                   1424:     my ($udom,$uname,$id) = @_;
                   1425:     my $homeserver = &domain($udom,'primary');
                   1426:     my ($outcome,%results);
                   1427:     if ($homeserver ne '') {
                   1428:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1429:                            &escape($id).':'.&escape($udom),$homeserver);
                   1430:         my $host=&hostname($homeserver);
                   1431:         if ($queryid !~/^\Q$host\E\_/) {
                   1432:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1433:             return;
                   1434:         }
                   1435:         my $response = &get_query_reply($queryid);
                   1436:         my $maxtries = 5;
                   1437:         my $tries = 1;
                   1438:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1439:             $response = &get_query_reply($queryid);
                   1440:             $tries ++;
                   1441:         }
                   1442:         if (!&error($response) && $response ne 'refused') {
                   1443:             if ($response eq 'unavailable') {
                   1444:                 $outcome = $response;
                   1445:             } else {
                   1446:                 $outcome = 'ok';
                   1447:                 my @matches = split(/\n/,$response);
                   1448:                 foreach my $match (@matches) {
                   1449:                     my ($key,$value) = split(/=/,$match);
                   1450:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1451:                 }
                   1452:             }
                   1453:         }
                   1454:     }
                   1455:     my %userinfo;
                   1456:     if (ref($results{$uname}) eq 'HASH') {
                   1457:         %userinfo = %{$results{$uname}};
                   1458:     } 
                   1459:     return ($outcome,%userinfo);
                   1460: }
                   1461: 
                   1462: sub inst_rulecheck {
1.923     raeburn  1463:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1464:     my %returnhash;
                   1465:     if ($udom ne '') {
                   1466:         if (ref($rules) eq 'ARRAY') {
                   1467:             @{$rules} = map {&escape($_);} (@{$rules});
                   1468:             my $rulestr = join(':',@{$rules});
                   1469:             my $homeserver=&domain($udom,'primary');
                   1470:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1471:                 my $response;
                   1472:                 if ($item eq 'username') {                
                   1473:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1474:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1475:                                               $homeserver));
1.923     raeburn  1476:                 } elsif ($item eq 'id') {
                   1477:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1478:                                               ':'.&escape($id).':'.$rulestr,
                   1479:                                               $homeserver));
1.945     raeburn  1480:                 } elsif ($item eq 'selfcreate') {
                   1481:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1482:                                                &escape($udom).':'.&escape($uname).
                   1483:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1484:                 }
1.912     raeburn  1485:                 if ($response ne 'refused') {
                   1486:                     my @pairs=split(/\&/,$response);
                   1487:                     foreach my $item (@pairs) {
                   1488:                         my ($key,$value)=split(/=/,$item,2);
                   1489:                         $key = &unescape($key);
                   1490:                         next if ($key =~ /^error: 2 /);
                   1491:                         $returnhash{$key}=&thaw_unescape($value);
                   1492:                     }
                   1493:                 }
                   1494:             }
                   1495:         }
                   1496:     }
                   1497:     return %returnhash;
                   1498: }
                   1499: 
                   1500: sub inst_userrules {
1.923     raeburn  1501:     my ($udom,$check) = @_;
1.912     raeburn  1502:     my (%ruleshash,@ruleorder);
                   1503:     if ($udom ne '') {
                   1504:         my $homeserver=&domain($udom,'primary');
                   1505:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1506:             my $response;
                   1507:             if ($check eq 'id') {
                   1508:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1509:                                  $homeserver);
1.943     raeburn  1510:             } elsif ($check eq 'email') {
                   1511:                 $response=&reply('instemailrules:'.&escape($udom),
                   1512:                                  $homeserver);
1.923     raeburn  1513:             } else {
                   1514:                 $response=&reply('instuserrules:'.&escape($udom),
                   1515:                                  $homeserver);
                   1516:             }
1.912     raeburn  1517:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1518:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1519:                 ($response ne 'no_such_host')) {
                   1520:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1521:                 my @pairs=split(/\&/,$hashitems);
                   1522:                 foreach my $item (@pairs) {
                   1523:                     my ($key,$value)=split(/=/,$item,2);
                   1524:                     $key = &unescape($key);
                   1525:                     next if ($key =~ /^error: 2 /);
                   1526:                     $ruleshash{$key}=&thaw_unescape($value);
                   1527:                 }
                   1528:                 my @esc_order = split(/\&/,$orderitems);
                   1529:                 foreach my $item (@esc_order) {
                   1530:                     push(@ruleorder,&unescape($item));
                   1531:                 }
                   1532:             }
                   1533:         }
                   1534:     }
                   1535:     return (\%ruleshash,\@ruleorder);
                   1536: }
                   1537: 
1.976     raeburn  1538: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1539: 
                   1540: sub get_domain_defaults {
                   1541:     my ($domain) = @_;
                   1542:     my $cachetime = 60*60*24;
                   1543:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1544:     if (defined($cached)) {
                   1545:         if (ref($result) eq 'HASH') {
                   1546:             return %{$result};
                   1547:         }
                   1548:     }
                   1549:     my %domdefaults;
                   1550:     my %domconfig =
1.989     raeburn  1551:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1552:                                   'requestcourses','inststatus',
1.1073    raeburn  1553:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1554:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1555:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1556:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1557:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1558:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1559:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1560:     } else {
                   1561:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1562:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1563:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1564:     }
1.976     raeburn  1565:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1566:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1567:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1568:         } else {
                   1569:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1570:         } 
                   1571:         my @usertools = ('aboutme','blog','portfolio');
                   1572:         foreach my $item (@usertools) {
                   1573:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1574:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1575:             }
                   1576:         }
                   1577:     }
1.985     raeburn  1578:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1579:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1580:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1581:         }
                   1582:     }
1.989     raeburn  1583:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1584:         foreach my $item ('inststatustypes','inststatusorder') {
                   1585:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1586:         }
                   1587:     }
1.1047    raeburn  1588:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1589:         foreach my $item ('canuse_pdfforms') {
                   1590:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1591:         }
                   1592:     }
1.1073    raeburn  1593:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1594:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1595:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1596:         }
                   1597:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1598:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1599:         }
                   1600:     }
1.943     raeburn  1601:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1602:                                   $cachetime);
                   1603:     return %domdefaults;
                   1604: }
                   1605: 
1.344     www      1606: # --------------------------------------------------- Assign a key to a student
                   1607: 
                   1608: sub assign_access_key {
1.364     www      1609: #
                   1610: # a valid key looks like uname:udom#comments
                   1611: # comments are being appended
                   1612: #
1.498     www      1613:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1614:     $kdom=
1.620     albertel 1615:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1616:     $knum=
1.620     albertel 1617:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1618:     $cdom=
1.620     albertel 1619:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1620:     $cnum=
1.620     albertel 1621:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1622:     $udom=$env{'user.name'} unless (defined($udom));
                   1623:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1624:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1625:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1626:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1627:                                                   # assigned to this person
                   1628:                                                   # - this should not happen,
1.345     www      1629:                                                   # unless something went wrong
                   1630:                                                   # the first time around
                   1631: # ready to assign
1.364     www      1632:         $logentry=$1.'; '.$logentry;
1.496     www      1633:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1634:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1635: # key now belongs to user
1.346     www      1636: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1637:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1638:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1639:                 return 'ok';
                   1640:             } else {
                   1641:                 return 
                   1642:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1643: 	    }
                   1644:         } else {
                   1645:             return 'error: Could not assign key, try again later.';
                   1646:         }
1.364     www      1647:     } elsif (!$existing{$ckey}) {
1.345     www      1648: # the key does not exist
                   1649: 	return 'error: The key does not exist';
                   1650:     } else {
                   1651: # the key is somebody else's
                   1652: 	return 'error: The key is already in use';
                   1653:     }
1.344     www      1654: }
                   1655: 
1.364     www      1656: # ------------------------------------------ put an additional comment on a key
                   1657: 
                   1658: sub comment_access_key {
                   1659: #
                   1660: # a valid key looks like uname:udom#comments
                   1661: # comments are being appended
                   1662: #
                   1663:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1664:     $cdom=
1.620     albertel 1665:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1666:     $cnum=
1.620     albertel 1667:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1668:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1669:     if ($existing{$ckey}) {
                   1670:         $existing{$ckey}.='; '.$logentry;
                   1671: # ready to assign
1.367     www      1672:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1673:                                                  $cdom,$cnum) eq 'ok') {
                   1674: 	    return 'ok';
                   1675:         } else {
                   1676: 	    return 'error: Count not store comment.';
                   1677:         }
                   1678:     } else {
                   1679: # the key does not exist
                   1680: 	return 'error: The key does not exist';
                   1681:     }
                   1682: }
                   1683: 
1.344     www      1684: # ------------------------------------------------------ Generate a set of keys
                   1685: 
                   1686: sub generate_access_keys {
1.364     www      1687:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1688:     $cdom=
1.620     albertel 1689:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1690:     $cnum=
1.620     albertel 1691:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1692:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1693:     unless (($cdom) && ($cnum)) { return 0; }
                   1694:     if ($number>10000) { return 0; }
                   1695:     sleep(2); # make sure don't get same seed twice
                   1696:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1697:     my $total=0;
                   1698:     for (my $i=1;$i<=$number;$i++) {
                   1699:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1700:                   sprintf("%lx",int(100000*rand)).'-'.
                   1701:                   sprintf("%lx",int(100000*rand));
                   1702:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1703:        $newkey=~s/0/h/g; # and also 0 and O
                   1704:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1705:        if ($existing{$newkey}) {
                   1706:            $i--;
                   1707:        } else {
1.364     www      1708: 	  if (&put('accesskeys',
                   1709:               { $newkey => '# generated '.localtime().
1.620     albertel 1710:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1711:                            '; '.$logentry },
                   1712: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1713:               $total++;
                   1714: 	  }
                   1715:        }
                   1716:     }
1.620     albertel 1717:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1718:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1719:     return $total;
                   1720: }
                   1721: 
                   1722: # ------------------------------------------------------- Validate an accesskey
                   1723: 
                   1724: sub validate_access_key {
                   1725:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1726:     $cdom=
1.620     albertel 1727:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1728:     $cnum=
1.620     albertel 1729:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1730:     $udom=$env{'user.domain'} unless (defined($udom));
                   1731:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1732:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1733:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1734: }
                   1735: 
                   1736: # ------------------------------------- Find the section of student in a course
1.652     albertel 1737: sub devalidate_getsection_cache {
                   1738:     my ($udom,$unam,$courseid)=@_;
                   1739:     my $hashid="$udom:$unam:$courseid";
                   1740:     &devalidate_cache_new('getsection',$hashid);
                   1741: }
1.298     matthew  1742: 
1.815     albertel 1743: sub courseid_to_courseurl {
                   1744:     my ($courseid) = @_;
                   1745:     #already url style courseid
                   1746:     return $courseid if ($courseid =~ m{^/});
                   1747: 
                   1748:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1749: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1750: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1751: 	return "/$cdom/$cnum";
                   1752:     }
                   1753: 
                   1754:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1755:     if (exists($courseinfo{'num'})) {
                   1756: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1757:     }
                   1758: 
                   1759:     return undef;
                   1760: }
                   1761: 
1.298     matthew  1762: sub getsection {
                   1763:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1764:     my $cachetime=1800;
1.551     albertel 1765: 
                   1766:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1767:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1768:     if (defined($cached)) { return $result; }
                   1769: 
1.298     matthew  1770:     my %Pending; 
                   1771:     my %Expired;
                   1772:     #
                   1773:     # Each role can either have not started yet (pending), be active, 
                   1774:     #    or have expired.
                   1775:     #
                   1776:     # If there is an active role, we are done.
                   1777:     #
                   1778:     # If there is more than one role which has not started yet, 
                   1779:     #     choose the one which will start sooner
                   1780:     # If there is one role which has not started yet, return it.
                   1781:     #
                   1782:     # If there is more than one expired role, choose the one which ended last.
                   1783:     # If there is a role which has expired, return it.
                   1784:     #
1.815     albertel 1785:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1786:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1787:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1788:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1789:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1790:         my $section=$1;
                   1791:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1792:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1793:         my $now=time;
1.548     albertel 1794:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1795:             $Expired{$end}=$section;
                   1796:             next;
                   1797:         }
1.548     albertel 1798:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1799:             $Pending{$start}=$section;
                   1800:             next;
                   1801:         }
1.599     albertel 1802:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1803:     }
                   1804:     #
                   1805:     # Presumedly there will be few matching roles from the above
                   1806:     # loop and the sorting time will be negligible.
                   1807:     if (scalar(keys(%Pending))) {
                   1808:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1809:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1810:     } 
                   1811:     if (scalar(keys(%Expired))) {
                   1812:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1813:         my $time = pop(@sorted);
1.599     albertel 1814:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1815:     }
1.599     albertel 1816:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1817: }
1.70      www      1818: 
1.599     albertel 1819: sub save_cache {
                   1820:     &purge_remembered();
1.722     albertel 1821:     #&Apache::loncommon::validate_page();
1.620     albertel 1822:     undef(%env);
1.780     albertel 1823:     undef($env_loaded);
1.599     albertel 1824: }
1.452     albertel 1825: 
1.599     albertel 1826: my $to_remember=-1;
                   1827: my %remembered;
                   1828: my %accessed;
                   1829: my $kicks=0;
                   1830: my $hits=0;
1.849     albertel 1831: sub make_key {
                   1832:     my ($name,$id) = @_;
1.872     albertel 1833:     if (length($id) > 65 
                   1834: 	&& length(&escape($id)) > 200) {
                   1835: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1836:     }
1.849     albertel 1837:     return &escape($name.':'.$id);
                   1838: }
                   1839: 
1.599     albertel 1840: sub devalidate_cache_new {
                   1841:     my ($name,$id,$debug) = @_;
                   1842:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1843:     $id=&make_key($name,$id);
1.599     albertel 1844:     $memcache->delete($id);
                   1845:     delete($remembered{$id});
                   1846:     delete($accessed{$id});
                   1847: }
                   1848: 
                   1849: sub is_cached_new {
                   1850:     my ($name,$id,$debug) = @_;
1.849     albertel 1851:     $id=&make_key($name,$id);
1.599     albertel 1852:     if (exists($remembered{$id})) {
                   1853: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1854: 	$accessed{$id}=[&gettimeofday()];
                   1855: 	$hits++;
                   1856: 	return ($remembered{$id},1);
                   1857:     }
                   1858:     my $value = $memcache->get($id);
                   1859:     if (!(defined($value))) {
                   1860: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1861: 	return (undef,undef);
1.416     albertel 1862:     }
1.599     albertel 1863:     if ($value eq '__undef__') {
                   1864: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1865: 	$value=undef;
                   1866:     }
                   1867:     &make_room($id,$value,$debug);
                   1868:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1869:     return ($value,1);
                   1870: }
                   1871: 
                   1872: sub do_cache_new {
                   1873:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1874:     $id=&make_key($name,$id);
1.599     albertel 1875:     my $setvalue=$value;
                   1876:     if (!defined($setvalue)) {
                   1877: 	$setvalue='__undef__';
                   1878:     }
1.623     albertel 1879:     if (!defined($time) ) {
                   1880: 	$time=600;
                   1881:     }
1.599     albertel 1882:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1883:     my $result = $memcache->set($id,$setvalue,$time);
                   1884:     if (! $result) {
1.872     albertel 1885: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1886: 	$memcache->disconnect_all();
1.872     albertel 1887:     }
1.600     albertel 1888:     # need to make a copy of $value
1.919     albertel 1889:     &make_room($id,$value,$debug);
1.599     albertel 1890:     return $value;
                   1891: }
                   1892: 
                   1893: sub make_room {
                   1894:     my ($id,$value,$debug)=@_;
1.919     albertel 1895: 
                   1896:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1897:                                     : $value;
1.599     albertel 1898:     if ($to_remember<0) { return; }
                   1899:     $accessed{$id}=[&gettimeofday()];
                   1900:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1901:     my $to_kick;
                   1902:     my $max_time=0;
                   1903:     foreach my $other (keys(%accessed)) {
                   1904: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1905: 	    $to_kick=$other;
                   1906: 	    $max_time=&tv_interval($accessed{$other});
                   1907: 	}
                   1908:     }
                   1909:     delete($remembered{$to_kick});
                   1910:     delete($accessed{$to_kick});
                   1911:     $kicks++;
                   1912:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1913:     return;
                   1914: }
                   1915: 
1.599     albertel 1916: sub purge_remembered {
1.604     albertel 1917:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1918:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1919:     undef(%remembered);
                   1920:     undef(%accessed);
1.428     albertel 1921: }
1.70      www      1922: # ------------------------------------- Read an entry from a user's environment
                   1923: 
                   1924: sub userenvironment {
                   1925:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1926:     my $items;
                   1927:     foreach my $item (@what) {
                   1928:         $items.=&escape($item).'&';
                   1929:     }
                   1930:     $items=~s/\&$//;
1.70      www      1931:     my %returnhash=();
1.1009    raeburn  1932:     my $uhome = &homeserver($unam,$udom);
                   1933:     unless ($uhome eq 'no_host') {
                   1934:         my @answer=split(/\&/, 
                   1935:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1936:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1937:             return %returnhash;
                   1938:         }
1.1009    raeburn  1939:         my $i;
                   1940:         for ($i=0;$i<=$#what;$i++) {
                   1941: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1942:         }
1.70      www      1943:     }
                   1944:     return %returnhash;
1.1       albertel 1945: }
                   1946: 
1.617     albertel 1947: # ---------------------------------------------------------- Get a studentphoto
                   1948: sub studentphoto {
                   1949:     my ($udom,$unam,$ext) = @_;
                   1950:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1951:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1952:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1953:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1954:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1955:             } else {
                   1956:                 my ($result,$perm_reqd)=
1.707     albertel 1957: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1958:                 if ($result eq 'ok') {
                   1959:                     if (!($perm_reqd eq 'yes')) {
                   1960:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1961:                     }
                   1962:                 }
                   1963:             }
                   1964:         }
                   1965:     } else {
                   1966:         my ($result,$perm_reqd) = 
1.707     albertel 1967: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1968:         if ($result eq 'ok') {
                   1969:             if (!($perm_reqd eq 'yes')) {
                   1970:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1971:             }
                   1972:         }
                   1973:     }
                   1974:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1975: }
                   1976: 
                   1977: sub retrievestudentphoto {
                   1978:     my ($udom,$unam,$ext,$type) = @_;
                   1979:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1980:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1981:     if ($ret eq 'ok') {
                   1982:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1983:         if ($type eq 'thumbnail') {
                   1984:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1985:         }
                   1986:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1987:         return $tokenurl;
                   1988:     } else {
                   1989:         if ($type eq 'thumbnail') {
                   1990:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1991:         } else { 
                   1992:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1993:         }
1.617     albertel 1994:     }
                   1995: }
                   1996: 
1.263     www      1997: # -------------------------------------------------------------------- New chat
                   1998: 
                   1999: sub chatsend {
1.724     raeburn  2000:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2001:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2002:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2003:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2004:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2005: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2006: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2007: }
                   2008: 
                   2009: # ------------------------------------------ Find current version of a resource
                   2010: 
                   2011: sub getversion {
                   2012:     my $fname=&clutter(shift);
                   2013:     unless ($fname=~/^\/res\//) { return -1; }
                   2014:     return &currentversion(&filelocation('',$fname));
                   2015: }
                   2016: 
                   2017: sub currentversion {
                   2018:     my $fname=shift;
                   2019:     my $author=$fname;
                   2020:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2021:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2022:     my $home=&homeserver($uname,$udom);
1.292     www      2023:     if ($home eq 'no_host') { 
                   2024:         return -1; 
                   2025:     }
1.1112    www      2026:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2027:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2028: 	return -1;
                   2029:     }
1.1112    www      2030:     return $answer;
1.263     www      2031: }
                   2032: 
1.1111    www      2033: #
                   2034: # Return special version number of resource if set by override, empty otherwise
                   2035: #
                   2036: sub usedversion {
                   2037:     my $fname=shift;
                   2038:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2039:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2040:     if ($urlversion) { return $urlversion; }
                   2041:     return '';
                   2042: }
                   2043: 
1.1       albertel 2044: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2045: 
1.1       albertel 2046: sub subscribe {
                   2047:     my $fname=shift;
1.761     raeburn  2048:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2049:     $fname=~s/[\n\r]//g;
1.1       albertel 2050:     my $author=$fname;
                   2051:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2052:     my ($udom,$uname)=split(/\//,$author);
                   2053:     my $home=homeserver($uname,$udom);
1.335     albertel 2054:     if ($home eq 'no_host') {
                   2055:         return 'not_found';
1.1       albertel 2056:     }
                   2057:     my $answer=reply("sub:$fname",$home);
1.64      www      2058:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2059: 	$answer.=' by '.$home;
                   2060:     }
1.1       albertel 2061:     return $answer;
                   2062: }
                   2063:     
1.8       www      2064: # -------------------------------------------------------------- Replicate file
                   2065: 
                   2066: sub repcopy {
                   2067:     my $filename=shift;
1.23      www      2068:     $filename=~s/\/+/\//g;
1.607     raeburn  2069:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2070:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2071:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2072: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2073: 	return &repcopy_userfile($filename);
                   2074:     }
1.532     albertel 2075:     $filename=~s/[\n\r]//g;
1.8       www      2076:     my $transname="$filename.in.transfer";
1.828     www      2077: # FIXME: this should flock
1.607     raeburn  2078:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2079:     my $remoteurl=subscribe($filename);
1.64      www      2080:     if ($remoteurl =~ /^con_lost by/) {
                   2081: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2082:            return 'unavailable';
1.8       www      2083:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2084: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2085: 	   return 'not_found';
1.64      www      2086:     } elsif ($remoteurl =~ /^rejected by/) {
                   2087: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2088:            return 'forbidden';
1.20      www      2089:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2090:            return 'ok';
1.8       www      2091:     } else {
1.290     www      2092:         my $author=$filename;
                   2093:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2094:         my ($udom,$uname)=split(/\//,$author);
                   2095:         my $home=homeserver($uname,$udom);
                   2096:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2097:            my @parts=split(/\//,$filename);
                   2098:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2099:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2100:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2101: 	       return 'bad_request';
1.8       www      2102:            }
                   2103:            my $count;
                   2104:            for ($count=5;$count<$#parts;$count++) {
                   2105:                $path.="/$parts[$count]";
                   2106:                if ((-e $path)!=1) {
                   2107: 		   mkdir($path,0777);
                   2108:                }
                   2109:            }
                   2110:            my $ua=new LWP::UserAgent;
                   2111:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2112:            my $response=$ua->request($request,$transname);
                   2113:            if ($response->is_error()) {
                   2114: 	       unlink($transname);
                   2115:                my $message=$response->status_line;
1.672     albertel 2116:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2117:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2118:                return 'unavailable';
1.8       www      2119:            } else {
1.16      www      2120: 	       if ($remoteurl!~/\.meta$/) {
                   2121:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2122:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2123:                   if ($mresponse->is_error()) {
                   2124: 		      unlink($filename.'.meta');
                   2125:                       &logthis(
1.672     albertel 2126:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2127:                   }
                   2128: 	       }
1.8       www      2129:                rename($transname,$filename);
1.607     raeburn  2130:                return 'ok';
1.8       www      2131:            }
1.290     www      2132:        }
1.8       www      2133:     }
1.330     www      2134: }
                   2135: 
                   2136: # ------------------------------------------------ Get server side include body
                   2137: sub ssi_body {
1.381     albertel 2138:     my ($filelink,%form)=@_;
1.606     matthew  2139:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2140:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2141:     }
1.953     www      2142:     my $output='';
                   2143:     my $response;
1.980     raeburn  2144:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2145:        ($output,$response)=&externalssi($filelink);
1.953     www      2146:     } else {
1.1004    droeschl 2147:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2148:        $filelink .= 'inhibitmenu=yes';
1.953     www      2149:        ($output,$response)=&ssi($filelink,%form);
                   2150:     }
1.778     albertel 2151:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2152:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2153:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2154:     if (wantarray) {
                   2155:         return ($output, $response);
                   2156:     } else {
                   2157:         return $output;
                   2158:     }
1.8       www      2159: }
                   2160: 
1.15      www      2161: # --------------------------------------------------------- Server Side Include
                   2162: 
1.782     albertel 2163: sub absolute_url {
                   2164:     my ($host_name) = @_;
                   2165:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2166:     if ($host_name eq '') {
                   2167: 	$host_name = $ENV{'SERVER_NAME'};
                   2168:     }
                   2169:     return $protocol.$host_name;
                   2170: }
                   2171: 
1.942     foxr     2172: #
                   2173: #   Server side include.
                   2174: # Parameters:
                   2175: #  fn     Possibly encrypted resource name/id.
                   2176: #  form   Hash that describes how the rendering should be done
                   2177: #         and other things.
1.944     foxr     2178: # Returns:
1.950     raeburn  2179: #   Scalar context: The content of the response.
                   2180: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2181: #     
1.15      www      2182: sub ssi {
                   2183: 
1.944     foxr     2184:     my ($fn,%form)=@_;
1.15      www      2185:     my $ua=new LWP::UserAgent;
1.23      www      2186:     my $request;
1.711     albertel 2187: 
                   2188:     $form{'no_update_last_known'}=1;
1.895     albertel 2189:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2190:     if (%form) {
1.782     albertel 2191:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2192:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2193:     } else {
1.782     albertel 2194:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2195:     }
                   2196: 
1.15      www      2197:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2198:     my $response=$ua->request($request);
                   2199: 
1.944     foxr     2200:     if (wantarray) {
                   2201: 	return ($response->content, $response);
                   2202:     } else {
                   2203: 	return $response->content;
1.942     foxr     2204:     }
1.324     www      2205: }
                   2206: 
                   2207: sub externalssi {
                   2208:     my ($url)=@_;
                   2209:     my $ua=new LWP::UserAgent;
                   2210:     my $request=new HTTP::Request('GET',$url);
                   2211:     my $response=$ua->request($request);
1.954     raeburn  2212:     if (wantarray) {
                   2213:         return ($response->content, $response);
                   2214:     } else {
                   2215:         return $response->content;
                   2216:     }
1.15      www      2217: }
1.254     www      2218: 
1.492     albertel 2219: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2220: 
                   2221: sub allowuploaded {
                   2222:     my ($srcurl,$url)=@_;
                   2223:     $url=&clutter(&declutter($url));
                   2224:     my $dir=$url;
                   2225:     $dir=~s/\/[^\/]+$//;
                   2226:     my %httpref=();
                   2227:     my $httpurl=&hreflocation('',$url);
                   2228:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2229:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2230: }
1.477     raeburn  2231: 
1.478     albertel 2232: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2233: # input: action, courseID, current domain, intended
1.637     raeburn  2234: #        path to file, source of file, instruction to parse file for objects,
                   2235: #        ref to hash for embedded objects,
                   2236: #        ref to hash for codebase of java objects.
1.1095    raeburn  2237: #        reference to scalar to accommodate mime type determined
                   2238: #          from File::MMagic if $parser = parse.
1.637     raeburn  2239: #
1.485     raeburn  2240: # output: url to file (if action was uploaddoc), 
                   2241: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2242: #
1.478     albertel 2243: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2244: # course.
1.477     raeburn  2245: #
1.478     albertel 2246: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2247: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2248: #          course's home server.
1.477     raeburn  2249: #
1.478     albertel 2250: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2251: #          be copied from $source (current location) to 
                   2252: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2253: #         and will then be copied to
                   2254: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2255: #         course's home server.
1.485     raeburn  2256: #
1.481     raeburn  2257: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2258: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2259: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2260: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2261: #         in course's home server.
1.637     raeburn  2262: #
1.477     raeburn  2263: 
                   2264: sub process_coursefile {
1.1095    raeburn  2265:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2266:         $mimetype)=@_;
1.477     raeburn  2267:     my $fetchresult;
1.638     albertel 2268:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2269:     if ($action eq 'propagate') {
1.638     albertel 2270:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2271: 			     $home);
1.481     raeburn  2272:     } else {
1.477     raeburn  2273:         my $fpath = '';
                   2274:         my $fname = $file;
1.478     albertel 2275:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2276:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2277:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2278:         if ($action eq 'copy') {
                   2279:             if ($source eq '') {
                   2280:                 $fetchresult = 'no source file';
                   2281:                 return $fetchresult;
                   2282:             } else {
                   2283:                 my $destination = $filepath.'/'.$fname;
                   2284:                 rename($source,$destination);
                   2285:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2286:                                  $home);
1.481     raeburn  2287:             }
                   2288:         } elsif ($action eq 'uploaddoc') {
                   2289:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2290:             print $fh $env{'form.'.$source};
1.481     raeburn  2291:             close($fh);
1.637     raeburn  2292:             if ($parser eq 'parse') {
1.1024    raeburn  2293:                 my $mm = new File::MMagic;
1.1095    raeburn  2294:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2295:                 if ($type eq 'text/html') {
1.1024    raeburn  2296:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2297:                     unless ($parse_result eq 'ok') {
                   2298:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2299:                     }
1.637     raeburn  2300:                 }
1.1095    raeburn  2301:                 if (ref($mimetype)) {
                   2302:                     $$mimetype = $type;
                   2303:                 } 
1.637     raeburn  2304:             }
1.477     raeburn  2305:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2306:                                  $home);
1.481     raeburn  2307:             if ($fetchresult eq 'ok') {
                   2308:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2309:             } else {
                   2310:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2311:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2312:                 return '/adm/notfound.html';
                   2313:             }
1.477     raeburn  2314:         }
                   2315:     }
1.485     raeburn  2316:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2317:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2318:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2319:     }
                   2320:     return $fetchresult;
                   2321: }
                   2322: 
1.637     raeburn  2323: sub build_filepath {
                   2324:     my ($fpath) = @_;
                   2325:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2326:     unless ($fpath eq '') {
                   2327:         my @parts=split('/',$fpath);
                   2328:         foreach my $part (@parts) {
                   2329:             $filepath.= '/'.$part;
                   2330:             if ((-e $filepath)!=1) {
                   2331:                 mkdir($filepath,0777);
                   2332:             }
                   2333:         }
                   2334:     }
                   2335:     return $filepath;
                   2336: }
                   2337: 
                   2338: sub store_edited_file {
1.638     albertel 2339:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2340:     my $file = $primary_url;
                   2341:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2342:     my $fpath = '';
                   2343:     my $fname = $file;
                   2344:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2345:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2346:     my $filepath = &build_filepath($fpath);
                   2347:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2348:     print $fh $content;
                   2349:     close($fh);
1.638     albertel 2350:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2351:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2352: 			  $home);
1.637     raeburn  2353:     if ($$fetchresult eq 'ok') {
                   2354:         return '/uploaded/'.$fpath.'/'.$fname;
                   2355:     } else {
1.638     albertel 2356:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2357: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2358:         return '/adm/notfound.html';
                   2359:     }
                   2360: }
                   2361: 
1.531     albertel 2362: sub clean_filename {
1.831     albertel 2363:     my ($fname,$args)=@_;
1.315     www      2364: # Replace Windows backslashes by forward slashes
1.257     www      2365:     $fname=~s/\\/\//g;
1.831     albertel 2366:     if (!$args->{'keep_path'}) {
                   2367:         # Get rid of everything but the actual filename
                   2368: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2369:     }
1.315     www      2370: # Replace spaces by underscores
                   2371:     $fname=~s/\s+/\_/g;
                   2372: # Replace all other weird characters by nothing
1.831     albertel 2373:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2374: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2375: # numbers
                   2376:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2377:     return $fname;
                   2378: }
1.1051    raeburn  2379: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2380: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2381: # image with the same aspect ratio as the original, but with dimensions which do 
                   2382: # not exceed $resizewidth and $resizeheight.
                   2383:  
1.984     neumanie 2384: sub resizeImage {
1.1051    raeburn  2385:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2386:     my $ima = Image::Magick->new;
                   2387:     my $resized;
                   2388:     if (-e $img_path) {
                   2389:         $ima->Read($img_path);
                   2390:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2391:             my $width = $ima->Get('width');
                   2392:             my $height = $ima->Get('height');
                   2393:             if ($width > $resizewidth) {
                   2394: 	        my $factor = $width/$resizewidth;
                   2395:                 my $newheight = $height/$factor;
                   2396:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2397:                 $resized = 1;
                   2398:             }
                   2399:         }
                   2400:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2401:             my $width = $ima->Get('width');
                   2402:             my $height = $ima->Get('height');
                   2403:             if ($height > $resizeheight) {
                   2404:                 my $factor = $height/$resizeheight;
                   2405:                 my $newwidth = $width/$factor;
                   2406:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2407:                 $resized = 1;
                   2408:             }
                   2409:         }
                   2410:         if ($resized) {
                   2411:             $ima->Write($img_path);
                   2412:         }
                   2413:     }
                   2414:     return;
1.977     amueller 2415: }
                   2416: 
1.608     albertel 2417: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2418: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2419: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2420: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2421: #                                    canceloverwrite, or ''. 
                   2422: #                   if 'coursedoc': upload to the current course
                   2423: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2424: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2425: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2426: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2427: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2428: #        $allfiles - reference to hash for embedded objects
                   2429: #        $codebase - reference to hash for codebase of java objects
                   2430: #        $desuname - username for permanent storage of uploaded file
                   2431: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2432: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2433: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2434: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2435: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2436: #        $mimetype - reference to scalar to accommodate mime type determined
                   2437: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2438: # 
1.686     albertel 2439: # output: url of file in userspace, or error: <message> 
                   2440: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2441: 
1.531     albertel 2442: sub userfileupload {
1.1090    raeburn  2443:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2444:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2445:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2446:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2447:     $fname=&clean_filename($fname);
1.1090    raeburn  2448:     # See if there is anything left
1.257     www      2449:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2450:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2451:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2452:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2453:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2454:         my $now = time;
1.1090    raeburn  2455:         my $filepath;
1.1095    raeburn  2456:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2457:              $filepath = 'tmp/helprequests/'.$now;
                   2458:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2459:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2460:                          '_'.$env{'user.domain'}.'/pending';
                   2461:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2462:             my ($docuname,$docudom);
                   2463:             if ($destudom) {
                   2464:                 $docudom = $destudom;
                   2465:             } else {
                   2466:                 $docudom = $env{'user.domain'};
                   2467:             }
                   2468:             if ($destuname) {
                   2469:                 $docuname = $destuname;
                   2470:             } else {
                   2471:                 $docuname = $env{'user.name'};
                   2472:             }
                   2473:             if (exists($env{'form.group'})) {
                   2474:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2475:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2476:             }
                   2477:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2478:             if ($context eq 'canceloverwrite') {
                   2479:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2480:                 if (-e  $tempfile) {
                   2481:                     my @info = stat($tempfile);
                   2482:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2483:                         unlink($tempfile);
                   2484:                     }
                   2485:                 }
                   2486:                 return;
1.523     raeburn  2487:             }
                   2488:         }
1.1090    raeburn  2489:         # Create the directory if not present
1.741     raeburn  2490:         my @parts=split(/\//,$filepath);
                   2491:         my $fullpath = $perlvar{'lonDaemons'};
                   2492:         for (my $i=0;$i<@parts;$i++) {
                   2493:             $fullpath .= '/'.$parts[$i];
                   2494:             if ((-e $fullpath)!=1) {
                   2495:                 mkdir($fullpath,0777);
                   2496:             }
                   2497:         }
                   2498:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2499:         print $fh $env{'form.'.$formname};
                   2500:         close($fh);
1.1090    raeburn  2501:         if ($context eq 'existingfile') {
                   2502:             my @info = stat($fullpath.'/'.$fname);
                   2503:             return ($fullpath.'/'.$fname,$info[9]);
                   2504:         } else {
                   2505:             return $fullpath.'/'.$fname;
                   2506:         }
1.523     raeburn  2507:     }
1.995     raeburn  2508:     if ($subdir eq 'scantron') {
                   2509:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2510:     } else {
1.995     raeburn  2511:         $fname="$subdir/$fname";
                   2512:     }
1.1090    raeburn  2513:     if ($context eq 'coursedoc') {
1.638     albertel 2514: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2515: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2516:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2517:             return &finishuserfileupload($docuname,$docudom,
                   2518: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2519: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2520:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2521:         } else {
1.620     albertel 2522:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2523:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2524: 				       $fname,$formname,$parser,
1.1095    raeburn  2525: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2526:         }
1.719     banghart 2527:     } elsif (defined($destuname)) {
                   2528:         my $docuname=$destuname;
                   2529:         my $docudom=$destudom;
1.860     raeburn  2530: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2531: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2532:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2533:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2534:     } else {
1.638     albertel 2535:         my $docuname=$env{'user.name'};
                   2536:         my $docudom=$env{'user.domain'};
1.714     raeburn  2537:         if (exists($env{'form.group'})) {
                   2538:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2539:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2540:         }
1.860     raeburn  2541: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2542: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2543:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2544:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2545:     }
1.271     www      2546: }
                   2547: 
                   2548: sub finishuserfileupload {
1.860     raeburn  2549:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2550:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2551:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2552:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2553:   
1.860     raeburn  2554:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2555:     $file=$fname;
                   2556:     if ($fname=~m|/|) {
                   2557:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2558: 	$path.=$fnamepath.'/';
                   2559:     }
1.259     www      2560:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2561:     my $count;
                   2562:     for ($count=4;$count<=$#parts;$count++) {
                   2563:         $filepath.="/$parts[$count]";
                   2564:         if ((-e $filepath)!=1) {
                   2565: 	    mkdir($filepath,0777);
                   2566:         }
                   2567:     }
1.984     neumanie 2568: 
1.258     www      2569: # Save the file
                   2570:     {
1.701     albertel 2571: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2572: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2573: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2574: 	    return '/adm/notfound.html';
                   2575: 	}
1.1090    raeburn  2576:         if ($context eq 'overwrite') {
1.1117    foxr     2577:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2578:             my $target = $filepath.'/'.$file;
                   2579:             if (-e $source) {
                   2580:                 my @info = stat($source);
                   2581:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2582:                     unless (&File::Copy::move($source,$target)) {
                   2583:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2584:                         return "Moving from $source failed";
                   2585:                     }
                   2586:                 } else {
                   2587:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2588:                 }
                   2589:             } else {
                   2590:                 return "Temporary file: $source missing";
                   2591:             }
                   2592:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2593: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2594: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2595: 	    return '/adm/notfound.html';
                   2596: 	}
1.570     albertel 2597: 	close(FH);
1.1051    raeburn  2598:         if ($resizewidth && $resizeheight) {
                   2599:             my $mm = new File::MMagic;
                   2600:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2601:             if ($mime_type =~ m{^image/}) {
                   2602: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2603:             }  
1.977     amueller 2604: 	}
1.258     www      2605:     }
1.637     raeburn  2606:     if ($parser eq 'parse') {
1.1024    raeburn  2607:         my $mm = new File::MMagic;
1.1095    raeburn  2608:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2609:         if ($type eq 'text/html') {
1.1024    raeburn  2610:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2611:                                                        $allfiles,$codebase);
                   2612:             unless ($parse_result eq 'ok') {
                   2613:                 &logthis('Failed to parse '.$filepath.$file.
                   2614: 	   	         ' for embedded media: '.$parse_result); 
                   2615:             }
1.637     raeburn  2616:         }
1.1095    raeburn  2617:         if (ref($mimetype)) {
                   2618:             $$mimetype = $type;
                   2619:         }
1.637     raeburn  2620:     }
1.860     raeburn  2621:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2622:         my $input = $filepath.'/'.$file;
                   2623:         my $output = $filepath.'/'.'tn-'.$file;
                   2624:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2625:         system("convert -sample $thumbsize $input $output");
                   2626:         if (-e $filepath.'/'.'tn-'.$file) {
                   2627:             $fetchthumb  = 1; 
                   2628:         }
                   2629:     }
1.858     raeburn  2630:  
1.259     www      2631: # Notify homeserver to grep it
                   2632: #
1.984     neumanie 2633:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2634:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2635:     if ($fetchresult eq 'ok') {
1.860     raeburn  2636:         if ($fetchthumb) {
                   2637:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2638:             if ($thumbresult ne 'ok') {
                   2639:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2640:                          $docuhome.': '.$thumbresult);
                   2641:             }
                   2642:         }
1.259     www      2643: #
1.258     www      2644: # Return the URL to it
1.494     albertel 2645:         return '/uploaded/'.$path.$file;
1.263     www      2646:     } else {
1.494     albertel 2647:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2648: 		 ': '.$fetchresult);
1.263     www      2649:         return '/adm/notfound.html';
1.858     raeburn  2650:     }
1.493     albertel 2651: }
                   2652: 
1.637     raeburn  2653: sub extract_embedded_items {
1.961     raeburn  2654:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2655:     my @state = ();
                   2656:     my %javafiles = (
                   2657:                       codebase => '',
                   2658:                       code => '',
                   2659:                       archive => ''
                   2660:                     );
                   2661:     my %mediafiles = (
                   2662:                       src => '',
                   2663:                       movie => '',
                   2664:                      );
1.648     raeburn  2665:     my $p;
                   2666:     if ($content) {
                   2667:         $p = HTML::LCParser->new($content);
                   2668:     } else {
1.961     raeburn  2669:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2670:     }
1.641     albertel 2671:     while (my $t=$p->get_token()) {
1.640     albertel 2672: 	if ($t->[0] eq 'S') {
                   2673: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2674: 	    push(@state, $tagname);
1.648     raeburn  2675:             if (lc($tagname) eq 'allow') {
                   2676:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2677:             }
1.640     albertel 2678: 	    if (lc($tagname) eq 'img') {
                   2679: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2680: 	    }
1.886     albertel 2681: 	    if (lc($tagname) eq 'a') {
                   2682: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2683: 	    }
1.645     raeburn  2684:             if (lc($tagname) eq 'script') {
                   2685:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2686:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2687:                 } else {
                   2688:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2689:                 }
                   2690:             }
                   2691:             if (lc($tagname) eq 'link') {
                   2692:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2693:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2694:                 }
                   2695:             }
1.640     albertel 2696: 	    if (lc($tagname) eq 'object' ||
                   2697: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2698: 		foreach my $item (keys(%javafiles)) {
                   2699: 		    $javafiles{$item} = '';
                   2700: 		}
                   2701: 	    }
                   2702: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2703: 		my $name = lc($attr->{'name'});
                   2704: 		foreach my $item (keys(%javafiles)) {
                   2705: 		    if ($name eq $item) {
                   2706: 			$javafiles{$item} = $attr->{'value'};
                   2707: 			last;
                   2708: 		    }
                   2709: 		}
                   2710: 		foreach my $item (keys(%mediafiles)) {
                   2711: 		    if ($name eq $item) {
                   2712: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2713: 			last;
                   2714: 		    }
                   2715: 		}
                   2716: 	    }
                   2717: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2718: 		foreach my $item (keys(%javafiles)) {
                   2719: 		    if ($attr->{$item}) {
                   2720: 			$javafiles{$item} = $attr->{$item};
                   2721: 			last;
                   2722: 		    }
                   2723: 		}
                   2724: 		foreach my $item (keys(%mediafiles)) {
                   2725: 		    if ($attr->{$item}) {
                   2726: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2727: 			last;
                   2728: 		    }
                   2729: 		}
                   2730: 	    }
                   2731: 	} elsif ($t->[0] eq 'E') {
                   2732: 	    my ($tagname) = ($t->[1]);
                   2733: 	    if ($javafiles{'codebase'} ne '') {
                   2734: 		$javafiles{'codebase'} .= '/';
                   2735: 	    }  
                   2736: 	    if (lc($tagname) eq 'applet' ||
                   2737: 		lc($tagname) eq 'object' ||
                   2738: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2739: 		) {
                   2740: 		foreach my $item (keys(%javafiles)) {
                   2741: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2742: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2743: 			&add_filetype($allfiles,$file,$item);
                   2744: 		    }
                   2745: 		}
                   2746: 	    } 
                   2747: 	    pop @state;
                   2748: 	}
                   2749:     }
1.637     raeburn  2750:     return 'ok';
                   2751: }
                   2752: 
1.639     albertel 2753: sub add_filetype {
                   2754:     my ($allfiles,$file,$type)=@_;
                   2755:     if (exists($allfiles->{$file})) {
                   2756: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2757: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2758: 	}
                   2759:     } else {
                   2760: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2761:     }
                   2762: }
                   2763: 
1.493     albertel 2764: sub removeuploadedurl {
1.984     neumanie 2765:     my ($url)=@_;	
                   2766:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2767:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2768: }
                   2769: 
                   2770: sub removeuserfile {
                   2771:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2772:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2773:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2774:     if ($result eq 'ok') {	
1.798     raeburn  2775:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2776:             my $metafile = $fname.'.meta';
                   2777:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2778: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2779:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2780:             my $sqlresult = 
1.823     albertel 2781:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2782:                                         'portfolio_metadata',$group,
                   2783:                                         'delete');
1.798     raeburn  2784:         }
                   2785:     }
                   2786:     return $result;
1.257     www      2787: }
1.15      www      2788: 
1.530     albertel 2789: sub mkdiruserfile {
                   2790:     my ($docuname,$docudom,$dir)=@_;
                   2791:     my $home=&homeserver($docuname,$docudom);
                   2792:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2793: }
                   2794: 
1.531     albertel 2795: sub renameuserfile {
                   2796:     my ($docuname,$docudom,$old,$new)=@_;
                   2797:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2798:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2799:                         &escape("$old").':'.&escape("$new"),$home);
                   2800:     if ($result eq 'ok') {
                   2801:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2802:             my $oldmeta = $old.'.meta';
                   2803:             my $newmeta = $new.'.meta';
                   2804:             my $metaresult = 
                   2805:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2806: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2807:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2808:             my $sqlresult = 
1.823     albertel 2809:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2810:                                         'portfolio_metadata',$group,
                   2811:                                         'delete');
1.798     raeburn  2812:         }
                   2813:     }
                   2814:     return $result;
1.531     albertel 2815: }
                   2816: 
1.14      www      2817: # ------------------------------------------------------------------------- Log
                   2818: 
                   2819: sub log {
                   2820:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2821:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2822: }
                   2823: 
                   2824: # ------------------------------------------------------------------ Course Log
1.352     www      2825: #
                   2826: # This routine flushes several buffers of non-mission-critical nature
                   2827: #
1.157     www      2828: 
                   2829: sub flushcourselogs {
1.352     www      2830:     &logthis('Flushing log buffers');
                   2831: #
                   2832: # course logs
                   2833: # This is a log of all transactions in a course, which can be used
                   2834: # for data mining purposes
                   2835: #
                   2836: # It also collects the courseid database, which lists last transaction
                   2837: # times and course titles for all courseids
                   2838: #
                   2839:     my %courseidbuffer=();
1.921     raeburn  2840:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2841:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2842: 		          &escape($courselogs{$crsid}),
                   2843: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2844: 	    delete $courselogs{$crsid};
                   2845:         } else {
                   2846:             &logthis('Failed to flush log buffer for '.$crsid);
                   2847:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2848:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2849:                         " exceeded maximum size, deleting.</font>");
                   2850:                delete $courselogs{$crsid};
                   2851:             }
1.352     www      2852:         }
1.920     raeburn  2853:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2854:             'description' => $coursedescrbuf{$crsid},
                   2855:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2856:             'type'        => $coursetypebuf{$crsid},
                   2857:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2858:         };
1.191     harris41 2859:     }
1.352     www      2860: #
                   2861: # Write course id database (reverse lookup) to homeserver of courses 
                   2862: # Is used in pickcourse
                   2863: #
1.840     albertel 2864:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2865:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2866:                                     $courseidbuffer{$crs_home},
                   2867:                                     $crs_home,'timeonly');
1.352     www      2868:     }
                   2869: #
                   2870: # File accesses
                   2871: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2872: #
1.449     matthew  2873:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2874:         if ($entry =~ /___count$/) {
                   2875:             my ($dom,$name);
1.807     albertel 2876:             ($dom,$name,undef)=
1.811     albertel 2877: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2878:             if (! defined($dom) || $dom eq '' || 
                   2879:                 ! defined($name) || $name eq '') {
1.620     albertel 2880:                 my $cid = $env{'request.course.id'};
                   2881:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2882:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2883:             }
1.450     matthew  2884:             my $value = $accesshash{$entry};
                   2885:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2886:             my %temphash=($url => $value);
1.449     matthew  2887:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2888:             if ($result eq 'ok') {
                   2889:                 delete $accesshash{$entry};
                   2890:             } elsif ($result eq 'unknown_cmd') {
                   2891:                 # Target server has old code running on it.
1.450     matthew  2892:                 my %temphash=($entry => $value);
1.449     matthew  2893:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2894:                     delete $accesshash{$entry};
                   2895:                 }
                   2896:             }
                   2897:         } else {
1.811     albertel 2898:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2899:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2900:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2901:                 delete $accesshash{$entry};
                   2902:             }
1.185     www      2903:         }
1.191     harris41 2904:     }
1.352     www      2905: #
                   2906: # Roles
                   2907: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2908: #
1.800     albertel 2909:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2910:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2911: 	    split(/\:/,$entry);
                   2912:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2913:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2914:                 $rudom,$runame) eq 'ok') {
                   2915: 	    delete $userrolehash{$entry};
                   2916:         }
                   2917:     }
1.662     raeburn  2918: #
                   2919: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2920: #
                   2921:     my %domrolebuffer = ();
1.1000    raeburn  2922:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2923:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2924:         if ($domrolebuffer{$rudom}) {
                   2925:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2926:                       '='.&escape($domainrolehash{$entry});
                   2927:         } else {
                   2928:             $domrolebuffer{$rudom}.=&escape($entry).
                   2929:                       '='.&escape($domainrolehash{$entry});
                   2930:         }
                   2931:         delete $domainrolehash{$entry};
                   2932:     }
                   2933:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2934: 	my %servers = &get_servers($dom,'library');
                   2935: 	foreach my $tryserver (keys(%servers)) {
                   2936: 	    unless (&reply('domroleput:'.$dom.':'.
                   2937: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2938: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2939: 	    }
1.662     raeburn  2940:         }
                   2941:     }
1.186     www      2942:     $dumpcount++;
1.157     www      2943: }
                   2944: 
                   2945: sub courselog {
                   2946:     my $what=shift;
1.158     www      2947:     $what=time.':'.$what;
1.620     albertel 2948:     unless ($env{'request.course.id'}) { return ''; }
                   2949:     $coursedombuf{$env{'request.course.id'}}=
                   2950:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2951:     $coursenumbuf{$env{'request.course.id'}}=
                   2952:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2953:     $coursehombuf{$env{'request.course.id'}}=
                   2954:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2955:     $coursedescrbuf{$env{'request.course.id'}}=
                   2956:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2957:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2958:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2959:     $courseownerbuf{$env{'request.course.id'}}=
                   2960:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2961:     $coursetypebuf{$env{'request.course.id'}}=
                   2962:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2963:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2964: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2965:     } else {
1.620     albertel 2966: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2967:     }
1.620     albertel 2968:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2969: 	&flushcourselogs();
                   2970:     }
1.158     www      2971: }
                   2972: 
                   2973: sub courseacclog {
                   2974:     my $fnsymb=shift;
1.620     albertel 2975:     unless ($env{'request.course.id'}) { return ''; }
                   2976:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2977:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2978:         $what.=':POST';
1.583     matthew  2979:         # FIXME: Probably ought to escape things....
1.800     albertel 2980: 	foreach my $key (keys(%env)) {
                   2981:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2982:                 my $formitem = $1;
                   2983:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2984:                     $what.=':'.$formitem.'='.$env{$key};
                   2985:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2986:                     $what.=':'.$formitem.'='.$env{$key};
                   2987:                 }
1.158     www      2988:             }
1.191     harris41 2989:         }
1.583     matthew  2990:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2991:         # FIXME: We should not be depending on a form parameter that someone
                   2992:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2993:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2994:             $what.= ':POST';
                   2995:             # FIXME: Probably ought to escape things....
                   2996:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2997:                                  'crsdiscuss') {
1.620     albertel 2998:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2999:             }
                   3000:         }
1.158     www      3001:     }
                   3002:     &courselog($what);
1.149     www      3003: }
                   3004: 
1.185     www      3005: sub countacc {
                   3006:     my $url=&declutter(shift);
1.458     matthew  3007:     return if (! defined($url) || $url eq '');
1.620     albertel 3008:     unless ($env{'request.course.id'}) { return ''; }
                   3009:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3010:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3011:     $accesshash{$key}++;
1.185     www      3012: }
1.349     www      3013: 
1.361     www      3014: sub linklog {
                   3015:     my ($from,$to)=@_;
                   3016:     $from=&declutter($from);
                   3017:     $to=&declutter($to);
                   3018:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3019:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3020: }
                   3021:   
1.349     www      3022: sub userrolelog {
                   3023:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3024:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3025:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3026:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3027:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3028:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3029:        $userrolehash
                   3030:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3031:                     =$tend.':'.$tstart;
1.662     raeburn  3032:     }
1.898     albertel 3033:     if (($env{'request.role'} =~ /dc\./) &&
                   3034: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3035: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3036: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3037:          ($trole=~/^co/))) {
1.898     albertel 3038:        $userrolehash
                   3039:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3040:                     =$tend.':'.$tstart;
                   3041:     }
1.662     raeburn  3042:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3043:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3044:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3045:         ($trole=~/^sc/)) {
                   3046:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3047:        $domainrolehash
                   3048:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3049:                     = $tend.':'.$tstart;
                   3050:     }
1.351     www      3051: }
                   3052: 
1.957     raeburn  3053: sub courserolelog {
                   3054:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3055:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3056:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3057:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3058:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3059:         ($trole eq 'co')) {
1.957     raeburn  3060:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3061:             my $cdom = $1;
                   3062:             my $cnum = $2;
                   3063:             my $sec = $3;
                   3064:             my $namespace = 'rolelog';
                   3065:             my %storehash = (
                   3066:                                role    => $trole,
                   3067:                                start   => $tstart,
                   3068:                                end     => $tend,
                   3069:                                selfenroll => $selfenroll,
                   3070:                                context    => $context,
                   3071:                             );
                   3072:             if ($trole eq 'gr') {
                   3073:                 $namespace = 'groupslog';
                   3074:                 $storehash{'group'} = $sec;
                   3075:             } else {
                   3076:                 $storehash{'section'} = $sec;
                   3077:             }
                   3078:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3079:             if (($trole ne 'st') || ($sec ne '')) {
                   3080:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3081:             }
1.957     raeburn  3082:         }
                   3083:     }
                   3084:     return;
                   3085: }
                   3086: 
1.351     www      3087: sub get_course_adv_roles {
1.948     raeburn  3088:     my ($cid,$codes) = @_;
1.620     albertel 3089:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3090:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3091:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3092:     my %nothide=();
1.800     albertel 3093:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3094:         if ($user !~ /:/) {
                   3095: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3096:         } else {
                   3097:             $nothide{$user}=1;
                   3098:         }
1.470     www      3099:     }
1.351     www      3100:     my %returnhash=();
                   3101:     my %dumphash=
                   3102:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3103:     my $now=time;
1.997     raeburn  3104:     my %privileged;
1.1000    raeburn  3105:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3106: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3107:         if (($tstart) && ($tstart<0)) { next; }
                   3108:         if (($tend) && ($tend<$now)) { next; }
                   3109:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3110:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3111: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3112:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3113:             my %dompersonnel =
1.998     raeburn  3114:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3115:             $privileged{$domain} = {};
                   3116:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3117:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3118:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3119:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3120:                         $privileged{$udom}{$uname} = 1;
                   3121:                     }
                   3122:                 }
                   3123:             }
                   3124:         }
                   3125:         if ((exists($privileged{$domain}{$username})) && 
                   3126:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3127: 	if ($role eq 'cr') { next; }
1.948     raeburn  3128:         if ($codes) {
                   3129:             if ($section) { $role .= ':'.$section; }
                   3130:             if ($returnhash{$role}) {
                   3131:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3132:             } else {
                   3133:                 $returnhash{$role}=$username.':'.$domain;
                   3134:             }
1.351     www      3135:         } else {
1.988     raeburn  3136:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3137:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3138:             if ($returnhash{$key}) {
                   3139: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3140:             } else {
                   3141:                 $returnhash{$key}=$username.':'.$domain;
                   3142:             }
1.351     www      3143:         }
1.948     raeburn  3144:     }
1.400     www      3145:     return %returnhash;
                   3146: }
                   3147: 
                   3148: sub get_my_roles {
1.937     raeburn  3149:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3150:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3151:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3152:     my (%dumphash,%nothide);
1.1086    raeburn  3153:     if ($context eq 'userroles') {
                   3154:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3155:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3156:     } else {
                   3157:         %dumphash=
1.400     www      3158:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3159:         if ($hidepriv) {
                   3160:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3161:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3162:                 if ($user !~ /:/) {
                   3163:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3164:                 } else {
                   3165:                     $nothide{$user} = 1;
                   3166:                 }
                   3167:             }
                   3168:         }
1.858     raeburn  3169:     }
1.400     www      3170:     my %returnhash=();
                   3171:     my $now=time;
1.999     raeburn  3172:     my %privileged;
1.800     albertel 3173:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3174:         my ($role,$tend,$tstart);
                   3175:         if ($context eq 'userroles') {
                   3176: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3177:         } else {
                   3178:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3179:         }
1.400     www      3180:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3181:         my $status = 'active';
1.939     raeburn  3182:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3183:             $status = 'previous';
                   3184:         } 
                   3185:         if (($tstart) && ($now<$tstart)) {
                   3186:             $status = 'future';
                   3187:         }
                   3188:         if (ref($types) eq 'ARRAY') {
                   3189:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3190:                 next;
                   3191:             } 
                   3192:         } else {
                   3193:             if ($status ne 'active') {
                   3194:                 next;
                   3195:             }
                   3196:         }
1.867     raeburn  3197:         my ($rolecode,$username,$domain,$section,$area);
                   3198:         if ($context eq 'userroles') {
                   3199:             ($area,$rolecode) = split(/_/,$entry);
                   3200:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3201:         } else {
                   3202:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3203:         }
1.832     raeburn  3204:         if (ref($roledoms) eq 'ARRAY') {
                   3205:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3206:                 next;
                   3207:             }
                   3208:         }
                   3209:         if (ref($roles) eq 'ARRAY') {
                   3210:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3211:                 if ($role =~ /^cr\//) {
                   3212:                     if (!grep(/^cr$/,@{$roles})) {
                   3213:                         next;
                   3214:                     }
1.1104    raeburn  3215:                 } elsif ($role =~ /^gr\//) {
                   3216:                     if (!grep(/^gr$/,@{$roles})) {
                   3217:                         next;
                   3218:                     }
1.922     raeburn  3219:                 } else {
                   3220:                     next;
                   3221:                 }
1.832     raeburn  3222:             }
1.867     raeburn  3223:         }
1.937     raeburn  3224:         if ($hidepriv) {
1.999     raeburn  3225:             if ($context eq 'userroles') {
                   3226:                 if ((&privileged($username,$domain)) &&
                   3227:                     (!$nothide{$username.':'.$domain})) {
                   3228:                     next;
                   3229:                 }
                   3230:             } else {
                   3231:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3232:                     my %dompersonnel =
                   3233:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3234:                     $privileged{$domain} = {};
                   3235:                     if (keys(%dompersonnel)) {
                   3236:                         foreach my $server (keys(%dompersonnel)) {
                   3237:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3238:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3239:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3240:                                     $privileged{$udom}{$uname} = $trole;
                   3241:                                 }
                   3242:                             }
                   3243:                         }
                   3244:                     }
                   3245:                 }
                   3246:                 if (exists($privileged{$domain}{$username})) {
                   3247:                     if (!$nothide{$username.':'.$domain}) {
                   3248:                         next;
                   3249:                     }
                   3250:                 }
1.937     raeburn  3251:             }
                   3252:         }
1.933     raeburn  3253:         if ($withsec) {
                   3254:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3255:                 $tstart.':'.$tend;
                   3256:         } else {
                   3257:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3258:         }
1.832     raeburn  3259:     }
1.373     www      3260:     return %returnhash;
1.399     www      3261: }
                   3262: 
                   3263: # ----------------------------------------------------- Frontpage Announcements
                   3264: #
                   3265: #
                   3266: 
                   3267: sub postannounce {
                   3268:     my ($server,$text)=@_;
1.844     albertel 3269:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3270:     unless ($text=~/\w/) { $text=''; }
                   3271:     return &reply('setannounce:'.&escape($text),$server);
                   3272: }
                   3273: 
                   3274: sub getannounce {
1.448     albertel 3275: 
                   3276:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3277: 	my $announcement='';
1.800     albertel 3278: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3279: 	close($fh);
1.399     www      3280: 	if ($announcement=~/\w/) { 
                   3281: 	    return 
                   3282:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3283:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3284: 	} else {
                   3285: 	    return '';
                   3286: 	}
                   3287:     } else {
                   3288: 	return '';
                   3289:     }
1.351     www      3290: }
1.353     www      3291: 
                   3292: # ---------------------------------------------------------- Course ID routines
                   3293: # Deal with domain's nohist_courseid.db files
                   3294: #
                   3295: 
                   3296: sub courseidput {
1.921     raeburn  3297:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3298:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3299:     my $outcome;
                   3300:     if ($caller eq 'timeonly') {
                   3301:         my $cids = '';
                   3302:         foreach my $item (keys(%$storehash)) {
                   3303:             $cids.=&escape($item).'&';
                   3304:         }
                   3305:         $cids=~s/\&$//;
                   3306:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3307:                           $coursehome);       
                   3308:     } else {
                   3309:         my $items = '';
                   3310:         foreach my $item (keys(%$storehash)) {
                   3311:             $items.= &escape($item).'='.
                   3312:                      &freeze_escape($$storehash{$item}).'&';
                   3313:         }
                   3314:         $items=~s/\&$//;
                   3315:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3316:                           $coursehome);
1.918     raeburn  3317:     }
                   3318:     if ($outcome eq 'unknown_cmd') {
                   3319:         my $what;
                   3320:         foreach my $cid (keys(%$storehash)) {
                   3321:             $what .= &escape($cid).'=';
1.921     raeburn  3322:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3323:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3324:             }
                   3325:             $what =~ s/\:$/&/;
                   3326:         }
                   3327:         $what =~ s/\&$//;  
                   3328:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3329:     } else {
                   3330:         return $outcome;
                   3331:     }
1.353     www      3332: }
                   3333: 
                   3334: sub courseiddump {
1.921     raeburn  3335:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3336:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3337:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3338:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3339:     my $as_hash = 1;
                   3340:     my %returnhash;
                   3341:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3342:     my %libserv = &all_library();
                   3343:     foreach my $tryserver (keys(%libserv)) {
                   3344:         if ( (  $hostidflag == 1 
                   3345: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3346: 	     || (!defined($hostidflag)) ) {
                   3347: 
1.918     raeburn  3348: 	    if (($domfilter eq '') ||
                   3349: 		(&host_domain($tryserver) eq $domfilter)) {
                   3350:                 my $rep = 
                   3351:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3352:                          $sincefilter.':'.&escape($descfilter).':'.
                   3353:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3354:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3355:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3356:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3357:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3358:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3359:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3360:                          &escape($creationcontext).':'.$domcloner,
                   3361:                          $tryserver);
1.918     raeburn  3362:                 my @pairs=split(/\&/,$rep);
                   3363:                 foreach my $item (@pairs) {
                   3364:                     my ($key,$value)=split(/\=/,$item,2);
                   3365:                     $key = &unescape($key);
                   3366:                     next if ($key =~ /^error: 2 /);
                   3367:                     my $result = &thaw_unescape($value);
                   3368:                     if (ref($result) eq 'HASH') {
                   3369:                         $returnhash{$key}=$result;
                   3370:                     } else {
1.921     raeburn  3371:                         my @responses = split(/:/,$value);
                   3372:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3373:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3374:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3375:                         }
1.1008    raeburn  3376:                     }
1.353     www      3377:                 }
                   3378:             }
                   3379:         }
                   3380:     }
                   3381:     return %returnhash;
                   3382: }
                   3383: 
1.1055    raeburn  3384: sub courselastaccess {
                   3385:     my ($cdom,$cnum,$hostidref) = @_;
                   3386:     my %returnhash;
                   3387:     if ($cdom && $cnum) {
                   3388:         my $chome = &homeserver($cnum,$cdom);
                   3389:         if ($chome ne 'no_host') {
                   3390:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3391:             &extract_lastaccess(\%returnhash,$rep);
                   3392:         }
                   3393:     } else {
                   3394:         if (!$cdom) { $cdom=''; }
                   3395:         my %libserv = &all_library();
                   3396:         foreach my $tryserver (keys(%libserv)) {
                   3397:             if (ref($hostidref) eq 'ARRAY') {
                   3398:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3399:             } 
                   3400:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3401:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3402:                 &extract_lastaccess(\%returnhash,$rep);
                   3403:             }
                   3404:         }
                   3405:     }
                   3406:     return %returnhash;
                   3407: }
                   3408: 
                   3409: sub extract_lastaccess {
                   3410:     my ($returnhash,$rep) = @_;
                   3411:     if (ref($returnhash) eq 'HASH') {
                   3412:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3413:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3414:                  $rep eq '') {
                   3415:             my @pairs=split(/\&/,$rep);
                   3416:             foreach my $item (@pairs) {
                   3417:                 my ($key,$value)=split(/\=/,$item,2);
                   3418:                 $key = &unescape($key);
                   3419:                 next if ($key =~ /^error: 2 /);
                   3420:                 $returnhash->{$key} = &thaw_unescape($value);
                   3421:             }
                   3422:         }
                   3423:     }
                   3424:     return;
                   3425: }
                   3426: 
1.658     raeburn  3427: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3428: 
                   3429: sub dcmailput {
1.685     raeburn  3430:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3431:     my $status = &Apache::lonnet::critical(
1.740     www      3432:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3433:        &escape($message),$server);
1.662     raeburn  3434:     return $status;
                   3435: }
                   3436: 
1.658     raeburn  3437: sub dcmaildump {
                   3438:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3439:     my %returnhash=();
1.846     albertel 3440: 
                   3441:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3442:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3443:                                                          &escape($enddate).':';
                   3444: 	my @esc_senders=map { &escape($_)} @$senders;
                   3445: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3446: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3447:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3448:             if (($key) && ($value)) {
                   3449:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3450:             }
                   3451:         }
                   3452:     }
                   3453:     return %returnhash;
                   3454: }
1.662     raeburn  3455: # ---------------------------------------------------------- Domain roles
                   3456: 
                   3457: sub get_domain_roles {
                   3458:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3459:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3460:         $startdate = '.';
                   3461:     }
1.1018    raeburn  3462:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3463:         $enddate = '.';
                   3464:     }
1.922     raeburn  3465:     my $rolelist;
                   3466:     if (ref($roles) eq 'ARRAY') {
                   3467:         $rolelist = join(':',@{$roles});
                   3468:     }
1.662     raeburn  3469:     my %personnel = ();
1.841     albertel 3470: 
                   3471:     my %servers = &get_servers($dom,'library');
                   3472:     foreach my $tryserver (keys(%servers)) {
                   3473: 	%{$personnel{$tryserver}}=();
                   3474: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3475: 					    &escape($startdate).':'.
                   3476: 					    &escape($enddate).':'.
                   3477: 					    &escape($rolelist), $tryserver))) {
                   3478: 	    my ($key,$value) = split(/\=/,$line,2);
                   3479: 	    if (($key) && ($value)) {
                   3480: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3481: 	    }
                   3482: 	}
1.662     raeburn  3483:     }
                   3484:     return %personnel;
                   3485: }
1.658     raeburn  3486: 
1.1057    www      3487: # ----------------------------------------------------------- Interval timing 
1.149     www      3488: 
1.504     albertel 3489: sub get_first_access {
                   3490:     my ($type,$argsymb)=@_;
1.790     albertel 3491:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3492:     if ($argsymb) { $symb=$argsymb; }
                   3493:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3494:     if ($type eq 'course') {
                   3495: 	$res='course';
                   3496:     } elsif ($type eq 'map') {
1.588     albertel 3497: 	$res=&symbread($map);
                   3498:     } else {
                   3499: 	$res=$symb;
                   3500:     }
                   3501:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3502:     return $times{"$courseid\0$res"};
1.504     albertel 3503: }
                   3504: 
                   3505: sub set_first_access {
                   3506:     my ($type)=@_;
1.790     albertel 3507:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3508:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3509:     if ($type eq 'course') {
                   3510: 	$res='course';
                   3511:     } elsif ($type eq 'map') {
1.588     albertel 3512: 	$res=&symbread($map);
                   3513:     } else {
                   3514: 	$res=$symb;
                   3515:     }
                   3516:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3517:     if (!$firstaccess) {
1.588     albertel 3518: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3519:     }
                   3520:     return 'already_set';
1.504     albertel 3521: }
                   3522: 
1.110     www      3523: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3524: 
                   3525: sub expirespread {
                   3526:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3527:     my $cid=$env{'request.course.id'}; 
1.110     www      3528:     if ($cid) {
                   3529:        my $now=time;
                   3530:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3531:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3532:                             $env{'course.'.$cid.'.num'}.
1.110     www      3533: 	        	    ':nohist_expirationdates:'.
                   3534:                             &escape($key).'='.$now,
1.620     albertel 3535:                             $env{'course.'.$cid.'.home'})
1.110     www      3536:     }
                   3537:     return 'ok';
1.14      www      3538: }
                   3539: 
1.109     www      3540: # ----------------------------------------------------- Devalidate Spreadsheets
                   3541: 
                   3542: sub devalidate {
1.325     www      3543:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3544:     my $cid=$env{'request.course.id'}; 
1.109     www      3545:     if ($cid) {
1.391     matthew  3546:         # delete the stored spreadsheets for
                   3547:         # - the student level sheet of this user in course's homespace
                   3548:         # - the assessment level sheet for this resource 
                   3549:         #   for this user in user's homespace
1.553     albertel 3550: 	# - current conditional state info
1.325     www      3551: 	my $key=$uname.':'.$udom.':';
1.109     www      3552:         my $status=
1.299     matthew  3553: 	    &del('nohist_calculatedsheets',
1.391     matthew  3554: 		 [$key.'studentcalc:'],
1.620     albertel 3555: 		 $env{'course.'.$cid.'.domain'},
                   3556: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3557: 		.' '.
                   3558: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3559: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3560:         unless ($status eq 'ok ok') {
                   3561:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3562:                     $uname.' at '.$udom.' for '.
1.109     www      3563: 		    $symb.': '.$status);
1.133     albertel 3564:         }
1.553     albertel 3565: 	&delenv('user.state.'.$cid);
1.109     www      3566:     }
                   3567: }
                   3568: 
1.265     albertel 3569: sub get_scalar {
                   3570:     my ($string,$end) = @_;
                   3571:     my $value;
                   3572:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3573: 	$value = $1;
                   3574:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3575: 	$value = $1;
                   3576:     }
                   3577:     return &unescape($value);
                   3578: }
                   3579: 
                   3580: sub array2str {
                   3581:   my (@array) = @_;
                   3582:   my $result=&arrayref2str(\@array);
                   3583:   $result=~s/^__ARRAY_REF__//;
                   3584:   $result=~s/__END_ARRAY_REF__$//;
                   3585:   return $result;
                   3586: }
                   3587: 
1.204     albertel 3588: sub arrayref2str {
                   3589:   my ($arrayref) = @_;
1.265     albertel 3590:   my $result='__ARRAY_REF__';
1.204     albertel 3591:   foreach my $elem (@$arrayref) {
1.265     albertel 3592:     if(ref($elem) eq 'ARRAY') {
                   3593:       $result.=&arrayref2str($elem).'&';
                   3594:     } elsif(ref($elem) eq 'HASH') {
                   3595:       $result.=&hashref2str($elem).'&';
                   3596:     } elsif(ref($elem)) {
                   3597:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3598:     } else {
                   3599:       $result.=&escape($elem).'&';
                   3600:     }
                   3601:   }
                   3602:   $result=~s/\&$//;
1.265     albertel 3603:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3604:   return $result;
                   3605: }
                   3606: 
1.168     albertel 3607: sub hash2str {
1.204     albertel 3608:   my (%hash) = @_;
                   3609:   my $result=&hashref2str(\%hash);
1.265     albertel 3610:   $result=~s/^__HASH_REF__//;
                   3611:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3612:   return $result;
                   3613: }
                   3614: 
                   3615: sub hashref2str {
                   3616:   my ($hashref)=@_;
1.265     albertel 3617:   my $result='__HASH_REF__';
1.800     albertel 3618:   foreach my $key (sort(keys(%$hashref))) {
                   3619:     if (ref($key) eq 'ARRAY') {
                   3620:       $result.=&arrayref2str($key).'=';
                   3621:     } elsif (ref($key) eq 'HASH') {
                   3622:       $result.=&hashref2str($key).'=';
                   3623:     } elsif (ref($key)) {
1.265     albertel 3624:       $result.='=';
1.800     albertel 3625:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3626:     } else {
1.800     albertel 3627: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3628:     }
                   3629: 
1.800     albertel 3630:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3631:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3632:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3633:       $result.=&hashref2str($hashref->{$key}).'&';
                   3634:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3635:        $result.='&';
1.800     albertel 3636:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3637:     } else {
1.800     albertel 3638:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3639:     }
                   3640:   }
1.168     albertel 3641:   $result=~s/\&$//;
1.265     albertel 3642:   $result .= '__END_HASH_REF__';
1.168     albertel 3643:   return $result;
                   3644: }
                   3645: 
                   3646: sub str2hash {
1.265     albertel 3647:     my ($string)=@_;
                   3648:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3649:     return %$hash;
                   3650: }
                   3651: 
                   3652: sub str2hashref {
1.168     albertel 3653:   my ($string) = @_;
1.265     albertel 3654: 
                   3655:   my %hash;
                   3656: 
                   3657:   if($string !~ /^__HASH_REF__/) {
                   3658:       if (! ($string eq '' || !defined($string))) {
                   3659: 	  $hash{'error'}='Not hash reference';
                   3660:       }
                   3661:       return (\%hash, $string);
                   3662:   }
                   3663: 
                   3664:   $string =~ s/^__HASH_REF__//;
                   3665: 
                   3666:   while($string !~ /^__END_HASH_REF__/) {
                   3667:       #key
                   3668:       my $key='';
                   3669:       if($string =~ /^__HASH_REF__/) {
                   3670:           ($key, $string)=&str2hashref($string);
                   3671:           if(defined($key->{'error'})) {
                   3672:               $hash{'error'}='Bad data';
                   3673:               return (\%hash, $string);
                   3674:           }
                   3675:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3676:           ($key, $string)=&str2arrayref($string);
                   3677:           if($key->[0] eq 'Array reference error') {
                   3678:               $hash{'error'}='Bad data';
                   3679:               return (\%hash, $string);
                   3680:           }
                   3681:       } else {
                   3682:           $string =~ s/^(.*?)=//;
1.267     albertel 3683: 	  $key=&unescape($1);
1.265     albertel 3684:       }
                   3685:       $string =~ s/^=//;
                   3686: 
                   3687:       #value
                   3688:       my $value='';
                   3689:       if($string =~ /^__HASH_REF__/) {
                   3690:           ($value, $string)=&str2hashref($string);
                   3691:           if(defined($value->{'error'})) {
                   3692:               $hash{'error'}='Bad data';
                   3693:               return (\%hash, $string);
                   3694:           }
                   3695:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3696:           ($value, $string)=&str2arrayref($string);
                   3697:           if($value->[0] eq 'Array reference error') {
                   3698:               $hash{'error'}='Bad data';
                   3699:               return (\%hash, $string);
                   3700:           }
                   3701:       } else {
                   3702: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3703:       }
                   3704:       $string =~ s/^&//;
                   3705: 
                   3706:       $hash{$key}=$value;
1.204     albertel 3707:   }
1.265     albertel 3708: 
                   3709:   $string =~ s/^__END_HASH_REF__//;
                   3710: 
                   3711:   return (\%hash, $string);
1.204     albertel 3712: }
                   3713: 
                   3714: sub str2array {
1.265     albertel 3715:     my ($string)=@_;
                   3716:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3717:     return @$array;
                   3718: }
                   3719: 
                   3720: sub str2arrayref {
1.204     albertel 3721:   my ($string) = @_;
1.265     albertel 3722:   my @array;
                   3723: 
                   3724:   if($string !~ /^__ARRAY_REF__/) {
                   3725:       if (! ($string eq '' || !defined($string))) {
                   3726: 	  $array[0]='Array reference error';
                   3727:       }
                   3728:       return (\@array, $string);
                   3729:   }
                   3730: 
                   3731:   $string =~ s/^__ARRAY_REF__//;
                   3732: 
                   3733:   while($string !~ /^__END_ARRAY_REF__/) {
                   3734:       my $value='';
                   3735:       if($string =~ /^__HASH_REF__/) {
                   3736:           ($value, $string)=&str2hashref($string);
                   3737:           if(defined($value->{'error'})) {
                   3738:               $array[0] ='Array reference error';
                   3739:               return (\@array, $string);
                   3740:           }
                   3741:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3742:           ($value, $string)=&str2arrayref($string);
                   3743:           if($value->[0] eq 'Array reference error') {
                   3744:               $array[0] ='Array reference error';
                   3745:               return (\@array, $string);
                   3746:           }
                   3747:       } else {
                   3748: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3749:       }
                   3750:       $string =~ s/^&//;
                   3751: 
                   3752:       push(@array, $value);
1.191     harris41 3753:   }
1.265     albertel 3754: 
                   3755:   $string =~ s/^__END_ARRAY_REF__//;
                   3756: 
                   3757:   return (\@array, $string);
1.168     albertel 3758: }
                   3759: 
1.167     albertel 3760: # -------------------------------------------------------------------Temp Store
                   3761: 
1.168     albertel 3762: sub tmpreset {
                   3763:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3764:   if (!$symb) {
                   3765:     $symb=&symbread();
1.620     albertel 3766:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3767:   }
                   3768:   $symb=escape($symb);
                   3769: 
1.620     albertel 3770:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3771:   $namespace=~s/\//\_/g;
                   3772:   $namespace=~s/\W//g;
                   3773: 
1.620     albertel 3774:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3775:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3776:   if ($domain eq 'public' && $stuname eq 'public') {
                   3777:       $stuname=$ENV{'REMOTE_ADDR'};
                   3778:   }
1.1117    foxr     3779:   my $path=LONCAPA::tempdir();
1.168     albertel 3780:   my %hash;
                   3781:   if (tie(%hash,'GDBM_File',
                   3782: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3783: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3784:     foreach my $key (keys(%hash)) {
1.180     albertel 3785:       if ($key=~ /:$symb/) {
1.168     albertel 3786: 	delete($hash{$key});
                   3787:       }
                   3788:     }
                   3789:   }
                   3790: }
                   3791: 
1.167     albertel 3792: sub tmpstore {
1.168     albertel 3793:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3794: 
                   3795:   if (!$symb) {
                   3796:     $symb=&symbread();
1.620     albertel 3797:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3798:   }
                   3799:   $symb=escape($symb);
                   3800: 
                   3801:   if (!$namespace) {
                   3802:     # I don't think we would ever want to store this for a course.
                   3803:     # it seems this will only be used if we don't have a course.
1.620     albertel 3804:     #$namespace=$env{'request.course.id'};
1.168     albertel 3805:     #if (!$namespace) {
1.620     albertel 3806:       $namespace=$env{'request.state'};
1.168     albertel 3807:     #}
                   3808:   }
                   3809:   $namespace=~s/\//\_/g;
                   3810:   $namespace=~s/\W//g;
1.620     albertel 3811:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3812:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3813:   if ($domain eq 'public' && $stuname eq 'public') {
                   3814:       $stuname=$ENV{'REMOTE_ADDR'};
                   3815:   }
1.168     albertel 3816:   my $now=time;
                   3817:   my %hash;
1.1117    foxr     3818:   my $path=LONCAPA::tempdir();
1.168     albertel 3819:   if (tie(%hash,'GDBM_File',
                   3820: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3821: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3822:     $hash{"version:$symb"}++;
                   3823:     my $version=$hash{"version:$symb"};
                   3824:     my $allkeys=''; 
                   3825:     foreach my $key (keys(%$storehash)) {
                   3826:       $allkeys.=$key.':';
1.591     albertel 3827:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3828:     }
                   3829:     $hash{"$version:$symb:timestamp"}=$now;
                   3830:     $allkeys.='timestamp';
                   3831:     $hash{"$version:keys:$symb"}=$allkeys;
                   3832:     if (untie(%hash)) {
                   3833:       return 'ok';
                   3834:     } else {
                   3835:       return "error:$!";
                   3836:     }
                   3837:   } else {
                   3838:     return "error:$!";
                   3839:   }
                   3840: }
1.167     albertel 3841: 
1.168     albertel 3842: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3843: 
1.168     albertel 3844: sub tmprestore {
                   3845:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3846: 
1.168     albertel 3847:   if (!$symb) {
                   3848:     $symb=&symbread();
1.620     albertel 3849:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3850:   }
                   3851:   $symb=escape($symb);
                   3852: 
1.620     albertel 3853:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3854: 
1.620     albertel 3855:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3856:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3857:   if ($domain eq 'public' && $stuname eq 'public') {
                   3858:       $stuname=$ENV{'REMOTE_ADDR'};
                   3859:   }
1.168     albertel 3860:   my %returnhash;
                   3861:   $namespace=~s/\//\_/g;
                   3862:   $namespace=~s/\W//g;
                   3863:   my %hash;
1.1117    foxr     3864:   my $path=LONCAPA::tempdir();
1.168     albertel 3865:   if (tie(%hash,'GDBM_File',
                   3866: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3867: 	  &GDBM_READER(),0640)) {
1.168     albertel 3868:     my $version=$hash{"version:$symb"};
                   3869:     $returnhash{'version'}=$version;
                   3870:     my $scope;
                   3871:     for ($scope=1;$scope<=$version;$scope++) {
                   3872:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3873:       my @keys=split(/:/,$vkeys);
                   3874:       my $key;
                   3875:       $returnhash{"$scope:keys"}=$vkeys;
                   3876:       foreach $key (@keys) {
1.591     albertel 3877: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3878: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3879:       }
                   3880:     }
1.168     albertel 3881:     if (!(untie(%hash))) {
                   3882:       return "error:$!";
                   3883:     }
                   3884:   } else {
                   3885:     return "error:$!";
                   3886:   }
                   3887:   return %returnhash;
1.167     albertel 3888: }
                   3889: 
1.9       www      3890: # ----------------------------------------------------------------------- Store
                   3891: 
                   3892: sub store {
1.124     www      3893:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3894:     my $home='';
                   3895: 
1.168     albertel 3896:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3897: 
1.213     www      3898:     $symb=&symbclean($symb);
1.122     albertel 3899:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3900: 
1.620     albertel 3901:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3902:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3903: 
                   3904:     &devalidate($symb,$stuname,$domain);
1.109     www      3905: 
                   3906:     $symb=escape($symb);
1.187     www      3907:     if (!$namespace) { 
1.620     albertel 3908:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3909:           return ''; 
                   3910:        } 
                   3911:     }
1.620     albertel 3912:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3913: 
                   3914:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3915:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3916: 
1.12      www      3917:     my $namevalue='';
1.800     albertel 3918:     foreach my $key (keys(%$storehash)) {
                   3919:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3920:     }
1.12      www      3921:     $namevalue=~s/\&$//;
1.187     www      3922:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3923:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3924: }
                   3925: 
1.47      www      3926: # -------------------------------------------------------------- Critical Store
                   3927: 
                   3928: sub cstore {
1.124     www      3929:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3930:     my $home='';
                   3931: 
1.168     albertel 3932:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3933: 
1.213     www      3934:     $symb=&symbclean($symb);
1.122     albertel 3935:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3936: 
1.620     albertel 3937:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3938:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3939: 
                   3940:     &devalidate($symb,$stuname,$domain);
1.109     www      3941: 
                   3942:     $symb=escape($symb);
1.187     www      3943:     if (!$namespace) { 
1.620     albertel 3944:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3945:           return ''; 
                   3946:        } 
                   3947:     }
1.620     albertel 3948:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3949: 
                   3950:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3951:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3952: 
1.47      www      3953:     my $namevalue='';
1.800     albertel 3954:     foreach my $key (keys(%$storehash)) {
                   3955:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3956:     }
1.47      www      3957:     $namevalue=~s/\&$//;
1.187     www      3958:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3959:     return critical
                   3960:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3961: }
                   3962: 
1.9       www      3963: # --------------------------------------------------------------------- Restore
                   3964: 
                   3965: sub restore {
1.124     www      3966:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3967:     my $home='';
                   3968: 
1.168     albertel 3969:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3970: 
1.122     albertel 3971:     if (!$symb) {
                   3972:       unless ($symb=escape(&symbread())) { return ''; }
                   3973:     } else {
1.213     www      3974:       $symb=&escape(&symbclean($symb));
1.122     albertel 3975:     }
1.188     www      3976:     if (!$namespace) { 
1.620     albertel 3977:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3978:           return ''; 
                   3979:        } 
                   3980:     }
1.620     albertel 3981:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3982:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3983:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3984:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3985: 
1.12      www      3986:     my %returnhash=();
1.800     albertel 3987:     foreach my $line (split(/\&/,$answer)) {
                   3988: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3989:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3990:     }
1.75      www      3991:     my $version;
                   3992:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3993:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3994:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3995:        }
1.75      www      3996:     }
1.13      www      3997:     return %returnhash;
1.34      www      3998: }
                   3999: 
                   4000: # ---------------------------------------------------------- Course Description
1.1118    foxr     4001: #
                   4002: #  
1.34      www      4003: 
                   4004: sub coursedescription {
1.731     albertel 4005:     my ($courseid,$args)=@_;
1.34      www      4006:     $courseid=~s/^\///;
1.49      www      4007:     $courseid=~s/\_/\//g;
1.34      www      4008:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4009:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4010:     my $normalid=$cdomain.'_'.$cnum;
                   4011:     # need to always cache even if we get errors otherwise we keep 
                   4012:     # trying and trying and trying to get the course description.
                   4013:     my %envhash=();
                   4014:     my %returnhash=();
1.731     albertel 4015:     
                   4016:     my $expiretime=600;
                   4017:     if ($env{'request.course.id'} eq $normalid) {
                   4018: 	$expiretime=120;
                   4019:     }
                   4020: 
                   4021:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4022:     if (!$args->{'freshen_cache'}
                   4023: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4024: 	foreach my $key (keys(%env)) {
                   4025: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4026: 	    my ($setting) = $1;
                   4027: 	    $returnhash{$setting} = $env{$key};
                   4028: 	}
                   4029: 	return %returnhash;
                   4030:     }
                   4031: 
1.1118    foxr     4032:     # get the data again
                   4033: 
1.731     albertel 4034:     if (!$args->{'one_time'}) {
                   4035: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4036:     }
1.811     albertel 4037: 
1.34      www      4038:     if ($chome ne 'no_host') {
1.302     albertel 4039:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4040:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4041: 	   my $username = $env{'user.name'}; # Defult username
                   4042: 	   if(defined $args->{'user'}) {
                   4043: 	       $username = $args->{'user'};
                   4044: 	   }
1.129     albertel 4045:            $returnhash{'home'}= $chome;
                   4046: 	   $returnhash{'domain'} = $cdomain;
                   4047: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4048:            if (!defined($returnhash{'type'})) {
                   4049:                $returnhash{'type'} = 'Course';
                   4050:            }
1.130     albertel 4051:            while (my ($name,$value) = each %returnhash) {
1.53      www      4052:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4053:            }
1.270     www      4054:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4055:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4056: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4057:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4058:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4059:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4060:        }
                   4061:     }
1.731     albertel 4062:     if (!$args->{'one_time'}) {
1.949     raeburn  4063: 	&appenv(\%envhash);
1.731     albertel 4064:     }
1.302     albertel 4065:     return %returnhash;
1.461     www      4066: }
                   4067: 
1.1080    raeburn  4068: sub update_released_required {
                   4069:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4070:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4071:         $cid = $env{'request.course.id'};
                   4072:         $cdom = $env{'course.'.$cid.'.domain'};
                   4073:         $cnum = $env{'course.'.$cid.'.num'};
                   4074:         $chome = $env{'course.'.$cid.'.home'};
                   4075:     }
                   4076:     if ($needsrelease) {
                   4077:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4078:         my $needsupdate;
                   4079:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4080:             $needsupdate = 1;
                   4081:         } else {
                   4082:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4083:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4084:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4085:                 $needsupdate = 1;
                   4086:             }
                   4087:         }
                   4088:         if ($needsupdate) {
                   4089:             my %needshash = (
                   4090:                              'internal.releaserequired' => $needsrelease,
                   4091:                             );
                   4092:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4093:             if ($putresult eq 'ok') {
                   4094:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4095:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4096:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4097:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4098:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4099:                 }
                   4100:             }
                   4101:         }
                   4102:     }
                   4103:     return;
                   4104: }
                   4105: 
1.461     www      4106: # -------------------------------------------------See if a user is privileged
                   4107: 
                   4108: sub privileged {
                   4109:     my ($username,$domain)=@_;
                   4110:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4111: 			&homeserver($username,$domain));
1.1033    raeburn  4112:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4113:         ($rolesdump =~ /^error:/)) {
                   4114:         return 0;
                   4115:     }
1.461     www      4116:     my $now=time;
                   4117:     if ($rolesdump ne '') {
1.800     albertel 4118:         foreach my $entry (split(/&/,$rolesdump)) {
                   4119: 	    if ($entry!~/^rolesdef_/) {
                   4120: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4121: 		$area=~s/\_\w\w$//;
                   4122: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4123: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4124: 		    my $active=1;
                   4125: 		    if ($tend) {
                   4126: 			if ($tend<$now) { $active=0; }
                   4127: 		    }
                   4128: 		    if ($tstart) {
                   4129: 			if ($tstart>$now) { $active=0; }
                   4130: 		    }
                   4131: 		    if ($active) { return 1; }
                   4132: 		}
                   4133: 	    }
                   4134: 	}
                   4135:     }
                   4136:     return 0;
1.9       www      4137: }
1.1       albertel 4138: 
1.103     harris41 4139: # -------------------------------------------------------- Get user privileges
1.11      www      4140: 
                   4141: sub rolesinit {
                   4142:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4143:     my $now=time;
                   4144:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4145:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4146:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4147:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4148:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4149:         return \%userroles;
                   4150:     }
1.11      www      4151:     my %allroles=();
1.678     raeburn  4152:     my %allgroups=();   
1.11      www      4153: 
                   4154:     if ($rolesdump ne '') {
1.800     albertel 4155:         foreach my $entry (split(/&/,$rolesdump)) {
                   4156: 	  if ($entry!~/^rolesdef_/) {
                   4157:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4158: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4159:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4160: 	    if ($role=~/^cr/) { 
1.807     albertel 4161: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4162: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4163: 		    ($tend,$tstart)=split('_',$trest);
                   4164: 		} else {
                   4165: 		    $trole=$role;
                   4166: 		}
1.678     raeburn  4167:             } elsif ($role =~ m|^gr/|) {
                   4168:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4169:                 next if ($tstart eq '-1');
1.678     raeburn  4170:                 ($trole,$group_privs) = split(/\//,$trole);
                   4171:                 $group_privs = &unescape($group_privs);
1.587     albertel 4172: 	    } else {
                   4173: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4174: 	    }
1.743     albertel 4175: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4176: 					 $username);
                   4177: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4178:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4179:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4180:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4181: 		my $spec=$trole.'.'.$area;
                   4182: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4183: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4184:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4185:                 } elsif ($trole eq 'gr') {
                   4186:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4187: 		} else {
1.567     raeburn  4188:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4189: 		}
1.12      www      4190:             }
1.662     raeburn  4191:           }
1.191     harris41 4192:         }
1.743     albertel 4193:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4194:         $userroles{'user.adv'}    = $adv;
                   4195: 	$userroles{'user.author'} = $author;
1.620     albertel 4196:         $env{'user.adv'}=$adv;
1.11      www      4197:     }
1.743     albertel 4198:     return \%userroles;  
1.11      www      4199: }
                   4200: 
1.567     raeburn  4201: sub set_arearole {
                   4202:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4203: # log the associated role with the area
                   4204:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4205:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4206: }
                   4207: 
                   4208: sub custom_roleprivs {
                   4209:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4210:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4211:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4212:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4213:         my ($rdummy,$roledef)=
                   4214:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4215:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4216:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4217:             if (defined($syspriv)) {
1.1043    raeburn  4218:                 if ($trest =~ /^$match_community$/) {
                   4219:                     $syspriv =~ s/bre\&S//; 
                   4220:                 }
1.567     raeburn  4221:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4222:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4223:             }
                   4224:             if ($tdomain ne '') {
                   4225:                 if (defined($dompriv)) {
                   4226:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4227:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4228:                 }
                   4229:                 if (($trest ne '') && (defined($coursepriv))) {
                   4230:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4231:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4232:                 }
                   4233:             }
                   4234:         }
                   4235:     }
                   4236: }
                   4237: 
1.678     raeburn  4238: sub group_roleprivs {
                   4239:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4240:     my $access = 1;
                   4241:     my $now = time;
                   4242:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4243:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4244:     if ($access) {
1.811     albertel 4245:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4246:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4247:     }
                   4248: }
1.567     raeburn  4249: 
                   4250: sub standard_roleprivs {
                   4251:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4252:     if (defined($pr{$trole.':s'})) {
                   4253:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4254:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4255:     }
                   4256:     if ($tdomain ne '') {
                   4257:         if (defined($pr{$trole.':d'})) {
                   4258:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4259:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4260:         }
                   4261:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4262:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4263:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4264:         }
                   4265:     }
                   4266: }
                   4267: 
                   4268: sub set_userprivs {
1.1064    raeburn  4269:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4270:     my $author=0;
                   4271:     my $adv=0;
1.678     raeburn  4272:     my %grouproles = ();
                   4273:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4274:         my @groupkeys; 
1.1000    raeburn  4275:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4276:             push(@groupkeys,$role);
                   4277:         }
                   4278:         if (ref($groups_roles) eq 'HASH') {
                   4279:             foreach my $key (keys(%{$groups_roles})) {
                   4280:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4281:                     push(@groupkeys,$key);
                   4282:                 }
                   4283:             }
                   4284:         }
                   4285:         if (@groupkeys > 0) {
                   4286:             foreach my $role (@groupkeys) {
                   4287:                 my ($trole,$area,$sec,$extendedarea);
                   4288:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4289:                     $trole = $1;
                   4290:                     $area = $2;
                   4291:                     $sec = $3;
                   4292:                     $extendedarea = $area.$sec;
                   4293:                     if (exists($$allgroups{$area})) {
                   4294:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4295:                             my $spec = $trole.'.'.$extendedarea;
                   4296:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4297:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4298:                         }
1.678     raeburn  4299:                     }
                   4300:                 }
                   4301:             }
                   4302:         }
                   4303:     }
1.800     albertel 4304:     foreach my $group (keys(%grouproles)) {
                   4305:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4306:     }
1.800     albertel 4307:     foreach my $role (keys(%{$allroles})) {
                   4308:         my %thesepriv;
1.941     raeburn  4309:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4310:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4311:             if ($item ne '') {
                   4312:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4313:                 if ($restrictions eq '') {
                   4314:                     $thesepriv{$privilege}='F';
                   4315:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4316:                     $thesepriv{$privilege}.=$restrictions;
                   4317:                 }
                   4318:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4319:             }
                   4320:         }
                   4321:         my $thesestr='';
1.1104    raeburn  4322:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4323: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4324: 	}
                   4325:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4326:     }
                   4327:     return ($author,$adv);
                   4328: }
                   4329: 
1.994     raeburn  4330: sub role_status {
1.1104    raeburn  4331:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4332:     my @pwhere = ();
                   4333:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4334:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4335:         unless (!defined($$role) || $$role eq '') {
                   4336:             $$where=join('.',@pwhere);
                   4337:             $$trolecode=$$role.'.'.$$where;
                   4338:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4339:             $$tstatus='is';
1.1104    raeburn  4340:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4341:                 $$tstatus='future';
1.1034    raeburn  4342:                 if ($$tstart<$now) {
                   4343:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4344:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4345:                             my (%allroles,%allgroups,$group_privs,
                   4346:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4347:                             my %userroles = (
                   4348:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4349:                             );
1.1064    raeburn  4350:                             @rolecodes = ('cm'); 
1.1002    raeburn  4351:                             my $spec=$$role.'.'.$$where;
                   4352:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4353:                             if ($$role =~ /^cr\//) {
                   4354:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4355:                                 push(@rolecodes,'cr');
1.1002    raeburn  4356:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4357:                                 push(@rolecodes,$$role);
1.1002    raeburn  4358:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4359:                                                     $env{'user.name'});
1.1064    raeburn  4360:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4361:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4362:                                 $group_privs = &unescape($group_privs);
                   4363:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4364:                                 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  4365:                                 &get_groups_roles($tdomain,$trest,
                   4366:                                                   \%course_roles,\@rolecodes,
                   4367:                                                   \%groups_roles);
1.1002    raeburn  4368:                             } else {
1.1064    raeburn  4369:                                 push(@rolecodes,$$role);
1.1002    raeburn  4370:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4371:                             }
1.1064    raeburn  4372:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4373:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4374:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4375:                         }
                   4376:                     }
1.1034    raeburn  4377:                     $$tstatus = 'is';
1.1002    raeburn  4378:                 }
1.994     raeburn  4379:             }
                   4380:             if ($$tend) {
1.1104    raeburn  4381:                 if ($$tend<$update) {
1.994     raeburn  4382:                     $$tstatus='expired';
                   4383:                 } elsif ($$tend<$now) {
                   4384:                     $$tstatus='will_not';
                   4385:                 }
                   4386:             }
                   4387:         }
                   4388:     }
                   4389: }
                   4390: 
1.1104    raeburn  4391: sub get_groups_roles {
                   4392:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4393:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4394:                   (ref($rolecodes) eq 'ARRAY') && 
                   4395:                   (ref($groups_roles) eq 'HASH')); 
                   4396:     if (keys(%{$cdom_courseroles}) > 0) {
                   4397:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4398:         if ($cdom ne '' && $cnum ne '') {
                   4399:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4400:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4401:                     my $crsrole = $1;
                   4402:                     my $crssec = $2;
                   4403:                     if ($crsrole =~ /^cr/) {
                   4404:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4405:                             push(@{$rolecodes},'cr');
                   4406:                         }
                   4407:                     } else {
                   4408:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4409:                             push(@{$rolecodes},$crsrole);
                   4410:                         }
                   4411:                     }
                   4412:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4413:                     if ($crssec ne '') {
                   4414:                         $rolekey .= "/$crssec";
                   4415:                     }
                   4416:                     $rolekey .= './';
                   4417:                     $groups_roles->{$rolekey} = $rolecodes;
                   4418:                 }
                   4419:             }
                   4420:         }
                   4421:     }
                   4422:     return;
                   4423: }
                   4424: 
                   4425: sub delete_env_groupprivs {
                   4426:     my ($where,$courseroles,$possroles) = @_;
                   4427:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4428:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4429:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4430:         %{$courseroles->{$udom}} =
                   4431:             &get_my_roles('','','userroles',['active'],
                   4432:                           $possroles,[$udom],1);
                   4433:     }
                   4434:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4435:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4436:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4437:             my $area = '/'.$cdom.'/'.$cnum;
                   4438:             my $privkey = "user.priv.$crsrole.$area";
                   4439:             if ($crssec ne '') {
                   4440:                 $privkey .= '/'.$crssec;
                   4441:             }
                   4442:             $privkey .= ".$area/$group";
                   4443:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4444:         }
                   4445:     }
                   4446:     return;
                   4447: }
                   4448: 
1.994     raeburn  4449: sub check_adhoc_privs {
1.1104    raeburn  4450:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4451:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4452:     if ($env{$cckey}) {
                   4453:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4454:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4455:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4456:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4457:         }
                   4458:     } else {
1.1088    raeburn  4459:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4460:     }
                   4461: }
                   4462: 
                   4463: sub set_adhoc_privileges {
                   4464: # role can be cc or ca
1.1088    raeburn  4465:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4466:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4467:     my $spec = $role.'.'.$area;
                   4468:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4469:                                   $env{'user.name'});
                   4470:     my %ccrole = ();
                   4471:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4472:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4473:     &appenv(\%userroles,[$role,'cm']);
                   4474:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4475:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4476:         &appenv( {'request.role'        => $spec,
                   4477:                   'request.role.domain' => $dcdom,
                   4478:                   'request.course.sec'  => ''
                   4479:                  }
                   4480:                );
                   4481:         my $tadv=0;
                   4482:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4483:         &appenv({'request.role.adv'    => $tadv});
                   4484:     }
1.994     raeburn  4485: }
                   4486: 
1.12      www      4487: # --------------------------------------------------------------- get interface
                   4488: 
                   4489: sub get {
1.131     albertel 4490:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4491:    my $items='';
1.800     albertel 4492:    foreach my $item (@$storearr) {
                   4493:        $items.=&escape($item).'&';
1.191     harris41 4494:    }
1.12      www      4495:    $items=~s/\&$//;
1.620     albertel 4496:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4497:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4498:    my $uhome=&homeserver($uname,$udomain);
                   4499: 
1.133     albertel 4500:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4501:    my @pairs=split(/\&/,$rep);
1.273     albertel 4502:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4503:      return @pairs;
                   4504:    }
1.15      www      4505:    my %returnhash=();
1.42      www      4506:    my $i=0;
1.800     albertel 4507:    foreach my $item (@$storearr) {
                   4508:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4509:       $i++;
1.191     harris41 4510:    }
1.15      www      4511:    return %returnhash;
1.27      www      4512: }
                   4513: 
                   4514: # --------------------------------------------------------------- del interface
                   4515: 
                   4516: sub del {
1.133     albertel 4517:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4518:    my $items='';
1.800     albertel 4519:    foreach my $item (@$storearr) {
                   4520:        $items.=&escape($item).'&';
1.191     harris41 4521:    }
1.984     neumanie 4522: 
1.27      www      4523:    $items=~s/\&$//;
1.620     albertel 4524:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4525:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4526:    my $uhome=&homeserver($uname,$udomain);
                   4527:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4528: }
                   4529: 
                   4530: # -------------------------------------------------------------- dump interface
                   4531: 
                   4532: sub dump {
1.1086    raeburn  4533:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4534:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4535:     if (!$uname) { $uname=$env{'user.name'}; }
                   4536:     my $uhome=&homeserver($uname,$udomain);
                   4537:     if ($regexp) {
                   4538: 	$regexp=&escape($regexp);
                   4539:     } else {
                   4540: 	$regexp='.';
                   4541:     }
1.1086    raeburn  4542:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4543:     my @pairs=split(/\&/,$rep);
                   4544:     my %returnhash=();
1.1098    foxr     4545:     if (!($rep =~ /^error/ )) {
                   4546: 	foreach my $item (@pairs) {
                   4547: 	    my ($key,$value)=split(/=/,$item,2);
                   4548: 	    $key = &unescape($key);
                   4549: 	    next if ($key =~ /^error: 2 /);
                   4550: 	    $returnhash{$key}=&thaw_unescape($value);
                   4551: 	}
1.755     albertel 4552:     }
                   4553:     return %returnhash;
1.407     www      4554: }
                   4555: 
1.1098    foxr     4556: 
1.717     albertel 4557: # --------------------------------------------------------- dumpstore interface
                   4558: 
                   4559: sub dumpstore {
                   4560:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4561:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4562:    if (!$uname) { $uname=$env{'user.name'}; }
                   4563:    my $uhome=&homeserver($uname,$udomain);
                   4564:    if ($regexp) {
                   4565:        $regexp=&escape($regexp);
                   4566:    } else {
                   4567:        $regexp='.';
                   4568:    }
                   4569:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4570:    my @pairs=split(/\&/,$rep);
                   4571:    my %returnhash=();
                   4572:    foreach my $item (@pairs) {
                   4573:        my ($key,$value)=split(/=/,$item,2);
                   4574:        next if ($key =~ /^error: 2 /);
                   4575:        $returnhash{$key}=&thaw_unescape($value);
                   4576:    }
                   4577:    return %returnhash;
1.717     albertel 4578: }
                   4579: 
1.407     www      4580: # -------------------------------------------------------------- keys interface
                   4581: 
                   4582: sub getkeys {
                   4583:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4584:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4585:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4586:    my $uhome=&homeserver($uname,$udomain);
                   4587:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4588:    my @keyarray=();
1.800     albertel 4589:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4590:       next if ($key =~ /^error: 2 /);
1.800     albertel 4591:       push(@keyarray,&unescape($key));
1.407     www      4592:    }
                   4593:    return @keyarray;
1.318     matthew  4594: }
                   4595: 
1.319     matthew  4596: # --------------------------------------------------------------- currentdump
                   4597: sub currentdump {
1.328     matthew  4598:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4599:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4600:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4601:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4602:    my $uhome = &homeserver($sname,$sdom);
                   4603:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4604:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4605:    #
1.318     matthew  4606:    my %returnhash=();
1.319     matthew  4607:    #
                   4608:    if ($rep eq "unknown_cmd") { 
                   4609:        # an old lond will not know currentdump
                   4610:        # Do a dump and make it look like a currentdump
1.822     albertel 4611:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4612:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4613:        my %hash = @tmp;
                   4614:        @tmp=();
1.424     matthew  4615:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4616:    } else {
                   4617:        my @pairs=split(/\&/,$rep);
1.800     albertel 4618:        foreach my $pair (@pairs) {
                   4619:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4620:            my ($symb,$param) = split(/:/,$key);
                   4621:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4622:                                                         &thaw_unescape($value);
1.319     matthew  4623:        }
1.191     harris41 4624:    }
1.12      www      4625:    return %returnhash;
1.424     matthew  4626: }
                   4627: 
                   4628: sub convert_dump_to_currentdump{
                   4629:     my %hash = %{shift()};
                   4630:     my %returnhash;
                   4631:     # Code ripped from lond, essentially.  The only difference
                   4632:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4633:     # we might run in to problems with parameter names =~ /^v\./
                   4634:     while (my ($key,$value) = each(%hash)) {
                   4635:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4636: 	$symb  = &unescape($symb);
                   4637: 	$param = &unescape($param);
1.424     matthew  4638:         next if ($v eq 'version' || $symb eq 'keys');
                   4639:         next if (exists($returnhash{$symb}) &&
                   4640:                  exists($returnhash{$symb}->{$param}) &&
                   4641:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4642:         $returnhash{$symb}->{$param}=$value;
                   4643:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4644:     }
                   4645:     #
                   4646:     # Remove all of the keys in the hashes which keep track of
                   4647:     # the version of the parameter.
                   4648:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4649:         # use a foreach because we are going to delete from the hash.
                   4650:         foreach my $key (keys(%$param_hash)) {
                   4651:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4652:         }
                   4653:     }
                   4654:     return \%returnhash;
1.12      www      4655: }
                   4656: 
1.627     albertel 4657: # ------------------------------------------------------ critical inc interface
                   4658: 
                   4659: sub cinc {
                   4660:     return &inc(@_,'critical');
                   4661: }
                   4662: 
1.449     matthew  4663: # --------------------------------------------------------------- inc interface
                   4664: 
                   4665: sub inc {
1.627     albertel 4666:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4667:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4668:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4669:     my $uhome=&homeserver($uname,$udomain);
                   4670:     my $items='';
                   4671:     if (! ref($store)) {
                   4672:         # got a single value, so use that instead
                   4673:         $items = &escape($store).'=&';
                   4674:     } elsif (ref($store) eq 'SCALAR') {
                   4675:         $items = &escape($$store).'=&';        
                   4676:     } elsif (ref($store) eq 'ARRAY') {
                   4677:         $items = join('=&',map {&escape($_);} @{$store});
                   4678:     } elsif (ref($store) eq 'HASH') {
                   4679:         while (my($key,$value) = each(%{$store})) {
                   4680:             $items.= &escape($key).'='.&escape($value).'&';
                   4681:         }
                   4682:     }
                   4683:     $items=~s/\&$//;
1.627     albertel 4684:     if ($critical) {
                   4685: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4686:     } else {
                   4687: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4688:     }
1.449     matthew  4689: }
                   4690: 
1.12      www      4691: # --------------------------------------------------------------- put interface
                   4692: 
                   4693: sub put {
1.134     albertel 4694:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4695:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4696:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4697:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4698:    my $items='';
1.800     albertel 4699:    foreach my $item (keys(%$storehash)) {
                   4700:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4701:    }
1.12      www      4702:    $items=~s/\&$//;
1.134     albertel 4703:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4704: }
                   4705: 
1.631     albertel 4706: # ------------------------------------------------------------ newput interface
                   4707: 
                   4708: sub newput {
                   4709:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4710:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4711:    if (!$uname) { $uname=$env{'user.name'}; }
                   4712:    my $uhome=&homeserver($uname,$udomain);
                   4713:    my $items='';
                   4714:    foreach my $key (keys(%$storehash)) {
                   4715:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4716:    }
                   4717:    $items=~s/\&$//;
                   4718:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4719: }
                   4720: 
                   4721: # ---------------------------------------------------------  putstore interface
                   4722: 
1.524     raeburn  4723: sub putstore {
1.715     albertel 4724:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4725:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4726:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4727:    my $uhome=&homeserver($uname,$udomain);
                   4728:    my $items='';
1.715     albertel 4729:    foreach my $key (keys(%$storehash)) {
                   4730:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4731:    }
1.715     albertel 4732:    $items=~s/\&$//;
1.716     albertel 4733:    my $esc_symb=&escape($symb);
                   4734:    my $esc_v=&escape($version);
1.715     albertel 4735:    my $reply =
1.716     albertel 4736:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4737: 	      $uhome);
                   4738:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4739:        # gfall back to way things use to be done
1.715     albertel 4740:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4741: 			    $uname);
1.524     raeburn  4742:    }
1.715     albertel 4743:    return $reply;
                   4744: }
                   4745: 
                   4746: sub old_putstore {
1.716     albertel 4747:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4748:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4749:     if (!$uname) { $uname=$env{'user.name'}; }
                   4750:     my $uhome=&homeserver($uname,$udomain);
                   4751:     my %newstorehash;
1.800     albertel 4752:     foreach my $item (keys(%$storehash)) {
                   4753: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4754: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4755:     }
                   4756:     my $items='';
                   4757:     my %allitems = ();
1.800     albertel 4758:     foreach my $item (keys(%newstorehash)) {
                   4759: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4760: 	    my $key = $1.':keys:'.$2;
                   4761: 	    $allitems{$key} .= $3.':';
                   4762: 	}
1.800     albertel 4763: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4764:     }
1.800     albertel 4765:     foreach my $item (keys(%allitems)) {
                   4766: 	$allitems{$item} =~ s/\:$//;
                   4767: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4768:     }
                   4769:     $items=~s/\&$//;
                   4770:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4771: }
                   4772: 
1.47      www      4773: # ------------------------------------------------------ critical put interface
                   4774: 
                   4775: sub cput {
1.134     albertel 4776:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4777:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4778:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4779:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4780:    my $items='';
1.800     albertel 4781:    foreach my $item (keys(%$storehash)) {
                   4782:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4783:    }
1.47      www      4784:    $items=~s/\&$//;
1.134     albertel 4785:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4786: }
                   4787: 
                   4788: # -------------------------------------------------------------- eget interface
                   4789: 
                   4790: sub eget {
1.133     albertel 4791:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4792:    my $items='';
1.800     albertel 4793:    foreach my $item (@$storearr) {
                   4794:        $items.=&escape($item).'&';
1.191     harris41 4795:    }
1.12      www      4796:    $items=~s/\&$//;
1.620     albertel 4797:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4798:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4799:    my $uhome=&homeserver($uname,$udomain);
                   4800:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4801:    my @pairs=split(/\&/,$rep);
                   4802:    my %returnhash=();
1.42      www      4803:    my $i=0;
1.800     albertel 4804:    foreach my $item (@$storearr) {
                   4805:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4806:       $i++;
1.191     harris41 4807:    }
1.12      www      4808:    return %returnhash;
                   4809: }
                   4810: 
1.667     albertel 4811: # ------------------------------------------------------------ tmpput interface
                   4812: sub tmpput {
1.802     raeburn  4813:     my ($storehash,$server,$context)=@_;
1.667     albertel 4814:     my $items='';
1.800     albertel 4815:     foreach my $item (keys(%$storehash)) {
                   4816: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4817:     }
                   4818:     $items=~s/\&$//;
1.802     raeburn  4819:     if (defined($context)) {
                   4820:         $items .= ':'.&escape($context);
                   4821:     }
1.667     albertel 4822:     return &reply("tmpput:$items",$server);
                   4823: }
                   4824: 
                   4825: # ------------------------------------------------------------ tmpget interface
                   4826: sub tmpget {
1.688     albertel 4827:     my ($token,$server)=@_;
                   4828:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4829:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4830:     my %returnhash;
                   4831:     foreach my $item (split(/\&/,$rep)) {
                   4832: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4833:         next if ($key =~ /^error: 2 /);
1.667     albertel 4834: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4835:     }
                   4836:     return %returnhash;
                   4837: }
                   4838: 
1.1113    raeburn  4839: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4840: sub tmpdel {
                   4841:     my ($token,$server)=@_;
                   4842:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4843:     return &reply("tmpdel:$token",$server);
                   4844: }
                   4845: 
1.765     albertel 4846: # -------------------------------------------------- portfolio access checking
                   4847: 
                   4848: sub portfolio_access {
1.766     albertel 4849:     my ($requrl) = @_;
1.765     albertel 4850:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4851:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4852:     if ($result) {
                   4853:         my %setters;
                   4854:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4855:             my ($startblock,$endblock) =
                   4856:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4857:             if ($startblock && $endblock) {
                   4858:                 return 'B';
                   4859:             }
                   4860:         } else {
                   4861:             my ($startblock,$endblock) =
                   4862:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4863:             if ($startblock && $endblock) {
                   4864:                 return 'B';
                   4865:             }
                   4866:         }
                   4867:     }
1.765     albertel 4868:     if ($result eq 'ok') {
1.766     albertel 4869:        return 'F';
1.765     albertel 4870:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4871:        return 'A';
1.765     albertel 4872:     }
1.766     albertel 4873:     return '';
1.765     albertel 4874: }
                   4875: 
                   4876: sub get_portfolio_access {
1.767     albertel 4877:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4878: 
                   4879:     if (!ref($access_hash)) {
                   4880: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4881: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4882: 						   $file_name);
                   4883: 	$access_hash = $access_controls{$file_name};
                   4884:     }
                   4885: 
1.765     albertel 4886:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4887:     my $now = time;
                   4888:     if (ref($access_hash) eq 'HASH') {
                   4889:         foreach my $key (keys(%{$access_hash})) {
                   4890:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4891:             if ($start > $now) {
                   4892:                 next;
                   4893:             }
                   4894:             if ($end && $end<$now) {
                   4895:                 next;
                   4896:             }
                   4897:             if ($scope eq 'public') {
                   4898:                 $public = $key;
                   4899:                 last;
                   4900:             } elsif ($scope eq 'guest') {
                   4901:                 $guest = $key;
                   4902:             } elsif ($scope eq 'domains') {
                   4903:                 push(@domains,$key);
                   4904:             } elsif ($scope eq 'users') {
                   4905:                 push(@users,$key);
                   4906:             } elsif ($scope eq 'course') {
                   4907:                 push(@courses,$key);
                   4908:             } elsif ($scope eq 'group') {
                   4909:                 push(@groups,$key);
                   4910:             }
                   4911:         }
                   4912:         if ($public) {
                   4913:             return 'ok';
                   4914:         }
                   4915:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4916:             if ($guest) {
                   4917:                 return $guest;
                   4918:             }
                   4919:         } else {
                   4920:             if (@domains > 0) {
                   4921:                 foreach my $domkey (@domains) {
                   4922:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4923:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4924:                             return 'ok';
                   4925:                         }
                   4926:                     }
                   4927:                 }
                   4928:             }
                   4929:             if (@users > 0) {
                   4930:                 foreach my $userkey (@users) {
1.865     raeburn  4931:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4932:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4933:                             if (ref($item) eq 'HASH') {
                   4934:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4935:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4936:                                     return 'ok';
                   4937:                                 }
                   4938:                             }
                   4939:                         }
                   4940:                     } 
1.765     albertel 4941:                 }
                   4942:             }
                   4943:             my %roleshash;
                   4944:             my @courses_and_groups = @courses;
                   4945:             push(@courses_and_groups,@groups); 
                   4946:             if (@courses_and_groups > 0) {
                   4947:                 my (%allgroups,%allroles); 
                   4948:                 my ($start,$end,$role,$sec,$group);
                   4949:                 foreach my $envkey (%env) {
1.1060    raeburn  4950:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4951:                         my $cid = $2.'_'.$3; 
                   4952:                         if ($1 eq 'gr') {
                   4953:                             $group = $4;
                   4954:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4955:                         } else {
                   4956:                             if ($4 eq '') {
                   4957:                                 $sec = 'none';
                   4958:                             } else {
                   4959:                                 $sec = $4;
                   4960:                             }
                   4961:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4962:                         }
1.811     albertel 4963:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4964:                         my $cid = $2.'_'.$3;
                   4965:                         if ($4 eq '') {
                   4966:                             $sec = 'none';
                   4967:                         } else {
                   4968:                             $sec = $4;
                   4969:                         }
                   4970:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4971:                     }
                   4972:                 }
                   4973:                 if (keys(%allroles) == 0) {
                   4974:                     return;
                   4975:                 }
                   4976:                 foreach my $key (@courses_and_groups) {
                   4977:                     my %content = %{$$access_hash{$key}};
                   4978:                     my $cnum = $content{'number'};
                   4979:                     my $cdom = $content{'domain'};
                   4980:                     my $cid = $cdom.'_'.$cnum;
                   4981:                     if (!exists($allroles{$cid})) {
                   4982:                         next;
                   4983:                     }    
                   4984:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4985:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4986:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4987:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4988:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4989:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4990:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4991:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4992:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4993:                                         if (grep/^all$/,@sections) {
                   4994:                                             return 'ok';
                   4995:                                         } else {
                   4996:                                             if (grep/^$sec$/,@sections) {
                   4997:                                                 return 'ok';
                   4998:                                             }
                   4999:                                         }
                   5000:                                     }
                   5001:                                 }
                   5002:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5003:                                     if (grep/^none$/,@groups) {
                   5004:                                         return 'ok';
                   5005:                                     }
                   5006:                                 } else {
                   5007:                                     if (grep/^all$/,@groups) {
                   5008:                                         return 'ok';
                   5009:                                     } 
                   5010:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5011:                                         if (grep/^$group$/,@groups) {
                   5012:                                             return 'ok';
                   5013:                                         }
                   5014:                                     }
                   5015:                                 } 
                   5016:                             }
                   5017:                         }
                   5018:                     }
                   5019:                 }
                   5020:             }
                   5021:             if ($guest) {
                   5022:                 return $guest;
                   5023:             }
                   5024:         }
                   5025:     }
                   5026:     return;
                   5027: }
                   5028: 
                   5029: sub course_group_datechecker {
                   5030:     my ($dates,$now,$status) = @_;
                   5031:     my ($start,$end) = split(/\./,$dates);
                   5032:     if (!$start && !$end) {
                   5033:         return 'ok';
                   5034:     }
                   5035:     if (grep/^active$/,@{$status}) {
                   5036:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5037:             return 'ok';
                   5038:         }
                   5039:     }
                   5040:     if (grep/^previous$/,@{$status}) {
                   5041:         if ($end > $now ) {
                   5042:             return 'ok';
                   5043:         }
                   5044:     }
                   5045:     if (grep/^future$/,@{$status}) {
                   5046:         if ($start > $now) {
                   5047:             return 'ok';
                   5048:         }
                   5049:     }
                   5050:     return; 
                   5051: }
                   5052: 
                   5053: sub parse_portfolio_url {
                   5054:     my ($url) = @_;
                   5055: 
                   5056:     my ($type,$udom,$unum,$group,$file_name);
                   5057:     
1.823     albertel 5058:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5059: 	$type = 1;
                   5060:         $udom = $1;
                   5061:         $unum = $2;
                   5062:         $file_name = $3;
1.823     albertel 5063:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5064: 	$type = 2;
                   5065:         $udom = $1;
                   5066:         $unum = $2;
                   5067:         $group = $3;
                   5068:         $file_name = $3.'/'.$4;
                   5069:     }
                   5070:     if (wantarray) {
                   5071: 	return ($type,$udom,$unum,$file_name,$group);
                   5072:     }
                   5073:     return $type;
                   5074: }
                   5075: 
                   5076: sub is_portfolio_url {
                   5077:     my ($url) = @_;
                   5078:     return scalar(&parse_portfolio_url($url));
                   5079: }
                   5080: 
1.798     raeburn  5081: sub is_portfolio_file {
                   5082:     my ($file) = @_;
1.820     raeburn  5083:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5084:         return 1;
                   5085:     }
                   5086:     return;
                   5087: }
                   5088: 
1.976     raeburn  5089: sub usertools_access {
1.1084    raeburn  5090:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5091:     my ($access,%tools);
                   5092:     if ($context eq '') {
                   5093:         $context = 'tools';
                   5094:     }
                   5095:     if ($context eq 'requestcourses') {
                   5096:         %tools = (
                   5097:                       official   => 1,
                   5098:                       unofficial => 1,
1.1006    raeburn  5099:                       community  => 1,
1.985     raeburn  5100:                  );
                   5101:     } else {
                   5102:         %tools = (
                   5103:                       aboutme   => 1,
                   5104:                       blog      => 1,
                   5105:                       portfolio => 1,
                   5106:                  );
                   5107:     }
1.976     raeburn  5108:     return if (!defined($tools{$tool}));
                   5109: 
                   5110:     if ((!defined($udom)) || (!defined($uname))) {
                   5111:         $udom = $env{'user.domain'};
                   5112:         $uname = $env{'user.name'};
                   5113:     }
                   5114: 
1.978     raeburn  5115:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5116:         if ($action ne 'reload') {
1.985     raeburn  5117:             if ($context eq 'requestcourses') {
                   5118:                 return $env{'environment.canrequest.'.$tool};
                   5119:             } else {
                   5120:                 return $env{'environment.availabletools.'.$tool};
                   5121:             }
                   5122:         }
1.976     raeburn  5123:     }
                   5124: 
                   5125:     my ($toolstatus,$inststatus);
                   5126: 
1.985     raeburn  5127:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5128:          ($action ne 'reload')) {
                   5129:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5130:         $inststatus = $env{'environment.inststatus'};
                   5131:     } else {
1.1084    raeburn  5132:         if (ref($userenvref) eq 'HASH') {
                   5133:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5134:             $inststatus = $userenvref->{'inststatus'};
                   5135:         } else {
                   5136:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5137:             $toolstatus = $userenv{$context.'.'.$tool};
                   5138:             $inststatus = $userenv{'inststatus'};
                   5139:         }
1.976     raeburn  5140:     }
                   5141: 
                   5142:     if ($toolstatus ne '') {
                   5143:         if ($toolstatus) {
                   5144:             $access = 1;
                   5145:         } else {
                   5146:             $access = 0;
                   5147:         }
                   5148:         return $access;
                   5149:     }
                   5150: 
1.1084    raeburn  5151:     my ($is_adv,%domdef);
                   5152:     if (ref($is_advref) eq 'HASH') {
                   5153:         $is_adv = $is_advref->{'is_adv'};
                   5154:     } else {
                   5155:         $is_adv = &is_advanced_user($udom,$uname);
                   5156:     }
                   5157:     if (ref($domdefref) eq 'HASH') {
                   5158:         %domdef = %{$domdefref};
                   5159:     } else {
                   5160:         %domdef = &get_domain_defaults($udom);
                   5161:     }
1.976     raeburn  5162:     if (ref($domdef{$tool}) eq 'HASH') {
                   5163:         if ($is_adv) {
                   5164:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5165:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5166:                     $access = 1;
                   5167:                 } else {
                   5168:                     $access = 0;
                   5169:                 }
                   5170:                 return $access;
                   5171:             }
                   5172:         }
                   5173:         if ($inststatus ne '') {
                   5174:             my ($hasaccess,$hasnoaccess);
                   5175:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5176:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5177:                     if ($domdef{$tool}{$affiliation}) {
                   5178:                         $hasaccess = 1;
                   5179:                     } else {
                   5180:                         $hasnoaccess = 1;
                   5181:                     }
                   5182:                 }
                   5183:             }
                   5184:             if ($hasaccess || $hasnoaccess) {
                   5185:                 if ($hasaccess) {
                   5186:                     $access = 1;
                   5187:                 } elsif ($hasnoaccess) {
                   5188:                     $access = 0; 
                   5189:                 }
                   5190:                 return $access;
                   5191:             }
                   5192:         } else {
                   5193:             if ($domdef{$tool}{'default'} ne '') {
                   5194:                 if ($domdef{$tool}{'default'}) {
                   5195:                     $access = 1;
                   5196:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5197:                     $access = 0;
                   5198:                 }
                   5199:                 return $access;
                   5200:             }
                   5201:         }
                   5202:     } else {
1.985     raeburn  5203:         if ($context eq 'tools') {
                   5204:             $access = 1;
                   5205:         } else {
                   5206:             $access = 0;
                   5207:         }
1.976     raeburn  5208:         return $access;
                   5209:     }
                   5210: }
                   5211: 
1.1050    raeburn  5212: sub is_course_owner {
                   5213:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5214:     if (($udom eq '') || ($uname eq '')) {
                   5215:         $udom = $env{'user.domain'};
                   5216:         $uname = $env{'user.name'};
                   5217:     }
                   5218:     unless (($udom eq '') || ($uname eq '')) {
                   5219:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5220:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5221:                 return 1;
                   5222:             } else {
                   5223:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5224:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5225:                     return 1;
                   5226:                 }
                   5227:             }
                   5228:         }
                   5229:     }
                   5230:     return;
                   5231: }
                   5232: 
1.976     raeburn  5233: sub is_advanced_user {
                   5234:     my ($udom,$uname) = @_;
1.1085    raeburn  5235:     if ($udom ne '' && $uname ne '') {
                   5236:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5237:             return $env{'user.adv'};  
                   5238:         }
                   5239:     }
1.976     raeburn  5240:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5241:     my %allroles;
                   5242:     my $is_adv;
                   5243:     foreach my $role (keys(%roleshash)) {
                   5244:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5245:         my $area = '/'.$tdomain.'/'.$trest;
                   5246:         if ($sec ne '') {
                   5247:             $area .= '/'.$sec;
                   5248:         }
                   5249:         if (($area ne '') && ($trole ne '')) {
                   5250:             my $spec=$trole.'.'.$area;
                   5251:             if ($trole =~ /^cr\//) {
                   5252:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5253:             } elsif ($trole ne 'gr') {
                   5254:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5255:             }
                   5256:         }
                   5257:     }
                   5258:     foreach my $role (keys(%allroles)) {
                   5259:         last if ($is_adv);
                   5260:         foreach my $item (split(/:/,$allroles{$role})) {
                   5261:             if ($item ne '') {
                   5262:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5263:                 if ($privilege eq 'adv') {
                   5264:                     $is_adv = 1;
                   5265:                     last;
                   5266:                 }
                   5267:             }
                   5268:         }
                   5269:     }
                   5270:     return $is_adv;
                   5271: }
1.798     raeburn  5272: 
1.1035    raeburn  5273: sub check_can_request {
1.1036    raeburn  5274:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5275:     my $canreq = 0;
                   5276:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5277:     my @options = ('approval','validate','autolimit');
                   5278:     my $optregex = join('|',@options);
                   5279:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5280:         foreach my $type (@{$types}) {
                   5281:             if (&usertools_access($env{'user.name'},
                   5282:                                   $env{'user.domain'},
                   5283:                                   $type,undef,'requestcourses')) {
                   5284:                 $canreq ++;
1.1036    raeburn  5285:                 if (ref($request_domains) eq 'HASH') {
                   5286:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5287:                 }
1.1035    raeburn  5288:                 if ($dom eq $env{'user.domain'}) {
                   5289:                     $can_request->{$type} = 1;
                   5290:                 }
                   5291:             }
                   5292:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5293:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5294:                 if (@curr > 0) {
1.1036    raeburn  5295:                     foreach my $item (@curr) {
                   5296:                         if (ref($request_domains) eq 'HASH') {
                   5297:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5298:                             if ($otherdom ne '') {
                   5299:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5300:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5301:                                         push(@{$request_domains->{$type}},$otherdom);
                   5302:                                     }
                   5303:                                 } else {
                   5304:                                     push(@{$request_domains->{$type}},$otherdom);
                   5305:                                 }
                   5306:                             }
                   5307:                         }
                   5308:                     }
                   5309:                     unless($dom eq $env{'user.domain'}) {
                   5310:                         $canreq ++;
1.1035    raeburn  5311:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5312:                             $can_request->{$type} = 1;
                   5313:                         }
                   5314:                     }
                   5315:                 }
                   5316:             }
                   5317:         }
                   5318:     }
                   5319:     return $canreq;
                   5320: }
                   5321: 
1.341     www      5322: # ---------------------------------------------- Custom access rule evaluation
                   5323: 
                   5324: sub customaccess {
                   5325:     my ($priv,$uri)=@_;
1.807     albertel 5326:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5327:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5328:     $udom = &LONCAPA::clean_domain($udom);
                   5329:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5330:     my $access=0;
1.800     albertel 5331:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5332: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5333: 	if ($type eq 'user') {
                   5334: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5335: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5336: 		if ($tdom) {
                   5337: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5338: 		}
1.896     albertel 5339: 		if ($tuname) {
                   5340: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5341: 		}
                   5342: 		$access=($effect eq 'allow');
                   5343: 		last;
                   5344: 	    }
                   5345: 	} else {
                   5346: 	    if ($role) {
                   5347: 		if ($role ne $urole) { next; }
                   5348: 	    }
                   5349: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5350: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5351: 		if ($tdom) {
                   5352: 		    if ($tdom ne $udom) { next; }
                   5353: 		}
                   5354: 		if ($tcrs) {
                   5355: 		    if ($tcrs ne $ucrs) { next; }
                   5356: 		}
                   5357: 		if ($tsec) {
                   5358: 		    if ($tsec ne $usec) { next; }
                   5359: 		}
                   5360: 		$access=($effect eq 'allow');
                   5361: 		last;
                   5362: 	    }
                   5363: 	    if ($realm eq '' && $role eq '') {
                   5364: 		$access=($effect eq 'allow');
                   5365: 	    }
1.402     bowersj2 5366: 	}
1.341     www      5367:     }
                   5368:     return $access;
                   5369: }
                   5370: 
1.103     harris41 5371: # ------------------------------------------------- Check for a user privilege
1.12      www      5372: 
                   5373: sub allowed {
1.810     raeburn  5374:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5375:     my $ver_orguri=$uri;
1.439     www      5376:     $uri=&deversion($uri);
1.152     www      5377:     my $orguri=$uri;
1.52      www      5378:     $uri=&declutter($uri);
1.809     raeburn  5379: 
1.810     raeburn  5380:     if ($priv eq 'evb') {
                   5381: # Evade communication block restrictions for specified role in a course
                   5382:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5383:             return $1;
                   5384:         } else {
                   5385:             return;
                   5386:         }
                   5387:     }
                   5388: 
1.620     albertel 5389:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5390: # Free bre access to adm and meta resources
1.775     albertel 5391:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5392: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5393: 	&& ($priv eq 'bre')) {
1.14      www      5394: 	return 'F';
1.159     www      5395:     }
                   5396: 
1.545     banghart 5397: # Free bre access to user's own portfolio contents
1.714     raeburn  5398:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5399:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5400: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5401:         my %setters;
                   5402:         my ($startblock,$endblock) = 
                   5403:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5404:         if ($startblock && $endblock) {
                   5405:             return 'B';
                   5406:         } else {
                   5407:             return 'F';
                   5408:         }
1.545     banghart 5409:     }
                   5410: 
1.762     raeburn  5411: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5412:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5413:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5414:         if (exists($env{'request.course.id'})) {
                   5415:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5416:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5417:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5418:                 my $courseprivid=$env{'request.course.id'};
                   5419:                 $courseprivid=~s/\_/\//;
                   5420:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5421:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5422:                     return $1; 
1.762     raeburn  5423:                 } else {
                   5424:                     if ($env{'request.course.sec'}) {
                   5425:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5426:                     }
                   5427:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5428:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5429:                         return $2;
                   5430:                     }
1.714     raeburn  5431:                 }
                   5432:             }
                   5433:         }
                   5434:     }
                   5435: 
1.159     www      5436: # Free bre to public access
                   5437: 
                   5438:     if ($priv eq 'bre') {
1.238     www      5439:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5440: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5441:            return 'F'; 
                   5442:         }
1.238     www      5443:         if ($copyright eq 'priv') {
                   5444:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5445: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5446: 		return '';
                   5447:             }
                   5448:         }
                   5449:         if ($copyright eq 'domain') {
                   5450:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5451: 	    unless (($env{'user.domain'} eq $1) ||
                   5452:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5453: 		return '';
                   5454:             }
1.262     matthew  5455:         }
1.620     albertel 5456:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5457:             # Library role, so allow browsing of resources in this domain.
                   5458:             return 'F';
1.238     www      5459:         }
1.341     www      5460:         if ($copyright eq 'custom') {
                   5461: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5462:         }
1.14      www      5463:     }
1.264     matthew  5464:     # Domain coordinator is trying to create a course
1.620     albertel 5465:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5466:         # uri is the requested domain in this case.
                   5467:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5468:         # a role of dc for the domain in question.
1.620     albertel 5469:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5470:     }
1.29      www      5471: 
1.52      www      5472:     my $thisallowed='';
                   5473:     my $statecond=0;
                   5474:     my $courseprivid='';
                   5475: 
1.1039    raeburn  5476:     my $ownaccess;
1.1043    raeburn  5477:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5478:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5479:         if ($uri eq '') {
                   5480:             $ownaccess = 1;
                   5481:         } else {
                   5482:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5483:                 my $udom = $env{'user.domain'};
                   5484:                 my $uname = $env{'user.name'};
                   5485:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5486:                     $ownaccess = 1;
1.1040    raeburn  5487:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5488:                     unless ($uri =~ m{\.\./}) {
                   5489:                         $ownaccess = 1;
                   5490:                     }
                   5491:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5492:                     my $now = time;
                   5493:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5494:                         my $adom = $1;
                   5495:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5496:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5497:                                 my ($start,$end) = split('.',$env{$key});
                   5498:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5499:                                     $ownaccess = 1;
                   5500:                                     last;
                   5501:                                 }
                   5502:                             }
                   5503:                         }
                   5504:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5505:                         my $adom = $1;
                   5506:                         my $aname = $2;
1.1042    raeburn  5507:                         foreach my $role ('ca','aa') { 
                   5508:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5509:                                 my ($start,$end) =
                   5510:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5511:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5512:                                     $ownaccess = 1;
                   5513:                                     last;
                   5514:                                 }
1.1039    raeburn  5515:                             }
                   5516:                         }
                   5517:                     }
                   5518:                 }
                   5519:             }
                   5520:         }
                   5521:     }
                   5522: 
1.52      www      5523: # Course
                   5524: 
1.620     albertel 5525:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5526:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5527:             $thisallowed.=$1;
                   5528:         }
1.52      www      5529:     }
1.29      www      5530: 
1.52      www      5531: # Domain
                   5532: 
1.620     albertel 5533:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5534:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5535:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5536:             $thisallowed.=$1;
                   5537:         }
1.12      www      5538:     }
1.52      www      5539: 
                   5540: # Course: uri itself is a course
1.66      www      5541:     my $courseuri=$uri;
                   5542:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5543:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5544: 
1.620     albertel 5545:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5546:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5547:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5548:             $thisallowed.=$1;
                   5549:         }
1.12      www      5550:     }
1.29      www      5551: 
1.665     albertel 5552: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5553: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5554:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5555: 	$thisallowed='';
1.671     raeburn  5556:         my ($match)=&is_on_map($uri);
                   5557:         if ($match) {
                   5558:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5559:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5560:                 $thisallowed.=$1;
                   5561:             }
                   5562:         } else {
1.705     albertel 5563:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5564:             if ($refuri) {
                   5565:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5566:                     $thisallowed='F';
1.671     raeburn  5567:                 } else {
                   5568:                     $refuri=&declutter($refuri);
                   5569:                     my ($match) = &is_on_map($refuri);
                   5570:                     if ($match) {
                   5571:                         $thisallowed='F';
                   5572:                     }
1.669     raeburn  5573:                 }
1.671     raeburn  5574:             }
                   5575:         }
1.314     www      5576:     }
1.492     albertel 5577: 
1.766     albertel 5578:     if ($priv eq 'bre'
                   5579: 	&& $thisallowed ne 'F' 
                   5580: 	&& $thisallowed ne '2'
                   5581: 	&& &is_portfolio_url($uri)) {
                   5582: 	$thisallowed = &portfolio_access($uri);
                   5583:     }
                   5584:     
1.52      www      5585: # Full access at system, domain or course-wide level? Exit.
1.29      www      5586:     if ($thisallowed=~/F/) {
                   5587: 	return 'F';
                   5588:     }
                   5589: 
1.52      www      5590: # If this is generating or modifying users, exit with special codes
1.29      www      5591: 
1.643     www      5592:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5593: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5594: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5595: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5596: 	    unless ($auname) { return $thisallowed; }
                   5597: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5598: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5599: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5600: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5601: 	}
1.52      www      5602: 	return $thisallowed;
                   5603:     }
                   5604: #
1.103     harris41 5605: # Gathered so far: system, domain and course wide privileges
1.52      www      5606: #
                   5607: # Course: See if uri or referer is an individual resource that is part of 
                   5608: # the course
                   5609: 
1.620     albertel 5610:     if ($env{'request.course.id'}) {
1.232     www      5611: 
1.620     albertel 5612:        $courseprivid=$env{'request.course.id'};
                   5613:        if ($env{'request.course.sec'}) {
                   5614:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5615:        }
                   5616:        $courseprivid=~s/\_/\//;
                   5617:        my $checkreferer=1;
1.232     www      5618:        my ($match,$cond)=&is_on_map($uri);
                   5619:        if ($match) {
                   5620:            $statecond=$cond;
1.620     albertel 5621:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5622:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5623:                $thisallowed.=$1;
                   5624:                $checkreferer=0;
                   5625:            }
1.29      www      5626:        }
1.83      www      5627:        
1.148     www      5628:        if ($checkreferer) {
1.620     albertel 5629: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5630:             unless ($refuri) {
1.800     albertel 5631:                 foreach my $key (keys(%env)) {
                   5632: 		    if ($key=~/^httpref\..*\*/) {
                   5633: 			my $pattern=$key;
1.156     www      5634:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5635:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5636:                         $pattern=~s/\//\\\//g;
1.152     www      5637:                         if ($orguri=~/$pattern/) {
1.800     albertel 5638: 			    $refuri=$env{$key};
1.148     www      5639:                         }
                   5640:                     }
1.191     harris41 5641:                 }
1.148     www      5642:             }
1.232     www      5643: 
1.148     www      5644:          if ($refuri) { 
1.152     www      5645: 	  $refuri=&declutter($refuri);
1.232     www      5646:           my ($match,$cond)=&is_on_map($refuri);
                   5647:             if ($match) {
                   5648:               my $refstatecond=$cond;
1.620     albertel 5649:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5650:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5651:                   $thisallowed.=$1;
1.53      www      5652:                   $uri=$refuri;
                   5653:                   $statecond=$refstatecond;
1.52      www      5654:               }
                   5655:           }
1.148     www      5656:         }
1.29      www      5657:        }
1.52      www      5658:    }
1.29      www      5659: 
1.52      www      5660: #
1.103     harris41 5661: # Gathered now: all privileges that could apply, and condition number
1.52      www      5662: # 
                   5663: #
                   5664: # Full or no access?
                   5665: #
1.29      www      5666: 
1.52      www      5667:     if ($thisallowed=~/F/) {
                   5668: 	return 'F';
                   5669:     }
1.29      www      5670: 
1.52      www      5671:     unless ($thisallowed) {
                   5672:         return '';
                   5673:     }
1.29      www      5674: 
1.52      www      5675: # Restrictions exist, deal with them
                   5676: #
                   5677: #   C:according to course preferences
                   5678: #   R:according to resource settings
                   5679: #   L:unless locked
                   5680: #   X:according to user session state
                   5681: #
                   5682: 
                   5683: # Possibly locked functionality, check all courses
1.54      www      5684: # Locks might take effect only after 10 minutes cache expiration for other
                   5685: # courses, and 2 minutes for current course
1.52      www      5686: 
                   5687:     my $envkey;
                   5688:     if ($thisallowed=~/L/) {
1.1000    raeburn  5689:         foreach $envkey (keys(%env)) {
1.54      www      5690:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5691:                my $courseid=$2;
                   5692:                my $roleid=$1.'.'.$2;
1.92      www      5693:                $courseid=~s/^\///;
1.54      www      5694:                my $expiretime=600;
1.620     albertel 5695:                if ($env{'request.role'} eq $roleid) {
1.54      www      5696: 		  $expiretime=120;
                   5697:                }
                   5698: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5699:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5700:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5701: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5702:                }
1.620     albertel 5703:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5704:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5705: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5706:                        &log($env{'user.domain'},$env{'user.name'},
                   5707:                             $env{'user.home'},
1.57      www      5708:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5709:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5710:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5711: 		       return '';
                   5712:                    }
                   5713:                }
1.620     albertel 5714:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5715:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5716: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5717:                        &log($env{'user.domain'},$env{'user.name'},
                   5718:                             $env{'user.home'},
1.57      www      5719:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5720:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5721:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5722: 		       return '';
                   5723:                    }
                   5724:                }
                   5725: 	   }
1.29      www      5726:        }
1.52      www      5727:     }
                   5728:    
                   5729: #
                   5730: # Rest of the restrictions depend on selected course
                   5731: #
                   5732: 
1.620     albertel 5733:     unless ($env{'request.course.id'}) {
1.766     albertel 5734: 	if ($thisallowed eq 'A') {
                   5735: 	    return 'A';
1.814     raeburn  5736:         } elsif ($thisallowed eq 'B') {
                   5737:             return 'B';
1.766     albertel 5738: 	} else {
                   5739: 	    return '1';
                   5740: 	}
1.52      www      5741:     }
1.29      www      5742: 
1.52      www      5743: #
                   5744: # Now user is definitely in a course
                   5745: #
1.53      www      5746: 
                   5747: 
                   5748: # Course preferences
                   5749: 
                   5750:    if ($thisallowed=~/C/) {
1.620     albertel 5751:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5752:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5753:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5754: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5755: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5756: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5757: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5758: 			$env{'request.course.id'});
                   5759: 	   }
1.237     www      5760:            return '';
                   5761:        }
                   5762: 
1.620     albertel 5763:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5764: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5765: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5766: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5767: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5768: 			$env{'request.course.id'});
                   5769: 	   }
1.54      www      5770:            return '';
                   5771:        }
1.53      www      5772:    }
                   5773: 
                   5774: # Resource preferences
                   5775: 
                   5776:    if ($thisallowed=~/R/) {
1.620     albertel 5777:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5778:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5779: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5780: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5781: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5782: 	   }
                   5783: 	   return '';
1.54      www      5784:        }
1.53      www      5785:    }
1.30      www      5786: 
1.246     www      5787: # Restricted by state or randomout?
1.30      www      5788: 
1.52      www      5789:    if ($thisallowed=~/X/) {
1.620     albertel 5790:       if ($env{'acc.randomout'}) {
1.579     albertel 5791: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5792:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5793:             return ''; 
                   5794:          }
1.247     www      5795:       }
                   5796:       if (&condval($statecond)) {
1.52      www      5797: 	 return '2';
                   5798:       } else {
                   5799:          return '';
                   5800:       }
                   5801:    }
1.30      www      5802: 
1.766     albertel 5803:     if ($thisallowed eq 'A') {
                   5804: 	return 'A';
1.814     raeburn  5805:     } elsif ($thisallowed eq 'B') {
                   5806:         return 'B';
1.766     albertel 5807:     }
1.52      www      5808:    return 'F';
1.232     www      5809: }
                   5810: 
1.710     albertel 5811: sub split_uri_for_cond {
                   5812:     my $uri=&deversion(&declutter(shift));
                   5813:     my @uriparts=split(/\//,$uri);
                   5814:     my $filename=pop(@uriparts);
                   5815:     my $pathname=join('/',@uriparts);
                   5816:     return ($pathname,$filename);
                   5817: }
1.232     www      5818: # --------------------------------------------------- Is a resource on the map?
                   5819: 
                   5820: sub is_on_map {
1.710     albertel 5821:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5822:     #Trying to find the conditional for the file
1.620     albertel 5823:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5824: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5825:     if ($match) {
1.289     bowersj2 5826: 	return (1,$1);
                   5827:     } else {
1.434     www      5828: 	return (0,0);
1.289     bowersj2 5829:     }
1.12      www      5830: }
                   5831: 
1.427     www      5832: # --------------------------------------------------------- Get symb from alias
                   5833: 
                   5834: sub get_symb_from_alias {
                   5835:     my $symb=shift;
                   5836:     my ($map,$resid,$url)=&decode_symb($symb);
                   5837: # Already is a symb
                   5838:     if ($url) { return $symb; }
                   5839: # Must be an alias
                   5840:     my $aliassymb='';
                   5841:     my %bighash;
1.620     albertel 5842:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5843:                             &GDBM_READER(),0640)) {
                   5844:         my $rid=$bighash{'mapalias_'.$symb};
                   5845: 	if ($rid) {
                   5846: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5847: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5848: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5849: 	}
                   5850:         untie %bighash;
                   5851:     }
                   5852:     return $aliassymb;
                   5853: }
                   5854: 
1.12      www      5855: # ----------------------------------------------------------------- Define Role
                   5856: 
                   5857: sub definerole {
                   5858:   if (allowed('mcr','/')) {
                   5859:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5860:     foreach my $role (split(':',$sysrole)) {
                   5861: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5862:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5863:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5864: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5865:                return "refused:s:$crole&$cqual"; 
                   5866:             }
                   5867:         }
1.191     harris41 5868:     }
1.800     albertel 5869:     foreach my $role (split(':',$domrole)) {
                   5870: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5871:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5872:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5873: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5874:                return "refused:d:$crole&$cqual"; 
                   5875:             }
                   5876:         }
1.191     harris41 5877:     }
1.800     albertel 5878:     foreach my $role (split(':',$courole)) {
                   5879: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5880:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5881:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5882: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5883:                return "refused:c:$crole&$cqual"; 
                   5884:             }
                   5885:         }
1.191     harris41 5886:     }
1.620     albertel 5887:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5888:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5889: 	        "rolesdef_$rolename=".
                   5890:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5891:     return reply($command,$env{'user.home'});
1.12      www      5892:   } else {
                   5893:     return 'refused';
                   5894:   }
1.105     harris41 5895: }
                   5896: 
                   5897: # ---------------- Make a metadata query against the network of library servers
                   5898: 
                   5899: sub metadata_query {
1.244     matthew  5900:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5901:     my %rhash;
1.845     albertel 5902:     my %libserv = &all_library();
1.244     matthew  5903:     my @server_list = (defined($server_array) ? @$server_array
                   5904:                                               : keys(%libserv) );
                   5905:     for my $server (@server_list) {
1.118     harris41 5906: 	unless ($custom or $customshow) {
                   5907: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5908: 	    $rhash{$server}=$reply;
                   5909: 	}
                   5910: 	else {
                   5911: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5912: 			     &escape($custom).':'.&escape($customshow),
                   5913: 			     $server);
                   5914: 	    $rhash{$server}=$reply;
                   5915: 	}
1.112     harris41 5916:     }
1.118     harris41 5917:     return \%rhash;
1.240     www      5918: }
                   5919: 
                   5920: # ----------------------------------------- Send log queries and wait for reply
                   5921: 
                   5922: sub log_query {
                   5923:     my ($uname,$udom,$query,%filters)=@_;
                   5924:     my $uhome=&homeserver($uname,$udom);
                   5925:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5926:     my $uhost=&hostname($uhome);
1.800     albertel 5927:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5928:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5929:                        $uhome);
1.479     albertel 5930:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5931:     return get_query_reply($queryid);
                   5932: }
                   5933: 
1.818     raeburn  5934: # -------------------------- Update MySQL table for portfolio file
                   5935: 
                   5936: sub update_portfolio_table {
1.821     raeburn  5937:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5938:     if ($group ne '') {
                   5939:         $file_name =~s /^\Q$group\E//;
                   5940:     }
1.818     raeburn  5941:     my $homeserver = &homeserver($uname,$udom);
                   5942:     my $queryid=
1.821     raeburn  5943:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5944:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5945:     my $reply = &get_query_reply($queryid);
                   5946:     return $reply;
                   5947: }
                   5948: 
1.899     raeburn  5949: # -------------------------- Update MySQL allusers table
                   5950: 
                   5951: sub update_allusers_table {
                   5952:     my ($uname,$udom,$names) = @_;
                   5953:     my $homeserver = &homeserver($uname,$udom);
                   5954:     my $queryid=
                   5955:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5956:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5957:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5958:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5959:                'generation='.&escape($names->{'generation'}).'%%'.
                   5960:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5961:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5962:     return;
1.899     raeburn  5963: }
                   5964: 
1.508     raeburn  5965: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5966: 
                   5967: sub fetch_enrollment_query {
1.511     raeburn  5968:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5969:     my $homeserver;
1.547     raeburn  5970:     my $maxtries = 1;
1.508     raeburn  5971:     if ($context eq 'automated') {
                   5972:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5973:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5974:     } else {
                   5975:         $homeserver = &homeserver($cnum,$dom);
                   5976:     }
1.838     albertel 5977:     my $host=&hostname($homeserver);
1.506     raeburn  5978:     my $cmd = '';
1.1000    raeburn  5979:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5980:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5981:     }
                   5982:     $cmd =~ s/%%$//;
                   5983:     $cmd = &escape($cmd);
                   5984:     my $query = 'fetchenrollment';
1.620     albertel 5985:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5986:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5987:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5988:         return 'error: '.$queryid;
                   5989:     }
1.506     raeburn  5990:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5991:     my $tries = 1;
                   5992:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5993:         $reply = &get_query_reply($queryid);
                   5994:         $tries ++;
                   5995:     }
1.526     raeburn  5996:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5997:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5998:     } else {
1.901     albertel 5999:         my @responses = split(/:/,$reply);
1.515     raeburn  6000:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6001:             foreach my $line (@responses) {
                   6002:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6003:                 $$replyref{$key} = $value;
                   6004:             }
                   6005:         } else {
1.1117    foxr     6006:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6007:             foreach my $line (@responses) {
                   6008:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6009:                 $$replyref{$key} = $value;
                   6010:                 if ($value > 0) {
1.800     albertel 6011:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6012:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6013:                         my $destname = $pathname.'/'.$filename;
                   6014:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6015:                         if ($xml_classlist =~ /^error/) {
                   6016:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6017:                         } else {
1.506     raeburn  6018:                             if ( open(FILE,">$destname") ) {
                   6019:                                 print FILE &unescape($xml_classlist);
                   6020:                                 close(FILE);
1.526     raeburn  6021:                             } else {
                   6022:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6023:                             }
                   6024:                         }
                   6025:                     }
                   6026:                 }
                   6027:             }
                   6028:         }
                   6029:         return 'ok';
                   6030:     }
                   6031:     return 'error';
                   6032: }
                   6033: 
1.242     www      6034: sub get_query_reply {
                   6035:     my $queryid=shift;
1.1117    foxr     6036:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6037:     my $reply='';
                   6038:     for (1..100) {
                   6039: 	sleep 2;
                   6040:         if (-e $replyfile.'.end') {
1.448     albertel 6041: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6042: 		$reply = join('',<$fh>);
                   6043: 		close($fh);
1.240     www      6044: 	   } else { return 'error: reply_file_error'; }
1.242     www      6045:            return &unescape($reply);
                   6046: 	}
1.240     www      6047:     }
1.242     www      6048:     return 'timeout:'.$queryid;
1.240     www      6049: }
                   6050: 
                   6051: sub courselog_query {
1.241     www      6052: #
                   6053: # possible filters:
                   6054: # url: url or symb
                   6055: # username
                   6056: # domain
                   6057: # action: view, submit, grade
                   6058: # start: timestamp
                   6059: # end: timestamp
                   6060: #
1.240     www      6061:     my (%filters)=@_;
1.620     albertel 6062:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6063:     if ($filters{'url'}) {
                   6064: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6065:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6066:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6067:     }
1.620     albertel 6068:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6069:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6070:     return &log_query($cname,$cdom,'courselog',%filters);
                   6071: }
                   6072: 
                   6073: sub userlog_query {
1.858     raeburn  6074: #
                   6075: # possible filters:
                   6076: # action: log check role
                   6077: # start: timestamp
                   6078: # end: timestamp
                   6079: #
1.240     www      6080:     my ($uname,$udom,%filters)=@_;
                   6081:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6082: }
                   6083: 
1.506     raeburn  6084: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6085: 
                   6086: sub auto_run {
1.508     raeburn  6087:     my ($cnum,$cdom) = @_;
1.876     raeburn  6088:     my $response = 0;
                   6089:     my $settings;
                   6090:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6091:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6092:         $settings = $domconfig{'autoenroll'};
                   6093:         if ($settings->{'run'} eq '1') {
                   6094:             $response = 1;
                   6095:         }
                   6096:     } else {
1.934     raeburn  6097:         my $homeserver;
                   6098:         if (&is_course($cdom,$cnum)) {
                   6099:             $homeserver = &homeserver($cnum,$cdom);
                   6100:         } else {
                   6101:             $homeserver = &domain($cdom,'primary');
                   6102:         }
                   6103:         if ($homeserver ne 'no_host') {
                   6104:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6105:         }
1.876     raeburn  6106:     }
1.506     raeburn  6107:     return $response;
                   6108: }
1.776     albertel 6109: 
1.506     raeburn  6110: sub auto_get_sections {
1.508     raeburn  6111:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6112:     my $homeserver;
                   6113:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6114:         $homeserver = &homeserver($cnum,$cdom);
                   6115:     }
                   6116:     if (!defined($homeserver)) { 
                   6117:         if ($cdom =~ /^$match_domain$/) {
                   6118:             $homeserver = &domain($cdom,'primary');
                   6119:         }
                   6120:     }
                   6121:     my @secs;
                   6122:     if (defined($homeserver)) {
                   6123:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6124:         unless ($response eq 'refused') {
                   6125:             @secs = split(/:/,$response);
                   6126:         }
1.506     raeburn  6127:     }
                   6128:     return @secs;
                   6129: }
1.776     albertel 6130: 
1.506     raeburn  6131: sub auto_new_course {
1.1099    raeburn  6132:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6133:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6134:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6135:     return $response;
                   6136: }
1.776     albertel 6137: 
1.506     raeburn  6138: sub auto_validate_courseID {
1.508     raeburn  6139:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6140:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6141:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6142:     return $response;
                   6143: }
1.776     albertel 6144: 
1.1007    raeburn  6145: sub auto_validate_instcode {
1.1020    raeburn  6146:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6147:     my ($homeserver,$response);
                   6148:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6149:         $homeserver = &homeserver($cnum,$cdom);
                   6150:     }
                   6151:     if (!defined($homeserver)) {
                   6152:         if ($cdom =~ /^$match_domain$/) {
                   6153:             $homeserver = &domain($cdom,'primary');
                   6154:         }
                   6155:     }
1.1065    raeburn  6156:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6157:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6158:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6159:     return ($outcome,$description);
1.1007    raeburn  6160: }
                   6161: 
1.506     raeburn  6162: sub auto_create_password {
1.873     raeburn  6163:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6164:     my ($homeserver,$response);
1.506     raeburn  6165:     my $create_passwd = 0;
                   6166:     my $authchk = '';
1.873     raeburn  6167:     if ($udom =~ /^$match_domain$/) {
                   6168:         $homeserver = &domain($udom,'primary');
                   6169:     }
                   6170:     if ($homeserver eq '') {
                   6171:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6172:             $homeserver = &homeserver($cnum,$cdom);
                   6173:         }
                   6174:     }
                   6175:     if ($homeserver eq '') {
                   6176:         $authchk = 'nodomain';
1.506     raeburn  6177:     } else {
1.873     raeburn  6178:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6179:         if ($response eq 'refused') {
                   6180:             $authchk = 'refused';
                   6181:         } else {
1.901     albertel 6182:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6183:         }
1.506     raeburn  6184:     }
                   6185:     return ($authparam,$create_passwd,$authchk);
                   6186: }
                   6187: 
1.706     raeburn  6188: sub auto_photo_permission {
                   6189:     my ($cnum,$cdom,$students) = @_;
                   6190:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6191:     my ($outcome,$perm_reqd,$conditions) = 
                   6192: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6193:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6194: 	return (undef,undef);
                   6195:     }
1.706     raeburn  6196:     return ($outcome,$perm_reqd,$conditions);
                   6197: }
                   6198: 
                   6199: sub auto_checkphotos {
                   6200:     my ($uname,$udom,$pid) = @_;
                   6201:     my $homeserver = &homeserver($uname,$udom);
                   6202:     my ($result,$resulttype);
                   6203:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6204: 				   &escape($uname).':'.&escape($pid),
                   6205: 				   $homeserver));
1.709     albertel 6206:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6207: 	return (undef,undef);
                   6208:     }
1.706     raeburn  6209:     if ($outcome) {
                   6210:         ($result,$resulttype) = split(/:/,$outcome);
                   6211:     } 
                   6212:     return ($result,$resulttype);
                   6213: }
                   6214: 
                   6215: sub auto_photochoice {
                   6216:     my ($cnum,$cdom) = @_;
                   6217:     my $homeserver = &homeserver($cnum,$cdom);
                   6218:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6219: 						       &escape($cdom),
                   6220: 						       $homeserver)));
1.709     albertel 6221:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6222: 	return (undef,undef);
                   6223:     }
1.706     raeburn  6224:     return ($update,$comment);
                   6225: }
                   6226: 
                   6227: sub auto_photoupdate {
                   6228:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6229:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6230:     my $host=&hostname($homeserver);
1.706     raeburn  6231:     my $cmd = '';
                   6232:     my $maxtries = 1;
1.800     albertel 6233:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6234:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6235:     }
                   6236:     $cmd =~ s/%%$//;
                   6237:     $cmd = &escape($cmd);
                   6238:     my $query = 'institutionalphotos';
                   6239:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6240:     unless ($queryid=~/^\Q$host\E\_/) {
                   6241:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6242:         return 'error: '.$queryid;
                   6243:     }
                   6244:     my $reply = &get_query_reply($queryid);
                   6245:     my $tries = 1;
                   6246:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6247:         $reply = &get_query_reply($queryid);
                   6248:         $tries ++;
                   6249:     }
                   6250:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6251:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6252:     } else {
                   6253:         my @responses = split(/:/,$reply);
                   6254:         my $outcome = shift(@responses); 
                   6255:         foreach my $item (@responses) {
                   6256:             my ($key,$value) = split(/=/,$item);
                   6257:             $$photo{$key} = $value;
                   6258:         }
                   6259:         return $outcome;
                   6260:     }
                   6261:     return 'error';
                   6262: }
                   6263: 
1.521     raeburn  6264: sub auto_instcode_format {
1.793     albertel 6265:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6266: 	$cat_order) = @_;
1.521     raeburn  6267:     my $courses = '';
1.772     raeburn  6268:     my @homeservers;
1.521     raeburn  6269:     if ($caller eq 'global') {
1.841     albertel 6270: 	my %servers = &get_servers($codedom,'library');
                   6271: 	foreach my $tryserver (keys(%servers)) {
                   6272: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6273: 		push(@homeservers,$tryserver);
                   6274: 	    }
1.584     raeburn  6275:         }
1.1022    raeburn  6276:     } elsif ($caller eq 'requests') {
                   6277:         if ($codedom =~ /^$match_domain$/) {
                   6278:             my $chome = &domain($codedom,'primary');
                   6279:             unless ($chome eq 'no_host') {
                   6280:                 push(@homeservers,$chome);
                   6281:             }
                   6282:         }
1.521     raeburn  6283:     } else {
1.772     raeburn  6284:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6285:     }
1.793     albertel 6286:     foreach my $code (keys(%{$instcodes})) {
                   6287:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6288:     }
                   6289:     chop($courses);
1.772     raeburn  6290:     my $ok_response = 0;
                   6291:     my $response;
                   6292:     while (@homeservers > 0 && $ok_response == 0) {
                   6293:         my $server = shift(@homeservers); 
                   6294:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6295:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6296:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6297: 		split(/:/,$response);
1.772     raeburn  6298:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6299:             push(@{$codetitles},&str2array($codetitles_str));
                   6300:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6301:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6302:             $ok_response = 1;
                   6303:         }
                   6304:     }
                   6305:     if ($ok_response) {
1.521     raeburn  6306:         return 'ok';
1.772     raeburn  6307:     } else {
                   6308:         return $response;
1.521     raeburn  6309:     }
                   6310: }
                   6311: 
1.792     raeburn  6312: sub auto_instcode_defaults {
                   6313:     my ($domain,$returnhash,$code_order) = @_;
                   6314:     my @homeservers;
1.841     albertel 6315: 
                   6316:     my %servers = &get_servers($domain,'library');
                   6317:     foreach my $tryserver (keys(%servers)) {
                   6318: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6319: 	    push(@homeservers,$tryserver);
                   6320: 	}
1.792     raeburn  6321:     }
1.841     albertel 6322: 
1.792     raeburn  6323:     my $response;
1.841     albertel 6324:     foreach my $server (@homeservers) {
1.792     raeburn  6325:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6326:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6327: 	
                   6328: 	foreach my $pair (split(/\&/,$response)) {
                   6329: 	    my ($name,$value)=split(/\=/,$pair);
                   6330: 	    if ($name eq 'code_order') {
                   6331: 		@{$code_order} = split(/\&/,&unescape($value));
                   6332: 	    } else {
                   6333: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6334: 	    }
                   6335: 	}
                   6336: 	return 'ok';
1.792     raeburn  6337:     }
1.841     albertel 6338: 
                   6339:     return $response;
1.1003    raeburn  6340: }
                   6341: 
                   6342: sub auto_possible_instcodes {
1.1007    raeburn  6343:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6344:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6345:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6346:         return;
                   6347:     }
1.1003    raeburn  6348:     my (@homeservers,$uhome);
                   6349:     if (defined(&domain($domain,'primary'))) {
                   6350:         $uhome=&domain($domain,'primary');
                   6351:         push(@homeservers,&domain($domain,'primary'));
                   6352:     } else {
                   6353:         my %servers = &get_servers($domain,'library');
                   6354:         foreach my $tryserver (keys(%servers)) {
                   6355:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6356:                 push(@homeservers,$tryserver);
                   6357:             }
                   6358:         }
                   6359:     }
                   6360:     my $response;
                   6361:     foreach my $server (@homeservers) {
                   6362:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6363:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6364:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6365:             split(':',$response);
                   6366:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6367:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6368:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6369:             my ($name,$value)=split('=',$item);
                   6370:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6371:         }
                   6372:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6373:             my ($name,$value)=split('=',$item);
                   6374:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6375:         }
                   6376:         return 'ok';
                   6377:     }
                   6378:     return $response;
                   6379: }
1.792     raeburn  6380: 
1.1010    raeburn  6381: sub auto_courserequest_checks {
                   6382:     my ($dom) = @_;
1.1020    raeburn  6383:     my ($homeserver,%validations);
                   6384:     if ($dom =~ /^$match_domain$/) {
                   6385:         $homeserver = &domain($dom,'primary');
                   6386:     }
                   6387:     unless ($homeserver eq 'no_host') {
                   6388:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6389:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6390:             my @items = split(/&/,$response);
                   6391:             foreach my $item (@items) {
                   6392:                 my ($key,$value) = split('=',$item);
                   6393:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6394:             }
                   6395:         }
                   6396:     }
1.1010    raeburn  6397:     return %validations; 
                   6398: }
                   6399: 
1.1020    raeburn  6400: sub auto_courserequest_validation {
                   6401:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6402:     my ($homeserver,$response);
                   6403:     if ($dom =~ /^$match_domain$/) {
                   6404:         $homeserver = &domain($dom,'primary');
                   6405:     }
                   6406:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6407:           
1.1020    raeburn  6408:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6409:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6410:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6411:                                     $homeserver));
                   6412:     }
                   6413:     return $response;
                   6414: }
                   6415: 
1.777     albertel 6416: sub auto_validate_class_sec {
1.918     raeburn  6417:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6418:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6419:     my $ownerlist;
                   6420:     if (ref($owners) eq 'ARRAY') {
                   6421:         $ownerlist = join(',',@{$owners});
                   6422:     } else {
                   6423:         $ownerlist = $owners;
                   6424:     }
1.773     raeburn  6425:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6426:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6427:     return $response;
                   6428: }
                   6429: 
1.679     raeburn  6430: # ------------------------------------------------------- Course Group routines
                   6431: 
                   6432: sub get_coursegroups {
1.809     raeburn  6433:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6434:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6435: }
                   6436: 
1.679     raeburn  6437: sub modify_coursegroup {
                   6438:     my ($cdom,$cnum,$groupsettings) = @_;
                   6439:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6440: }
                   6441: 
1.809     raeburn  6442: sub toggle_coursegroup_status {
                   6443:     my ($cdom,$cnum,$group,$action) = @_;
                   6444:     my ($from_namespace,$to_namespace);
                   6445:     if ($action eq 'delete') {
                   6446:         $from_namespace = 'coursegroups';
                   6447:         $to_namespace = 'deleted_groups';
                   6448:     } else {
                   6449:         $from_namespace = 'deleted_groups';
                   6450:         $to_namespace = 'coursegroups';
                   6451:     }
                   6452:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6453:     if (my $tmp = &error(%curr_group)) {
                   6454:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6455:         return ('read error',$tmp);
                   6456:     } else {
                   6457:         my %savedsettings = %curr_group; 
1.809     raeburn  6458:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6459:         my $deloutcome;
                   6460:         if ($result eq 'ok') {
1.809     raeburn  6461:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6462:         } else {
                   6463:             return ('write error',$result);
                   6464:         }
                   6465:         if ($deloutcome eq 'ok') {
                   6466:             return 'ok';
                   6467:         } else {
                   6468:             return ('delete error',$deloutcome);
                   6469:         }
                   6470:     }
                   6471: }
                   6472: 
1.679     raeburn  6473: sub modify_group_roles {
1.957     raeburn  6474:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6475:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6476:     my $role = 'gr/'.&escape($userprivs);
                   6477:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6478:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6479:     if ($result eq 'ok') {
                   6480:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6481:     }
1.679     raeburn  6482:     return $result;
                   6483: }
                   6484: 
                   6485: sub modify_coursegroup_membership {
                   6486:     my ($cdom,$cnum,$membership) = @_;
                   6487:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6488:     return $result;
                   6489: }
                   6490: 
1.682     raeburn  6491: sub get_active_groups {
                   6492:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6493:     my $now = time;
                   6494:     my %groups = ();
                   6495:     foreach my $key (keys(%env)) {
1.811     albertel 6496:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6497:             my ($start,$end) = split(/\./,$env{$key});
                   6498:             if (($end!=0) && ($end<$now)) { next; }
                   6499:             if (($start!=0) && ($start>$now)) { next; }
                   6500:             if ($1 eq $cdom && $2 eq $cnum) {
                   6501:                 $groups{$3} = $env{$key} ;
                   6502:             }
                   6503:         }
                   6504:     }
                   6505:     return %groups;
                   6506: }
                   6507: 
1.683     raeburn  6508: sub get_group_membership {
                   6509:     my ($cdom,$cnum,$group) = @_;
                   6510:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6511: }
                   6512: 
                   6513: sub get_users_groups {
                   6514:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6515:     my @usersgroups;
1.683     raeburn  6516:     my $cachetime=1800;
                   6517: 
                   6518:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6519:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6520:     if (defined($cached)) {
1.734     albertel 6521:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6522:     } else {  
                   6523:         $grouplist = '';
1.816     raeburn  6524:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6525:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6526:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6527:         my $access_end = $env{'course.'.$courseid.
                   6528:                               '.default_enrollment_end_date'};
                   6529:         my $now = time;
                   6530:         foreach my $key (keys(%roleshash)) {
                   6531:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6532:                 my $group = $1;
                   6533:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6534:                     my $start = $2;
                   6535:                     my $end = $1;
                   6536:                     if ($start == -1) { next; } # deleted from group
                   6537:                     if (($start!=0) && ($start>$now)) { next; }
                   6538:                     if (($end!=0) && ($end<$now)) {
                   6539:                         if ($access_end && $access_end < $now) {
                   6540:                             if ($access_end - $end < 86400) {
                   6541:                                 push(@usersgroups,$group);
1.733     raeburn  6542:                             }
                   6543:                         }
1.817     raeburn  6544:                         next;
1.733     raeburn  6545:                     }
1.817     raeburn  6546:                     push(@usersgroups,$group);
1.683     raeburn  6547:                 }
                   6548:             }
                   6549:         }
1.817     raeburn  6550:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6551:         $grouplist = join(':',@usersgroups);
                   6552:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6553:     }
1.733     raeburn  6554:     return @usersgroups;
1.683     raeburn  6555: }
                   6556: 
                   6557: sub devalidate_getgroups_cache {
                   6558:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6559:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6560: 
1.683     raeburn  6561:     my $hashid="$udom:$uname:$courseid";
                   6562:     &devalidate_cache_new('getgroups',$hashid);
                   6563: }
                   6564: 
1.12      www      6565: # ------------------------------------------------------------------ Plain Text
                   6566: 
                   6567: sub plaintext {
1.988     raeburn  6568:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6569:     if ($short =~ m{^cr/}) {
1.758     albertel 6570: 	return (split('/',$short))[-1];
                   6571:     }
1.742     raeburn  6572:     if (!defined($cid)) {
                   6573:         $cid = $env{'request.course.id'};
                   6574:     }
                   6575:     my %rolenames = (
1.1008    raeburn  6576:                       Course    => 'std',
                   6577:                       Community => 'alt1',
1.742     raeburn  6578:                     );
1.1037    raeburn  6579:     if ($cid ne '') {
                   6580:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6581:             unless ($forcedefault) {
                   6582:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6583:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6584:                 return &Apache::lonlocal::mt($roletext);
                   6585:             }
                   6586:         }
                   6587:     }
                   6588:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6589:         (defined($rolenames{$type})) && 
                   6590:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6591:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6592:     } elsif ($cid ne '') {
                   6593:         my $crstype = $env{'course.'.$cid.'.type'};
                   6594:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6595:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6596:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6597:         }
1.742     raeburn  6598:     }
1.1037    raeburn  6599:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6600: }
                   6601: 
                   6602: # ----------------------------------------------------------------- Assign Role
                   6603: 
                   6604: sub assignrole {
1.957     raeburn  6605:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6606:         $context)=@_;
1.21      www      6607:     my $mrole;
                   6608:     if ($role =~ /^cr\//) {
1.393     www      6609:         my $cwosec=$url;
1.811     albertel 6610:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6611: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6612:            my $refused = 1;
                   6613:            if ($context eq 'requestcourses') {
                   6614:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6615:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6616:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6617:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6618:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6619:                            if ($crsenv{'internal.courseowner'} eq
                   6620:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6621:                                $refused = '';
                   6622:                            }
                   6623:                        }
                   6624:                    }
                   6625:                }
                   6626:            }
                   6627:            if ($refused) {
                   6628:                &logthis('Refused custom assignrole: '.
                   6629:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6630:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6631:                return 'refused';
                   6632:            }
1.104     www      6633:         }
1.21      www      6634:         $mrole='cr';
1.678     raeburn  6635:     } elsif ($role =~ /^gr\//) {
                   6636:         my $cwogrp=$url;
1.811     albertel 6637:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6638:         unless (&allowed('mdg',$cwogrp)) {
                   6639:             &logthis('Refused group assignrole: '.
                   6640:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6641:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6642:             return 'refused';
                   6643:         }
                   6644:         $mrole='gr';
1.21      www      6645:     } else {
1.82      www      6646:         my $cwosec=$url;
1.811     albertel 6647:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6648:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6649:             my $refused;
                   6650:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6651:                 if (!(&allowed('c'.$role,$url))) {
                   6652:                     $refused = 1;
                   6653:                 }
                   6654:             } else {
                   6655:                 $refused = 1;
                   6656:             }
1.947     raeburn  6657:             if ($refused) {
1.1045    raeburn  6658:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6659:                 if (!$selfenroll && $context eq 'course') {
                   6660:                     my %crsenv;
                   6661:                     if ($role eq 'cc' || $role eq 'co') {
                   6662:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6663:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6664:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6665:                                 if ($crsenv{'internal.courseowner'} eq 
                   6666:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6667:                                     $refused = '';
                   6668:                                 }
                   6669:                             }
                   6670:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6671:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6672:                                 if ($crsenv{'internal.courseowner'} eq 
                   6673:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6674:                                     $refused = '';
                   6675:                                 }
                   6676:                             }
                   6677:                         }
                   6678:                     }
                   6679:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6680:                     $refused = '';
1.1017    raeburn  6681:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6682:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6683:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6684:                         my $wrongcc;
                   6685:                         if ($cnum =~ /^$match_community$/) {
                   6686:                             $wrongcc = 1 if ($role eq 'cc');
                   6687:                         } else {
                   6688:                             $wrongcc = 1 if ($role eq 'co');
                   6689:                         }
                   6690:                         unless ($wrongcc) {
                   6691:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6692:                             if ($crsenv{'internal.courseowner'} eq 
                   6693:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6694:                                 $refused = '';
                   6695:                             }
1.1017    raeburn  6696:                         }
                   6697:                     }
                   6698:                 }
                   6699:                 if ($refused) {
1.947     raeburn  6700:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6701:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6702: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6703:                     return 'refused';
                   6704:                 }
1.932     raeburn  6705:             }
1.104     www      6706:         }
1.21      www      6707:         $mrole=$role;
                   6708:     }
1.620     albertel 6709:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6710:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6711:     if ($end) { $command.='_'.$end; }
1.21      www      6712:     if ($start) {
                   6713: 	if ($end) { 
1.81      www      6714:            $command.='_'.$start; 
1.21      www      6715:         } else {
1.81      www      6716:            $command.='_0_'.$start;
1.21      www      6717:         }
                   6718:     }
1.739     raeburn  6719:     my $origstart = $start;
                   6720:     my $origend = $end;
1.957     raeburn  6721:     my $delflag;
1.357     www      6722: # actually delete
                   6723:     if ($deleteflag) {
1.373     www      6724: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6725: # modify command to delete the role
1.620     albertel 6726:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6727:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6728: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6729: # set start and finish to negative values for userrolelog
                   6730:            $start=-1;
                   6731:            $end=-1;
1.957     raeburn  6732:            $delflag = 1;
1.357     www      6733:         }
                   6734:     }
                   6735: # send command
1.349     www      6736:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6737: # log new user role if status is ok
1.349     www      6738:     if ($answer eq 'ok') {
1.663     raeburn  6739: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6740: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6741:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6742:         unless ($role =~ /^gr/) {
                   6743:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6744:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6745:         }
1.1053    raeburn  6746:         if ($role eq 'cc') {
                   6747:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6748:         }
1.349     www      6749:     }
                   6750:     return $answer;
1.169     harris41 6751: }
                   6752: 
1.1053    raeburn  6753: sub autoupdate_coowners {
                   6754:     my ($url,$end,$start,$uname,$udom) = @_;
                   6755:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6756:     if (($cdom ne '') && ($cnum ne '')) {
                   6757:         my $now = time;
                   6758:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6759:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6760:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6761:             my $instcode = $coursehash{'internal.coursecode'};
                   6762:             if ($instcode ne '') {
1.1056    raeburn  6763:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6764:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6765:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6766:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6767:                         if ($result eq 'valid') {
                   6768:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6769:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6770:                                     push(@newcoowners,$coowner);
                   6771:                                 }
                   6772:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6773:                                     push(@newcoowners,$uname.':'.$udom);
                   6774:                                 }
                   6775:                                 @newcoowners = sort(@newcoowners);
                   6776:                             } else {
                   6777:                                 push(@newcoowners,$uname.':'.$udom);
                   6778:                             }
                   6779:                         } else {
                   6780:                             if ($coursehash{'internal.co-owners'}) {
                   6781:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6782:                                     unless ($coowner eq $uname.':'.$udom) {
                   6783:                                         push(@newcoowners,$coowner);
                   6784:                                     }
                   6785:                                 }
                   6786:                                 unless (@newcoowners > 0) {
                   6787:                                     $delcoowners = 1;
                   6788:                                     $coowners = '';
                   6789:                                 }
                   6790:                             }
                   6791:                         }
                   6792:                         if (@newcoowners || $delcoowners) {
                   6793:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6794:                                             $delcoowners,@newcoowners);
                   6795:                         }
                   6796:                     }
                   6797:                 }
                   6798:             }
                   6799:         }
                   6800:     }
                   6801: }
                   6802: 
                   6803: sub store_coowners {
                   6804:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6805:     my $cid = $cdom.'_'.$cnum;
                   6806:     my ($coowners,$delresult,$putresult);
                   6807:     if (@newcoowners) {
                   6808:         $coowners = join(',',@newcoowners);
                   6809:         my %coownershash = (
                   6810:                             'internal.co-owners' => $coowners,
                   6811:                            );
                   6812:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6813:         if ($putresult eq 'ok') {
                   6814:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6815:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6816:             }
                   6817:         }
                   6818:     }
                   6819:     if ($delcoowners) {
                   6820:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6821:         if ($delresult eq 'ok') {
                   6822:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6823:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6824:             }
                   6825:         }
                   6826:     }
                   6827:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6828:         my %crsinfo =
                   6829:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6830:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6831:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6832:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6833:         }
                   6834:     }
                   6835: }
                   6836: 
1.169     harris41 6837: # -------------------------------------------------- Modify user authentication
1.197     www      6838: # Overrides without validation
                   6839: 
1.169     harris41 6840: sub modifyuserauth {
                   6841:     my ($udom,$uname,$umode,$upass)=@_;
                   6842:     my $uhome=&homeserver($uname,$udom);
1.197     www      6843:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6844:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6845:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6846:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6847:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6848: 		     &escape($upass),$uhome);
1.620     albertel 6849:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6850:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6851:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6852:     &log($udom,,$uname,$uhome,
1.620     albertel 6853:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6854:                                      $env{'user.name'}.', '.$umode.
1.197     www      6855:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6856:     unless ($reply eq 'ok') {
1.197     www      6857:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6858: 	return 'error: '.$reply;
                   6859:     }   
1.170     harris41 6860:     return 'ok';
1.80      www      6861: }
                   6862: 
1.81      www      6863: # --------------------------------------------------------------- Modify a user
1.80      www      6864: 
1.81      www      6865: sub modifyuser {
1.206     matthew  6866:     my ($udom,    $uname, $uid,
                   6867:         $umode,   $upass, $first,
                   6868:         $middle,  $last,  $gene,
1.1058    raeburn  6869:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6870:     $udom= &LONCAPA::clean_domain($udom);
                   6871:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6872:     my $showcandelete = 'none';
                   6873:     if (ref($candelete) eq 'ARRAY') {
                   6874:         if (@{$candelete} > 0) {
                   6875:             $showcandelete = join(', ',@{$candelete});
                   6876:         }
                   6877:     }
1.81      www      6878:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6879:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6880: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6881:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6882:                                      ' desiredhome not specified'). 
1.620     albertel 6883:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6884:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6885:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6886:     my $newuser;
                   6887:     if ($uhome eq 'no_host') {
                   6888:         $newuser = 1;
                   6889:     }
1.80      www      6890: # ----------------------------------------------------------------- Create User
1.406     albertel 6891:     if (($uhome eq 'no_host') && 
                   6892: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6893:         my $unhome='';
1.844     albertel 6894:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6895:             $unhome = $desiredhome;
1.620     albertel 6896: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6897: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6898:         } else { # load balancing routine for determining $unhome
1.81      www      6899:             my $loadm=10000000;
1.841     albertel 6900: 	    my %servers = &get_servers($udom,'library');
                   6901: 	    foreach my $tryserver (keys(%servers)) {
                   6902: 		my $answer=reply('load',$tryserver);
                   6903: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6904: 		    $loadm=$answer;
                   6905: 		    $unhome=$tryserver;
                   6906: 		}
1.80      www      6907: 	    }
                   6908:         }
                   6909:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6910: 	    return 'error: unable to find a home server for '.$uname.
                   6911:                    ' in domain '.$udom;
1.80      www      6912:         }
                   6913:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6914:                          &escape($upass),$unhome);
                   6915: 	unless ($reply eq 'ok') {
                   6916:             return 'error: '.$reply;
                   6917:         }   
1.230     stredwic 6918:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6919:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6920: 	    return 'error: unable verify users home machine.';
1.80      www      6921:         }
1.209     matthew  6922:     }   # End of creation of new user
1.80      www      6923: # ---------------------------------------------------------------------- Add ID
                   6924:     if ($uid) {
                   6925:        $uid=~tr/A-Z/a-z/;
                   6926:        my %uidhash=&idrget($udom,$uname);
1.196     www      6927:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6928:          && (!$forceid)) {
1.80      www      6929: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6930: 	      return 'error: user id "'.$uid.'" does not match '.
                   6931:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6932:           }
                   6933:        } else {
                   6934: 	  &idput($udom,($uname => $uid));
                   6935:        }
                   6936:     }
                   6937: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6938:     my @tmp=&get('environment',
1.899     raeburn  6939: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6940:                     'permanentemail','inststatus'],
1.134     albertel 6941: 		   $udom,$uname);
1.1075    raeburn  6942:     my (%names,%oldnames);
1.313     matthew  6943:     if ($tmp[0] =~ m/^error:.*/) { 
                   6944:         %names=(); 
                   6945:     } else {
                   6946:         %names = @tmp;
1.1075    raeburn  6947:         %oldnames = %names;
1.313     matthew  6948:     }
1.388     www      6949: #
1.1058    raeburn  6950: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6951: # of users did not contain them), do not overwrite existing values
                   6952: # unless field is in $candelete array ref.  
                   6953: #
                   6954: 
                   6955:     my @fields = ('firstname','middlename','lastname','generation',
                   6956:                   'permanentemail','id');
                   6957:     my %newvalues;
                   6958:     if (ref($candelete) eq 'ARRAY') {
                   6959:         foreach my $field (@fields) {
                   6960:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6961:                 if ($field eq 'firstname') {
                   6962:                     $names{$field} = $first;
                   6963:                 } elsif ($field eq 'middlename') {
                   6964:                     $names{$field} = $middle;
                   6965:                 } elsif ($field eq 'lastname') {
                   6966:                     $names{$field} = $last;
                   6967:                 } elsif ($field eq 'generation') { 
                   6968:                     $names{$field} = $gene;
                   6969:                 } elsif ($field eq 'permanentemail') {
                   6970:                     $names{$field} = $email;
                   6971:                 } elsif ($field eq 'id') {
                   6972:                     $names{$field}  = $uid;
                   6973:                 }
                   6974:             }
                   6975:         }
                   6976:     }
1.388     www      6977:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6978:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6979:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6980:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6981:     if ($email) {
                   6982:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6983:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6984:     }
1.899     raeburn  6985:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6986:     if (defined($inststatus)) {
                   6987:         $names{'inststatus'} = '';
                   6988:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6989:         if (ref($usertypes) eq 'HASH') {
                   6990:             my @okstatuses; 
                   6991:             foreach my $item (split(/:/,$inststatus)) {
                   6992:                 if (defined($usertypes->{$item})) {
                   6993:                     push(@okstatuses,$item);  
                   6994:                 }
                   6995:             }
                   6996:             if (@okstatuses) {
                   6997:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6998:             }
                   6999:         }
                   7000:     }
1.1075    raeburn  7001:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7002:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7003:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7004:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7005:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7006:     } else {
                   7007:         $logmsg .= ' during self creation';
                   7008:     }
1.1075    raeburn  7009:     my $changed;
                   7010:     if ($newuser) {
                   7011:         $changed = 1;
                   7012:     } else {
                   7013:         foreach my $field (@fields) {
                   7014:             if ($names{$field} ne $oldnames{$field}) {
                   7015:                 $changed = 1;
                   7016:                 last;
                   7017:             }
                   7018:         }
                   7019:     }
                   7020:     unless ($changed) {
                   7021:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7022:         &logthis($logmsg);
                   7023:         return 'ok';
                   7024:     }
                   7025:     my $reply = &put('environment', \%names, $udom,$uname);
                   7026:     if ($reply ne 'ok') { 
                   7027:         return 'error: '.$reply;
                   7028:     }
1.1087    raeburn  7029:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7030:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7031:     }
1.1075    raeburn  7032:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7033:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7034:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7035:     &logthis($logmsg);
1.134     albertel 7036:     return 'ok';
1.80      www      7037: }
                   7038: 
1.81      www      7039: # -------------------------------------------------------------- Modify student
1.80      www      7040: 
1.81      www      7041: sub modifystudent {
                   7042:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7043:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7044:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7045:     if (!$cid) {
1.620     albertel 7046: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7047: 	    return 'not_in_class';
                   7048: 	}
1.80      www      7049:     }
                   7050: # --------------------------------------------------------------- Make the user
1.81      www      7051:     my $reply=&modifyuser
1.209     matthew  7052: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7053:          $desiredhome,$email,$inststatus);
1.80      www      7054:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7055:     # This will cause &modify_student_enrollment to get the uid from the
                   7056:     # students environment
                   7057:     $uid = undef if (!$forceid);
1.455     albertel 7058:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7059: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7060:     return $reply;
                   7061: }
                   7062: 
                   7063: sub modify_student_enrollment {
1.957     raeburn  7064:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7065:     my ($cdom,$cnum,$chome);
                   7066:     if (!$cid) {
1.620     albertel 7067: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7068: 	    return 'not_in_class';
                   7069: 	}
1.620     albertel 7070: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7071: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7072:     } else {
                   7073: 	($cdom,$cnum)=split(/_/,$cid);
                   7074:     }
1.620     albertel 7075:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7076:     if (!$chome) {
1.457     raeburn  7077: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7078:     }
1.455     albertel 7079:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7080:     # Make sure the user exists
1.81      www      7081:     my $uhome=&homeserver($uname,$udom);
                   7082:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7083: 	return 'error: no such user';
                   7084:     }
1.297     matthew  7085:     # Get student data if we were not given enough information
                   7086:     if (!defined($first)  || $first  eq '' || 
                   7087:         !defined($last)   || $last   eq '' || 
                   7088:         !defined($uid)    || $uid    eq '' || 
                   7089:         !defined($middle) || $middle eq '' || 
                   7090:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7091:         # They did not supply us with enough data to enroll the student, so
                   7092:         # we need to pick up more information.
1.297     matthew  7093:         my %tmp = &get('environment',
1.294     matthew  7094:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7095:                        ,$udom,$uname);
                   7096: 
1.800     albertel 7097:         #foreach my $key (keys(%tmp)) {
                   7098:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7099:         #}
1.294     matthew  7100:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7101:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7102:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7103:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7104:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7105:     }
1.556     albertel 7106:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7107:     my $reply=cput('classlist',
                   7108: 		   {"$uname:$udom" => 
1.515     raeburn  7109: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7110: 		   $cdom,$cnum);
1.81      www      7111:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7112: 	return 'error: '.$reply;
1.652     albertel 7113:     } else {
                   7114: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7115:     }
1.297     matthew  7116:     # Add student role to user
1.83      www      7117:     my $uurl='/'.$cid;
1.81      www      7118:     $uurl=~s/\_/\//g;
                   7119:     if ($usec) {
                   7120: 	$uurl.='/'.$usec;
                   7121:     }
1.957     raeburn  7122:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7123: }
                   7124: 
1.556     albertel 7125: sub format_name {
                   7126:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7127:     my $name;
                   7128:     if ($first ne 'lastname') {
                   7129: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7130:     } else {
                   7131: 	if ($lastname=~/\S/) {
                   7132: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7133: 	    $name=~s/\s+,/,/;
                   7134: 	} else {
                   7135: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7136: 	}
                   7137:     }
                   7138:     $name=~s/^\s+//;
                   7139:     $name=~s/\s+$//;
                   7140:     $name=~s/\s+/ /g;
                   7141:     return $name;
                   7142: }
                   7143: 
1.84      www      7144: # ------------------------------------------------- Write to course preferences
                   7145: 
                   7146: sub writecoursepref {
                   7147:     my ($courseid,%prefs)=@_;
                   7148:     $courseid=~s/^\///;
                   7149:     $courseid=~s/\_/\//g;
                   7150:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7151:     my $chome=homeserver($cnum,$cdomain);
                   7152:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7153: 	return 'error: no such course';
                   7154:     }
                   7155:     my $cstring='';
1.800     albertel 7156:     foreach my $pref (keys(%prefs)) {
                   7157: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7158:     }
1.84      www      7159:     $cstring=~s/\&$//;
                   7160:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7161: }
                   7162: 
                   7163: # ---------------------------------------------------------- Make/modify course
                   7164: 
                   7165: sub createcourse {
1.741     raeburn  7166:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7167:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7168:     $url=&declutter($url);
                   7169:     my $cid='';
1.1028    raeburn  7170:     if ($context eq 'requestcourses') {
                   7171:         my $can_create = 0;
                   7172:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7173:         if ($udom eq $ownerdom) {
                   7174:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7175:                                   $context)) {
                   7176:                 $can_create = 1;
                   7177:             }
                   7178:         } else {
                   7179:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7180:                                            $category);
                   7181:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7182:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7183:                 if (@curr > 0) {
                   7184:                     my @options = qw(approval validate autolimit);
                   7185:                     my $optregex = join('|',@options);
                   7186:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7187:                         $can_create = 1;
                   7188:                     }
                   7189:                 }
                   7190:             }
                   7191:         }
                   7192:         if ($can_create) {
                   7193:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7194:                 unless (&allowed('ccc',$udom)) {
                   7195:                     return 'refused'; 
                   7196:                 }
1.1017    raeburn  7197:             }
                   7198:         } else {
                   7199:             return 'refused';
                   7200:         }
1.1028    raeburn  7201:     } elsif (!&allowed('ccc',$udom)) {
                   7202:         return 'refused';
1.84      www      7203:     }
1.1011    raeburn  7204: # --------------------------------------------------------------- Get Unique ID
                   7205:     my $uname;
                   7206:     if ($cnum =~ /^$match_courseid$/) {
                   7207:         my $chome=&homeserver($cnum,$udom,'true');
                   7208:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7209:             $uname = $cnum;
                   7210:         } else {
1.1038    raeburn  7211:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7212:         }
                   7213:     } else {
1.1038    raeburn  7214:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7215:     }
                   7216:     return $uname if ($uname =~ /^error/);
                   7217: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7218:     if (!defined($course_server)) {
                   7219:         if (defined(&domain($udom,'primary'))) {
                   7220:             $course_server = &domain($udom,'primary');
                   7221:         } else {
                   7222:             $course_server = $env{'user.home'}; 
                   7223:         }
                   7224:     }
                   7225:     my %host_servers =
                   7226:         &Apache::lonnet::get_servers($udom,'library');
                   7227:     unless ($host_servers{$course_server}) {
                   7228:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7229:     }
1.84      www      7230: # ------------------------------------------------------------- Make the course
                   7231:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7232:                       $course_server);
1.84      www      7233:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7234:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7235:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7236: 	return 'error: no such course';
                   7237:     }
1.271     www      7238: # ----------------------------------------------------------------- Course made
1.516     raeburn  7239: # log existence
1.1029    raeburn  7240:     my $now = time;
1.918     raeburn  7241:     my $newcourse = {
                   7242:                     $udom.'_'.$uname => {
1.921     raeburn  7243:                                      description => $description,
                   7244:                                      inst_code   => $inst_code,
                   7245:                                      owner       => $course_owner,
                   7246:                                      type        => $crstype,
1.1029    raeburn  7247:                                      creator     => $env{'user.name'}.':'.
                   7248:                                                     $env{'user.domain'},
                   7249:                                      created     => $now,
                   7250:                                      context     => $context,
1.918     raeburn  7251:                                                 },
                   7252:                     };
1.921     raeburn  7253:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7254: # set toplevel url
1.271     www      7255:     my $topurl=$url;
                   7256:     unless ($nonstandard) {
                   7257: # ------------------------------------------ For standard courses, make top url
                   7258:         my $mapurl=&clutter($url);
1.278     www      7259:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7260:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7261: <map>
                   7262: <resource id="1" type="start"></resource>
                   7263: <resource id="2" src="$mapurl"></resource>
                   7264: <resource id="3" type="finish"></resource>
                   7265: <link index="1" from="1" to="2"></link>
                   7266: <link index="2" from="2" to="3"></link>
                   7267: </map>
                   7268: ENDINITMAP
                   7269:         $topurl=&declutter(
1.638     albertel 7270:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7271:                           );
                   7272:     }
                   7273: # ----------------------------------------------------------- Write preferences
1.84      www      7274:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7275:                      ('description'              => $description,
                   7276:                       'url'                      => $topurl,
                   7277:                       'internal.creator'         => $env{'user.name'}.':'.
                   7278:                                                     $env{'user.domain'},
                   7279:                       'internal.created'         => $now,
                   7280:                       'internal.creationcontext' => $context)
                   7281:                     );
1.84      www      7282:     return '/'.$udom.'/'.$uname;
                   7283: }
                   7284: 
1.1011    raeburn  7285: # ------------------------------------------------------------------- Create ID
                   7286: sub generate_coursenum {
1.1038    raeburn  7287:     my ($udom,$crstype) = @_;
1.1011    raeburn  7288:     my $domdesc = &domain($udom);
                   7289:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7290:     my $first;
                   7291:     if ($crstype eq 'Community') {
                   7292:         $first = '0';
                   7293:     } else {
                   7294:         $first = int(1+rand(9)); 
                   7295:     } 
                   7296:     my $uname=$first.
1.1011    raeburn  7297:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7298:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7299:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7300: # ----------------------------------------------- Make sure that does not exist
                   7301:     my $uhome=&homeserver($uname,$udom,'true');
                   7302:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7303:         if ($crstype eq 'Community') {
                   7304:             $first = '0';
                   7305:         } else {
                   7306:             $first = int(1+rand(9));
                   7307:         }
                   7308:         $uname=$first.
1.1011    raeburn  7309:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7310:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7311:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7312:         $uhome=&homeserver($uname,$udom,'true');
                   7313:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7314:             return 'error: unable to generate unique course-ID';
                   7315:         }
                   7316:     }
                   7317:     return $uname;
                   7318: }
                   7319: 
1.813     albertel 7320: sub is_course {
                   7321:     my ($cdom,$cnum) = @_;
                   7322:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7323: 				undef,'.');
1.813     albertel 7324:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7325:         return 1;
                   7326:     }
                   7327:     return 0;
                   7328: }
                   7329: 
1.1015    raeburn  7330: sub store_userdata {
                   7331:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7332:     my $result;
1.1016    raeburn  7333:     if ($datakey ne '') {
1.1013    raeburn  7334:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7335:             if ($udom eq '' || $uname eq '') {
                   7336:                 $udom = $env{'user.domain'};
                   7337:                 $uname = $env{'user.name'};
                   7338:             }
                   7339:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7340:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7341:                 $result = 'error: no_host';
                   7342:             } else {
                   7343:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7344:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7345: 
                   7346:                 my $namevalue='';
                   7347:                 foreach my $key (keys(%{$storehash})) {
                   7348:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7349:                 }
                   7350:                 $namevalue=~s/\&$//;
1.1105    raeburn  7351:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7352:                                   $namevalue,$uhome);
1.1013    raeburn  7353:             }
                   7354:         } else {
                   7355:             $result = 'error: data to store was not a hash reference'; 
                   7356:         }
                   7357:     } else {
                   7358:         $result= 'error: invalid requestkey'; 
                   7359:     }
                   7360:     return $result;
                   7361: }
                   7362: 
1.21      www      7363: # ---------------------------------------------------------- Assign Custom Role
                   7364: 
                   7365: sub assigncustomrole {
1.957     raeburn  7366:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7367:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7368:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7369: }
                   7370: 
                   7371: # ----------------------------------------------------------------- Revoke Role
                   7372: 
                   7373: sub revokerole {
1.957     raeburn  7374:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7375:     my $now=time;
1.965     raeburn  7376:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7377: }
                   7378: 
                   7379: # ---------------------------------------------------------- Revoke Custom Role
                   7380: 
                   7381: sub revokecustomrole {
1.957     raeburn  7382:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7383:     my $now=time;
1.357     www      7384:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7385:            $deleteflag,$selfenroll,$context);
1.17      www      7386: }
                   7387: 
1.533     banghart 7388: # ------------------------------------------------------------ Disk usage
1.535     albertel 7389: sub diskusage {
1.955     raeburn  7390:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7391:     $directorypath =~ s/\/$//;
                   7392:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7393:                        .&escape($getpropath).':'.&escape($uname).':'
                   7394:                        .&escape($udom),homeserver($uname,$udom));
                   7395:     if ($listing eq 'unknown_cmd') {
                   7396:         if ($getpropath) {
                   7397:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7398:         }
                   7399:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7400:     }
1.514     albertel 7401:     return $listing;
1.512     banghart 7402: }
                   7403: 
1.566     banghart 7404: sub is_locked {
1.1096    raeburn  7405:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7406:     my @check;
                   7407:     my $is_locked;
1.1093    raeburn  7408:     push (@check,$file_name);
1.613     albertel 7409:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7410: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7411:     my ($tmp)=keys(%locked);
                   7412:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7413:     
1.566     banghart 7414:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7415:         $is_locked = 'false';
                   7416:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7417:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7418:                $is_locked = 'true';
1.1096    raeburn  7419:                if (ref($which) eq 'ARRAY') {
                   7420:                    push(@{$which},$entry);
                   7421:                } else {
                   7422:                    last;
                   7423:                }
1.745     raeburn  7424:            }
                   7425:        }
1.566     banghart 7426:     } else {
                   7427:         $is_locked = 'false';
                   7428:     }
1.1093    raeburn  7429:     return $is_locked;
1.566     banghart 7430: }
                   7431: 
1.759     albertel 7432: sub declutter_portfile {
                   7433:     my ($file) = @_;
1.833     albertel 7434:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7435:     return $file;
                   7436: }
                   7437: 
1.559     banghart 7438: # ------------------------------------------------------------- Mark as Read Only
                   7439: 
                   7440: sub mark_as_readonly {
                   7441:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7442:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7443:     my ($tmp)=keys(%current_permissions);
                   7444:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7445:     foreach my $file (@{$files}) {
1.759     albertel 7446: 	$file = &declutter_portfile($file);
1.561     banghart 7447:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7448:     }
1.613     albertel 7449:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7450:     return;
                   7451: }
                   7452: 
1.572     banghart 7453: # ------------------------------------------------------------Save Selected Files
                   7454: 
                   7455: sub save_selected_files {
                   7456:     my ($user, $path, @files) = @_;
                   7457:     my $filename = $user."savedfiles";
1.573     banghart 7458:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7459:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7460:     foreach my $file (@files) {
1.620     albertel 7461:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7462:     }
                   7463:     foreach my $file (@other_files) {
1.574     banghart 7464:         print (OUT $file."\n");
1.572     banghart 7465:     }
1.574     banghart 7466:     close (OUT);
1.572     banghart 7467:     return 'ok';
                   7468: }
                   7469: 
1.574     banghart 7470: sub clear_selected_files {
                   7471:     my ($user) = @_;
                   7472:     my $filename = $user."savedfiles";
1.1117    foxr     7473:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7474:     print (OUT undef);
                   7475:     close (OUT);
                   7476:     return ("ok");    
                   7477: }
                   7478: 
1.572     banghart 7479: sub files_in_path {
                   7480:     my ($user, $path) = @_;
                   7481:     my $filename = $user."savedfiles";
                   7482:     my %return_files;
1.1117    foxr     7483:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7484:     while (my $line_in = <IN>) {
1.574     banghart 7485:         chomp ($line_in);
                   7486:         my @paths_and_file = split (m!/!, $line_in);
                   7487:         my $file_part = pop (@paths_and_file);
                   7488:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7489:         $path_part.='/';
                   7490:         my $path_and_file = $path_part.$file_part;
                   7491:         if ($path_part eq $path) {
                   7492:             $return_files{$file_part}= 'selected';
                   7493:         }
                   7494:     }
1.574     banghart 7495:     close (IN);
                   7496:     return (\%return_files);
1.572     banghart 7497: }
                   7498: 
                   7499: # called in portfolio select mode, to show files selected NOT in current directory
                   7500: sub files_not_in_path {
                   7501:     my ($user, $path) = @_;
                   7502:     my $filename = $user."savedfiles";
                   7503:     my @return_files;
                   7504:     my $path_part;
1.1117    foxr     7505:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7506:     while (my $line = <IN>) {
1.572     banghart 7507:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7508:         my @paths_and_file = split(m|/|, $line);
                   7509:         my $file_part = pop(@paths_and_file);
                   7510:         chomp($file_part);
                   7511:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7512:         $path_part .= '/';
                   7513:         my $path_and_file = $path_part.$file_part;
                   7514:         if ($path_part ne $path) {
1.800     albertel 7515:             push(@return_files, ($path_and_file));
1.572     banghart 7516:         }
                   7517:     }
1.800     albertel 7518:     close(OUT);
1.574     banghart 7519:     return (@return_files);
1.572     banghart 7520: }
                   7521: 
1.745     raeburn  7522: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7523: 
1.745     raeburn  7524: sub get_portfile_permissions {
                   7525:     my ($domain,$user) = @_;
1.613     albertel 7526:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7527:     my ($tmp)=keys(%current_permissions);
                   7528:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7529:     return \%current_permissions;
                   7530: }
                   7531: 
                   7532: #---------------------------------------------Get portfolio file access controls
                   7533: 
1.749     raeburn  7534: sub get_access_controls {
1.745     raeburn  7535:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7536:     my %access;
                   7537:     my $real_file = $file;
                   7538:     $file =~ s/\.meta$//;
1.745     raeburn  7539:     if (defined($file)) {
1.749     raeburn  7540:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7541:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7542:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7543:             }
                   7544:         }
1.745     raeburn  7545:     } else {
1.749     raeburn  7546:         foreach my $key (keys(%{$current_permissions})) {
                   7547:             if ($key =~ /\0accesscontrol$/) {
                   7548:                 if (defined($group)) {
                   7549:                     if ($key !~ m-^\Q$group\E/-) {
                   7550:                         next;
                   7551:                     }
                   7552:                 }
                   7553:                 my ($fullpath) = split(/\0/,$key);
                   7554:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7555:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7556:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7557:                     }
                   7558:                 }
                   7559:             }
                   7560:         }
                   7561:     }
                   7562:     return %access;
                   7563: }
                   7564: 
                   7565: sub modify_access_controls {
                   7566:     my ($file_name,$changes,$domain,$user)=@_;
                   7567:     my ($outcome,$deloutcome);
                   7568:     my %store_permissions;
                   7569:     my %new_values;
                   7570:     my %new_control;
                   7571:     my %translation;
                   7572:     my @deletions = ();
                   7573:     my $now = time;
                   7574:     if (exists($$changes{'activate'})) {
                   7575:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7576:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7577:             my $numnew = scalar(@newitems);
                   7578:             for (my $i=0; $i<$numnew; $i++) {
                   7579:                 my $newkey = $newitems[$i];
                   7580:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7581:                 if ($newkey =~ /^\d+:/) { 
                   7582:                     $newkey =~ s/^(\d+)/$newid/;
                   7583:                     $translation{$1} = $newid;
                   7584:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7585:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7586:                     $translation{$1} = $newid;
                   7587:                 }
1.749     raeburn  7588:                 $new_values{$file_name."\0".$newkey} = 
                   7589:                                           $$changes{'activate'}{$newitems[$i]};
                   7590:                 $new_control{$newkey} = $now;
                   7591:             }
                   7592:         }
                   7593:     }
                   7594:     my %todelete;
                   7595:     my %changed_items;
                   7596:     foreach my $action ('delete','update') {
                   7597:         if (exists($$changes{$action})) {
                   7598:             if (ref($$changes{$action}) eq 'HASH') {
                   7599:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7600:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7601:                     if ($action eq 'delete') { 
                   7602:                         $todelete{$itemnum} = 1;
                   7603:                     } else {
                   7604:                         $changed_items{$itemnum} = $key;
                   7605:                     }
                   7606:                 }
1.745     raeburn  7607:             }
                   7608:         }
1.749     raeburn  7609:     }
                   7610:     # get lock on access controls for file.
                   7611:     my $lockhash = {
                   7612:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7613:                                                        ':'.$env{'user.domain'},
                   7614:                    }; 
                   7615:     my $tries = 0;
                   7616:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7617:    
                   7618:     while (($gotlock ne 'ok') && $tries <3) {
                   7619:         $tries ++;
                   7620:         sleep 1;
                   7621:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7622:     }
                   7623:     if ($gotlock eq 'ok') {
                   7624:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7625:         my ($tmp)=keys(%curr_permissions);
                   7626:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7627:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7628:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7629:             if (ref($curr_controls) eq 'HASH') {
                   7630:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7631:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7632:                     if (defined($todelete{$itemnum})) {
                   7633:                         push(@deletions,$file_name."\0".$control_item);
                   7634:                     } else {
                   7635:                         if (defined($changed_items{$itemnum})) {
                   7636:                             $new_control{$changed_items{$itemnum}} = $now;
                   7637:                             push(@deletions,$file_name."\0".$control_item);
                   7638:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7639:                         } else {
                   7640:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7641:                         }
                   7642:                     }
1.745     raeburn  7643:                 }
                   7644:             }
                   7645:         }
1.970     raeburn  7646:         my ($group);
                   7647:         if (&is_course($domain,$user)) {
                   7648:             ($group,my $file) = split(/\//,$file_name,2);
                   7649:         }
1.749     raeburn  7650:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7651:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7652:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7653:         #  remove lock
                   7654:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7655:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7656:         my $sqlresult =
1.970     raeburn  7657:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7658:                                     $group);
1.749     raeburn  7659:     } else {
                   7660:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7661:     }
1.749     raeburn  7662:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7663: }
                   7664: 
1.827     raeburn  7665: sub make_public_indefinitely {
                   7666:     my ($requrl) = @_;
                   7667:     my $now = time;
                   7668:     my $action = 'activate';
                   7669:     my $aclnum = 0;
                   7670:     if (&is_portfolio_url($requrl)) {
                   7671:         my (undef,$udom,$unum,$file_name,$group) =
                   7672:             &parse_portfolio_url($requrl);
                   7673:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7674:         my %access_controls = &get_access_controls($current_perms,
                   7675:                                                    $group,$file_name);
                   7676:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7677:             my ($num,$scope,$end,$start) = 
                   7678:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7679:             if ($scope eq 'public') {
                   7680:                 if ($start <= $now && $end == 0) {
                   7681:                     $action = 'none';
                   7682:                 } else {
                   7683:                     $action = 'update';
                   7684:                     $aclnum = $num;
                   7685:                 }
                   7686:                 last;
                   7687:             }
                   7688:         }
                   7689:         if ($action eq 'none') {
                   7690:              return 'ok';
                   7691:         } else {
                   7692:             my %changes;
                   7693:             my $newend = 0;
                   7694:             my $newstart = $now;
                   7695:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7696:             $changes{$action}{$newkey} = {
                   7697:                 type => 'public',
                   7698:                 time => {
                   7699:                     start => $newstart,
                   7700:                     end   => $newend,
                   7701:                 },
                   7702:             };
                   7703:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7704:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7705:             return $outcome;
                   7706:         }
                   7707:     } else {
                   7708:         return 'invalid';
                   7709:     }
                   7710: }
                   7711: 
1.745     raeburn  7712: #------------------------------------------------------Get Marked as Read Only
                   7713: 
                   7714: sub get_marked_as_readonly {
                   7715:     my ($domain,$user,$what,$group) = @_;
                   7716:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7717:     my @readonly_files;
1.629     banghart 7718:     my $cmp1=$what;
                   7719:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7720:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7721:         if (defined($group)) {
                   7722:             if ($file_name !~ m-^\Q$group\E/-) {
                   7723:                 next;
                   7724:             }
                   7725:         }
1.561     banghart 7726:         if (ref($value) eq "ARRAY"){
                   7727:             foreach my $stored_what (@{$value}) {
1.629     banghart 7728:                 my $cmp2=$stored_what;
1.759     albertel 7729:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7730:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7731:                 }
1.629     banghart 7732:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7733:                     push(@readonly_files, $file_name);
1.745     raeburn  7734:                     last;
1.563     banghart 7735:                 } elsif (!defined($what)) {
                   7736:                     push(@readonly_files, $file_name);
1.745     raeburn  7737:                     last;
1.561     banghart 7738:                 }
                   7739:             }
1.745     raeburn  7740:         }
1.561     banghart 7741:     }
                   7742:     return @readonly_files;
                   7743: }
1.577     banghart 7744: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7745: 
1.577     banghart 7746: sub get_marked_as_readonly_hash {
1.745     raeburn  7747:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7748:     my %readonly_files;
1.745     raeburn  7749:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7750:         if (defined($group)) {
                   7751:             if ($file_name !~ m-^\Q$group\E/-) {
                   7752:                 next;
                   7753:             }
                   7754:         }
1.577     banghart 7755:         if (ref($value) eq "ARRAY"){
                   7756:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7757:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7758:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7759:                         if ($lock_descriptor eq 'graded') {
                   7760:                             $readonly_files{$file_name} = 'graded';
                   7761:                         } elsif ($lock_descriptor eq 'handback') {
                   7762:                             $readonly_files{$file_name} = 'handback';
                   7763:                         } else {
                   7764:                             if (!exists($readonly_files{$file_name})) {
                   7765:                                 $readonly_files{$file_name} = 'locked';
                   7766:                             }
                   7767:                         }
1.745     raeburn  7768:                     }
1.750     banghart 7769:                 } 
1.577     banghart 7770:             }
                   7771:         } 
                   7772:     }
                   7773:     return %readonly_files;
                   7774: }
1.559     banghart 7775: # ------------------------------------------------------------ Unmark as Read Only
                   7776: 
                   7777: sub unmark_as_readonly {
1.629     banghart 7778:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7779:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7780:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7781:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7782:     my $symb_crs = $what;
                   7783:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7784:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7785:     my ($tmp)=keys(%current_permissions);
                   7786:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7787:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7788:     foreach my $file (@readonly_files) {
1.759     albertel 7789: 	my $clean_file = &declutter_portfile($file);
                   7790: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7791: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7792:         my @new_locks;
                   7793:         my @del_keys;
                   7794:         if (ref($current_locks) eq "ARRAY"){
                   7795:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7796:                 my $compare=$locker;
1.749     raeburn  7797:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7798:                     $compare=join('',@{$locker});
1.746     raeburn  7799:                     if ($compare ne $symb_crs) {
                   7800:                         push(@new_locks, $locker);
                   7801:                     }
1.563     banghart 7802:                 }
                   7803:             }
1.650     albertel 7804:             if (scalar(@new_locks) > 0) {
1.563     banghart 7805:                 $current_permissions{$file} = \@new_locks;
                   7806:             } else {
                   7807:                 push(@del_keys, $file);
1.613     albertel 7808:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7809:                 delete($current_permissions{$file});
1.563     banghart 7810:             }
                   7811:         }
1.561     banghart 7812:     }
1.613     albertel 7813:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7814:     return;
                   7815: }
1.512     banghart 7816: 
1.17      www      7817: # ------------------------------------------------------------ Directory lister
                   7818: 
                   7819: sub dirlist {
1.955     raeburn  7820:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7821:     $uri=~s/^\///;
                   7822:     $uri=~s/\/$//;
1.253     stredwic 7823:     my ($udom, $uname);
1.955     raeburn  7824:     if ($getuserdir) {
1.253     stredwic 7825:         $udom = $userdomain;
                   7826:         $uname = $username;
1.955     raeburn  7827:     } else {
                   7828:         (undef,$udom,$uname)=split(/\//,$uri);
                   7829:         if(defined($userdomain)) {
                   7830:             $udom = $userdomain;
                   7831:         }
                   7832:         if(defined($username)) {
                   7833:             $uname = $username;
                   7834:         }
1.253     stredwic 7835:     }
1.955     raeburn  7836:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7837: 
1.955     raeburn  7838:     $dirRoot = $perlvar{'lonDocRoot'};
                   7839:     if (defined($getpropath)) {
                   7840:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7841:         $dirRoot =~ s/\/$//;
1.955     raeburn  7842:     } elsif (defined($getuserdir)) {
                   7843:         my $subdir=$uname.'__';
                   7844:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7845:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7846:                    ."/$udom/$subdir/$uname";
                   7847:     } elsif (defined($alternateRoot)) {
                   7848:         $dirRoot = $alternateRoot;
1.751     banghart 7849:     }
1.253     stredwic 7850: 
                   7851:     if($udom) {
                   7852:         if($uname) {
1.955     raeburn  7853:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7854:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7855:                               .':'.&escape($uname).':'.&escape($udom),
                   7856:                               &homeserver($uname,$udom));
                   7857:             if ($listing eq 'unknown_cmd') {
                   7858:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7859:                                   &homeserver($uname,$udom));
                   7860:             } else {
                   7861:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7862:             }
1.605     matthew  7863:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7864:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7865: 				  &homeserver($uname,$udom));
1.605     matthew  7866:                 @listing_results = split(/:/,$listing);
                   7867:             } else {
                   7868:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7869:             }
                   7870:             return @listing_results;
1.955     raeburn  7871:         } elsif(!$alternateRoot) {
1.800     albertel 7872:             my %allusers;
1.841     albertel 7873: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7874:  	    foreach my $tryserver (keys(%servers)) {
                   7875:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7876:                                   &escape($udom),$tryserver);
                   7877:                 if ($listing eq 'unknown_cmd') {
                   7878: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7879: 				      $udom, $tryserver);
                   7880:                 } else {
                   7881:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7882:                 }
1.841     albertel 7883: 		if ($listing eq 'unknown_cmd') {
                   7884: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7885: 				      $udom, $tryserver);
                   7886: 		    @listing_results = split(/:/,$listing);
                   7887: 		} else {
                   7888: 		    @listing_results =
                   7889: 			map { &unescape($_); } split(/:/,$listing);
                   7890: 		}
                   7891: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7892: 		    $listing_results[0] ne 'empty'       &&
                   7893: 		    $listing_results[0] ne 'con_lost') {
                   7894: 		    foreach my $line (@listing_results) {
                   7895: 			my ($entry) = split(/&/,$line,2);
                   7896: 			$allusers{$entry} = 1;
                   7897: 		    }
                   7898: 		}
1.253     stredwic 7899:             }
                   7900:             my $alluserstr='';
1.800     albertel 7901:             foreach my $user (sort(keys(%allusers))) {
                   7902:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7903:             }
                   7904:             $alluserstr=~s/:$//;
                   7905:             return split(/:/,$alluserstr);
                   7906:         } else {
1.800     albertel 7907:             return ('missing user name');
1.253     stredwic 7908:         }
1.955     raeburn  7909:     } elsif(!defined($getpropath)) {
1.841     albertel 7910:         my @all_domains = sort(&all_domains());
1.955     raeburn  7911:         foreach my $domain (@all_domains) {
                   7912:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7913:         }
                   7914:         return @all_domains;
                   7915:     } else {
1.800     albertel 7916:         return ('missing domain');
1.275     stredwic 7917:     }
                   7918: }
                   7919: 
                   7920: # --------------------------------------------- GetFileTimestamp
                   7921: # This function utilizes dirlist and returns the date stamp for
                   7922: # when it was last modified.  It will also return an error of -1
                   7923: # if an error occurs
                   7924: 
                   7925: sub GetFileTimestamp {
1.955     raeburn  7926:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7927:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7928:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7929:     my ($fileStat) = 
                   7930:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7931:                                  undef,$getuserdir);
1.275     stredwic 7932:     my @stats = split('&', $fileStat);
                   7933:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7934:         # @stats contains first the filename, then the stat output
                   7935:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7936:     } else {
                   7937:         return -1;
1.253     stredwic 7938:     }
1.26      www      7939: }
                   7940: 
1.712     albertel 7941: sub stat_file {
                   7942:     my ($uri) = @_;
1.787     albertel 7943:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7944: 
1.955     raeburn  7945:     my ($udom,$uname,$file);
1.712     albertel 7946:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7947: 	($udom,$uname,$file) =
1.811     albertel 7948: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7949: 	$file = 'userfiles/'.$file;
                   7950:     }
                   7951:     if ($uri =~ m-^/res/-) {
                   7952: 	($udom,$uname) = 
1.807     albertel 7953: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7954: 	$file = $uri;
                   7955:     }
                   7956: 
                   7957:     if (!$udom || !$uname || !$file) {
                   7958: 	# unable to handle the uri
                   7959: 	return ();
                   7960:     }
1.956     raeburn  7961:     my $getpropath;
                   7962:     if ($file =~ /^userfiles\//) {
                   7963:         $getpropath = 1;
                   7964:     }
1.955     raeburn  7965:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7966:     my @stats = split('&', $result);
1.721     banghart 7967:     
1.712     albertel 7968:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7969: 	shift(@stats); #filename is first
                   7970: 	return @stats;
                   7971:     }
                   7972:     return ();
                   7973: }
                   7974: 
1.26      www      7975: # -------------------------------------------------------- Value of a Condition
                   7976: 
1.713     albertel 7977: # gets the value of a specific preevaluated condition
                   7978: #    stored in the string  $env{user.state.<cid>}
                   7979: # or looks up a condition reference in the bighash and if if hasn't
                   7980: # already been evaluated recurses into docondval to get the value of
                   7981: # the condition, then memoizing it to 
                   7982: #   $env{user.state.<cid>.<condition>}
1.40      www      7983: sub directcondval {
                   7984:     my $number=shift;
1.620     albertel 7985:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7986: 	&Apache::lonuserstate::evalstate();
                   7987:     }
1.713     albertel 7988:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7989: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7990:     } elsif ($number =~ /^_/) {
                   7991: 	my $sub_condition;
                   7992: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7993: 		&GDBM_READER(),0640)) {
                   7994: 	    $sub_condition=$bighash{'conditions'.$number};
                   7995: 	    untie(%bighash);
                   7996: 	}
                   7997: 	my $value = &docondval($sub_condition);
1.949     raeburn  7998: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7999: 	return $value;
                   8000:     }
1.620     albertel 8001:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8002:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8003:     } else {
                   8004:        return 2;
                   8005:     }
                   8006: }
                   8007: 
1.713     albertel 8008: # get the collection of conditions for this resource
1.26      www      8009: sub condval {
                   8010:     my $condidx=shift;
1.54      www      8011:     my $allpathcond='';
1.713     albertel 8012:     foreach my $cond (split(/\|/,$condidx)) {
                   8013: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8014: 	    $allpathcond.=
                   8015: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8016: 	}
1.191     harris41 8017:     }
1.54      www      8018:     $allpathcond=~s/\|$//;
1.713     albertel 8019:     return &docondval($allpathcond);
                   8020: }
                   8021: 
                   8022: #evaluates an expression of conditions
                   8023: sub docondval {
                   8024:     my ($allpathcond) = @_;
                   8025:     my $result=0;
                   8026:     if ($env{'request.course.id'}
                   8027: 	&& defined($allpathcond)) {
                   8028: 	my $operand='|';
                   8029: 	my @stack;
                   8030: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8031: 	    if ($chunk eq '(') {
                   8032: 		push @stack,($operand,$result);
                   8033: 	    } elsif ($chunk eq ')') {
                   8034: 		my $before=pop @stack;
                   8035: 		if (pop @stack eq '&') {
                   8036: 		    $result=$result>$before?$before:$result;
                   8037: 		} else {
                   8038: 		    $result=$result>$before?$result:$before;
                   8039: 		}
                   8040: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8041: 		$operand=$chunk;
                   8042: 	    } else {
                   8043: 		my $new=directcondval($chunk);
                   8044: 		if ($operand eq '&') {
                   8045: 		    $result=$result>$new?$new:$result;
                   8046: 		} else {
                   8047: 		    $result=$result>$new?$result:$new;
                   8048: 		}
                   8049: 	    }
                   8050: 	}
1.26      www      8051:     }
                   8052:     return $result;
1.421     albertel 8053: }
                   8054: 
                   8055: # ---------------------------------------------------- Devalidate courseresdata
                   8056: 
                   8057: sub devalidatecourseresdata {
                   8058:     my ($coursenum,$coursedomain)=@_;
                   8059:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8060:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8061: }
                   8062: 
1.763     www      8063: 
1.200     www      8064: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8065: #
                   8066: #  Parameters:
                   8067: #      $coursenum    - Number of the course.
                   8068: #      $coursedomain - Domain at which the course was created.
                   8069: #  Returns:
                   8070: #     A hash of the course parameters along (I think) with timestamps
                   8071: #     and version info.
1.877     foxr     8072: 
1.624     albertel 8073: sub get_courseresdata {
                   8074:     my ($coursenum,$coursedomain)=@_;
1.200     www      8075:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8076:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8077:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8078:     my %dumpreply;
1.417     albertel 8079:     unless (defined($cached)) {
1.624     albertel 8080: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8081: 	$result=\%dumpreply;
1.251     albertel 8082: 	my ($tmp) = keys(%dumpreply);
                   8083: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8084: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8085: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8086: 	    return $tmp;
1.416     albertel 8087: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8088: 	    $result=undef;
1.599     albertel 8089: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8090: 	}
                   8091:     }
1.624     albertel 8092:     return $result;
                   8093: }
                   8094: 
1.633     albertel 8095: sub devalidateuserresdata {
                   8096:     my ($uname,$udom)=@_;
                   8097:     my $hashid="$udom:$uname";
                   8098:     &devalidate_cache_new('userres',$hashid);
                   8099: }
                   8100: 
1.624     albertel 8101: sub get_userresdata {
                   8102:     my ($uname,$udom)=@_;
                   8103:     #most student don\'t have any data set, check if there is some data
                   8104:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8105: 
                   8106:     my $hashid="$udom:$uname";
                   8107:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8108:     if (!defined($cached)) {
                   8109: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8110: 	$result=\%resourcedata;
                   8111: 	&do_cache_new('userres',$hashid,$result,600);
                   8112:     }
                   8113:     my ($tmp)=keys(%$result);
                   8114:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8115: 	return $result;
                   8116:     }
                   8117:     #error 2 occurs when the .db doesn't exist
                   8118:     if ($tmp!~/error: 2 /) {
1.672     albertel 8119: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8120: 		 " Trying to get resource data for ".
                   8121: 		 $uname." at ".$udom.": ".
                   8122: 		 $tmp."</font>");
                   8123:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8124: 	#&EXT_cache_set($udom,$uname);
                   8125: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8126: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8127:     }
                   8128:     return $tmp;
                   8129: }
1.879     foxr     8130: #----------------------------------------------- resdata - return resource data
                   8131: #  Purpose:
                   8132: #    Return resource data for either users or for a course.
                   8133: #  Parameters:
                   8134: #     $name      - Course/user name.
                   8135: #     $domain    - Name of the domain the user/course is registered on.
                   8136: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8137: #     @which     - Array of names of resources desired.
                   8138: #  Returns:
                   8139: #     The value of the first reasource in @which that is found in the
                   8140: #     resource hash.
                   8141: #  Exceptional Conditions:
                   8142: #     If the $type passed in is not valid (not the string 'course' or 
                   8143: #     'user', an undefined  reference is returned.
                   8144: #     If none of the resources are found, an undef is returned
1.624     albertel 8145: sub resdata {
                   8146:     my ($name,$domain,$type,@which)=@_;
                   8147:     my $result;
                   8148:     if ($type eq 'course') {
                   8149: 	$result=&get_courseresdata($name,$domain);
                   8150:     } elsif ($type eq 'user') {
                   8151: 	$result=&get_userresdata($name,$domain);
                   8152:     }
                   8153:     if (!ref($result)) { return $result; }    
1.251     albertel 8154:     foreach my $item (@which) {
1.927     albertel 8155: 	if (defined($result->{$item->[0]})) {
                   8156: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8157: 	}
1.250     albertel 8158:     }
1.291     albertel 8159:     return undef;
1.200     www      8160: }
                   8161: 
1.379     matthew  8162: #
                   8163: # EXT resource caching routines
                   8164: #
                   8165: 
                   8166: sub clear_EXT_cache_status {
1.383     albertel 8167:     &delenv('cache.EXT.');
1.379     matthew  8168: }
                   8169: 
                   8170: sub EXT_cache_status {
                   8171:     my ($target_domain,$target_user) = @_;
1.383     albertel 8172:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8173:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8174:         # We know already the user has no data
                   8175:         return 1;
                   8176:     } else {
                   8177:         return 0;
                   8178:     }
                   8179: }
                   8180: 
                   8181: sub EXT_cache_set {
                   8182:     my ($target_domain,$target_user) = @_;
1.383     albertel 8183:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8184:     #&appenv({$cachename => time});
1.379     matthew  8185: }
                   8186: 
1.28      www      8187: # --------------------------------------------------------- Value of a Variable
1.58      www      8188: sub EXT {
1.715     albertel 8189: 
1.395     albertel 8190:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8191:     unless ($varname) { return ''; }
1.218     albertel 8192:     #get real user name/domain, courseid and symb
                   8193:     my $courseid;
1.359     albertel 8194:     my $publicuser;
1.427     www      8195:     if ($symbparm) {
                   8196: 	$symbparm=&get_symb_from_alias($symbparm);
                   8197:     }
1.218     albertel 8198:     if (!($uname && $udom)) {
1.790     albertel 8199:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8200:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8201:     } else {
1.620     albertel 8202: 	$courseid=$env{'request.course.id'};
1.218     albertel 8203:     }
1.48      www      8204:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8205:     my $rest;
1.320     albertel 8206:     if (defined($therest[0])) {
1.48      www      8207:        $rest=join('.',@therest);
                   8208:     } else {
                   8209:        $rest='';
                   8210:     }
1.320     albertel 8211: 
1.57      www      8212:     my $qualifierrest=$qualifier;
                   8213:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8214:     my $spacequalifierrest=$space;
                   8215:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8216:     if ($realm eq 'user') {
1.48      www      8217: # --------------------------------------------------------------- user.resource
                   8218: 	if ($space eq 'resource') {
1.651     albertel 8219: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8220: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8221: 		 &&
1.744     albertel 8222: 		 ($symbparm eq &symbread()) ) {	
                   8223: 		# if we are in the middle of processing the resource the
                   8224: 		# get the value we are planning on committing
                   8225:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8226:                     return $Apache::lonhomework::results{$qualifierrest};
                   8227:                 } else {
                   8228:                     return $Apache::lonhomework::history{$qualifierrest};
                   8229:                 }
1.335     albertel 8230: 	    } else {
1.359     albertel 8231: 		my %restored;
1.620     albertel 8232: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8233: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8234: 		} else {
                   8235: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8236: 		}
1.335     albertel 8237: 		return $restored{$qualifierrest};
                   8238: 	    }
1.48      www      8239: # ----------------------------------------------------------------- user.access
                   8240:         } elsif ($space eq 'access') {
1.218     albertel 8241: 	    # FIXME - not supporting calls for a specific user
1.48      www      8242:             return &allowed($qualifier,$rest);
                   8243: # ------------------------------------------ user.preferences, user.environment
                   8244:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8245: 	    if (($uname eq $env{'user.name'}) &&
                   8246: 		($udom eq $env{'user.domain'})) {
                   8247: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8248: 	    } else {
1.359     albertel 8249: 		my %returnhash;
                   8250: 		if (!$publicuser) {
                   8251: 		    %returnhash=&userenvironment($udom,$uname,
                   8252: 						 $qualifierrest);
                   8253: 		}
1.218     albertel 8254: 		return $returnhash{$qualifierrest};
                   8255: 	    }
1.48      www      8256: # ----------------------------------------------------------------- user.course
                   8257:         } elsif ($space eq 'course') {
1.218     albertel 8258: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8259:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8260: # ------------------------------------------------------------------- user.role
                   8261:         } elsif ($space eq 'role') {
1.218     albertel 8262: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8263:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8264:             if ($qualifier eq 'value') {
                   8265: 		return $role;
                   8266:             } elsif ($qualifier eq 'extent') {
                   8267:                 return $where;
                   8268:             }
                   8269: # ----------------------------------------------------------------- user.domain
                   8270:         } elsif ($space eq 'domain') {
1.218     albertel 8271:             return $udom;
1.48      www      8272: # ------------------------------------------------------------------- user.name
                   8273:         } elsif ($space eq 'name') {
1.218     albertel 8274:             return $uname;
1.48      www      8275: # ---------------------------------------------------- Any other user namespace
1.29      www      8276:         } else {
1.359     albertel 8277: 	    my %reply;
                   8278: 	    if (!$publicuser) {
                   8279: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8280: 	    }
                   8281: 	    return $reply{$qualifierrest};
1.48      www      8282:         }
1.236     www      8283:     } elsif ($realm eq 'query') {
                   8284: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8285:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8286: 						[$spacequalifierrest]);
1.620     albertel 8287: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8288:    } elsif ($realm eq 'request') {
1.48      www      8289: # ------------------------------------------------------------- request.browser
                   8290:         if ($space eq 'browser') {
1.430     www      8291: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8292: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8293: 		    return 1;
                   8294: 		} else {
                   8295: 		    return 0;
                   8296: 		}
                   8297: 	    } else {
1.620     albertel 8298: 		return $env{'browser.'.$qualifier};
1.430     www      8299: 	    }
1.57      www      8300: # ------------------------------------------------------------ request.filename
                   8301:         } else {
1.620     albertel 8302:             return $env{'request.'.$spacequalifierrest};
1.29      www      8303:         }
1.28      www      8304:     } elsif ($realm eq 'course') {
1.48      www      8305: # ---------------------------------------------------------- course.description
1.620     albertel 8306:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8307:     } elsif ($realm eq 'resource') {
1.165     www      8308: 
1.620     albertel 8309: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8310: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8311: 	}
1.693     albertel 8312: 
                   8313: 	if ($space eq 'title') {
                   8314: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8315: 	    return &gettitle($symbparm);
                   8316: 	}
                   8317: 	
                   8318: 	if ($space eq 'map') {
                   8319: 	    my ($map) = &decode_symb($symbparm);
                   8320: 	    return &symbread($map);
                   8321: 	}
1.905     albertel 8322: 	if ($space eq 'filename') {
                   8323: 	    if ($symbparm) {
                   8324: 		return &clutter((&decode_symb($symbparm))[2]);
                   8325: 	    }
                   8326: 	    return &hreflocation('',$env{'request.filename'});
                   8327: 	}
1.693     albertel 8328: 
                   8329: 	my ($section, $group, @groups);
1.593     albertel 8330: 	my ($courselevelm,$courselevel);
1.539     albertel 8331: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8332: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8333: 
1.218     albertel 8334: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8335: 
1.60      www      8336: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8337: 	    my $symbp=$symbparm;
1.735     albertel 8338: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8339: 
                   8340: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8341: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8342: 
1.620     albertel 8343: 	    if (($env{'user.name'} eq $uname) &&
                   8344: 		($env{'user.domain'} eq $udom)) {
                   8345: 		$section=$env{'request.course.sec'};
1.733     raeburn  8346:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8347:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8348: 	    } else {
1.539     albertel 8349: 		if (! defined($usection)) {
1.551     albertel 8350: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8351: 		} else {
                   8352: 		    $section = $usection;
                   8353: 		}
1.733     raeburn  8354:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8355: 	    }
                   8356: 
                   8357: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8358: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8359: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8360: 
1.593     albertel 8361: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8362: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8363: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8364: 
1.60      www      8365: # ----------------------------------------------------------- first, check user
1.624     albertel 8366: 
                   8367: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8368: 				       ([$courselevelr,'resource'],
                   8369: 					[$courselevelm,'map'     ],
                   8370: 					[$courselevel, 'course'  ]));
1.931     albertel 8371: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8372: 
1.594     albertel 8373: # ------------------------------------------------ second, check some of course
1.684     raeburn  8374:             my $coursereply;
1.691     raeburn  8375:             if (@groups > 0) {
                   8376:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8377:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8378:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8379:             }
1.96      www      8380: 
1.684     raeburn  8381: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8382: 				  $env{'course.'.$courseid.'.domain'},
                   8383: 				  'course',
                   8384: 				  ([$seclevelr,   'resource'],
                   8385: 				   [$seclevelm,   'map'     ],
                   8386: 				   [$seclevel,    'course'  ],
                   8387: 				   [$courselevelr,'resource']));
                   8388: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8389: 
1.60      www      8390: # ------------------------------------------------------ third, check map parms
1.218     albertel 8391: 	    my %parmhash=();
                   8392: 	    my $thisparm='';
                   8393: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8394: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8395: 		    &GDBM_READER(),0640)) {
1.218     albertel 8396: 		$thisparm=$parmhash{$symbparm};
                   8397: 		untie(%parmhash);
                   8398: 	    }
1.927     albertel 8399: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8400: 	}
1.594     albertel 8401: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8402: 
1.218     albertel 8403: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8404: 	my $filename;
                   8405: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8406: 	if ($symbparm) {
1.409     www      8407: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8408: 	} else {
1.620     albertel 8409: 	    $filename=$env{'request.filename'};
1.282     albertel 8410: 	}
                   8411: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8412: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8413: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8414: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8415: 
1.927     albertel 8416: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8417: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8418: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8419: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8420: 				     $env{'course.'.$courseid.'.domain'},
                   8421: 				     'course',
1.927     albertel 8422: 				     ([$courselevelm,'map'   ],
                   8423: 				      [$courselevel, 'course']));
                   8424: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8425: 	}
1.145     www      8426: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8427: 	unless ($space eq '0') {
1.336     albertel 8428: 	    my @parts=split(/_/,$space);
                   8429: 	    my $id=pop(@parts);
                   8430: 	    my $part=join('_',@parts);
                   8431: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8432: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8433: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8434: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8435: 	}
1.395     albertel 8436: 	if ($recurse) { return undef; }
                   8437: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8438: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8439: # ---------------------------------------------------- Any other user namespace
                   8440:     } elsif ($realm eq 'environment') {
                   8441: # ----------------------------------------------------------------- environment
1.620     albertel 8442: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8443: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8444: 	} else {
1.770     albertel 8445: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8446: 		return '';
                   8447: 	    }
1.219     albertel 8448: 	    my %returnhash=&userenvironment($udom,$uname,
                   8449: 					    $spacequalifierrest);
                   8450: 	    return $returnhash{$spacequalifierrest};
                   8451: 	}
1.28      www      8452:     } elsif ($realm eq 'system') {
1.48      www      8453: # ----------------------------------------------------------------- system.time
                   8454: 	if ($space eq 'time') {
                   8455: 	    return time;
                   8456:         }
1.696     albertel 8457:     } elsif ($realm eq 'server') {
                   8458: # ----------------------------------------------------------------- system.time
                   8459: 	if ($space eq 'name') {
                   8460: 	    return $ENV{'SERVER_NAME'};
                   8461:         }
1.28      www      8462:     }
1.48      www      8463:     return '';
1.61      www      8464: }
                   8465: 
1.927     albertel 8466: sub get_reply {
                   8467:     my ($reply_value) = @_;
1.940     raeburn  8468:     if (ref($reply_value) eq 'ARRAY') {
                   8469:         if (wantarray) {
                   8470: 	    return @$reply_value;
                   8471:         }
                   8472:         return $reply_value->[0];
                   8473:     } else {
                   8474:         return $reply_value;
1.927     albertel 8475:     }
                   8476: }
                   8477: 
1.691     raeburn  8478: sub check_group_parms {
                   8479:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8480:     my @groupitems = ();
                   8481:     my $resultitem;
1.927     albertel 8482:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8483:     foreach my $group (@{$groups}) {
                   8484:         foreach my $level (@levels) {
1.927     albertel 8485:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8486:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8487:         }
                   8488:     }
                   8489:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8490:                             $env{'course.'.$courseid.'.domain'},
                   8491:                                      'course',@groupitems);
                   8492:     return $coursereply;
                   8493: }
                   8494: 
                   8495: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8496:     my ($courseid,@groups) = @_;
                   8497:     @groups = sort(@groups);
1.691     raeburn  8498:     return @groups;
                   8499: }
                   8500: 
1.395     albertel 8501: sub packages_tab_default {
                   8502:     my ($uri,$varname)=@_;
                   8503:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8504: 
                   8505:     my (@extension,@specifics,$do_default);
                   8506:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8507: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8508: 	if ($pack_type eq 'default') {
                   8509: 	    $do_default=1;
                   8510: 	} elsif ($pack_type eq 'extension') {
                   8511: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8512: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8513: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8514: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8515: 	}
                   8516:     }
                   8517:     # first look for a package that matches the requested part id
                   8518:     foreach my $package (@specifics) {
                   8519: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8520: 	next if ($pack_part ne $part);
                   8521: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8522: 	    return $packagetab{"$pack_type&$name&default"};
                   8523: 	}
                   8524:     }
                   8525:     # look for any possible matching non extension_ package
                   8526:     foreach my $package (@specifics) {
                   8527: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8528: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8529: 	    return $packagetab{"$pack_type&$name&default"};
                   8530: 	}
1.585     albertel 8531: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8532: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8533: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8534: 	}
                   8535:     }
1.738     albertel 8536:     # look for any posible extension_ match
                   8537:     foreach my $package (@extension) {
                   8538: 	my ($package,$pack_type)=@{$package};
                   8539: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8540: 	    return $packagetab{"$pack_type&$name&default"};
                   8541: 	}
                   8542: 	if (defined($packagetab{$package."&$name&default"})) {
                   8543: 	    return $packagetab{$package."&$name&default"};
                   8544: 	}
                   8545:     }
                   8546:     # look for a global default setting
                   8547:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8548: 	return $packagetab{"default&$name&default"};
                   8549:     }
1.395     albertel 8550:     return undef;
                   8551: }
                   8552: 
1.334     albertel 8553: sub add_prefix_and_part {
                   8554:     my ($prefix,$part)=@_;
                   8555:     my $keyroot;
                   8556:     if (defined($prefix) && $prefix !~ /^__/) {
                   8557: 	# prefix that has a part already
                   8558: 	$keyroot=$prefix;
                   8559:     } elsif (defined($prefix)) {
                   8560: 	# prefix that is missing a part
                   8561: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8562:     } else {
                   8563: 	# no prefix at all
                   8564: 	if (defined($part)) { $keyroot='_'.$part; }
                   8565:     }
                   8566:     return $keyroot;
                   8567: }
                   8568: 
1.71      www      8569: # ---------------------------------------------------------------- Get metadata
                   8570: 
1.599     albertel 8571: my %metaentry;
1.1070    www      8572: my %importedpartids;
1.71      www      8573: sub metadata {
1.176     www      8574:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8575:     $uri=&declutter($uri);
1.288     albertel 8576:     # if it is a non metadata possible uri return quickly
1.529     albertel 8577:     if (($uri eq '') || 
                   8578: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8579: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8580:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8581: 	return undef;
                   8582:     }
                   8583:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8584: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8585: 	return undef;
1.288     albertel 8586:     }
1.73      www      8587:     my $filename=$uri;
                   8588:     $uri=~s/\.meta$//;
1.172     www      8589: #
                   8590: # Is the metadata already cached?
1.177     www      8591: # Look at timestamp of caching
1.172     www      8592: # Everything is cached by the main uri, libraries are never directly cached
                   8593: #
1.428     albertel 8594:     if (!defined($liburi)) {
1.599     albertel 8595: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8596: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8597:     }
                   8598:     {
1.1069    www      8599: # Imported parts would go here
1.1070    www      8600:         my %importedids=();
                   8601:         my @origfileimportpartids=();
1.1069    www      8602:         my $importedparts=0;
1.172     www      8603: #
                   8604: # Is this a recursive call for a library?
                   8605: #
1.599     albertel 8606: #	if (! exists($metacache{$uri})) {
                   8607: #	    $metacache{$uri}={};
                   8608: #	}
1.924     albertel 8609: 	my $cachetime = 60*60;
1.171     www      8610:         if ($liburi) {
                   8611: 	    $liburi=&declutter($liburi);
                   8612:             $filename=$liburi;
1.401     bowersj2 8613:         } else {
1.599     albertel 8614: 	    &devalidate_cache_new('meta',$uri);
                   8615: 	    undef(%metaentry);
1.401     bowersj2 8616: 	}
1.140     www      8617:         my %metathesekeys=();
1.73      www      8618:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8619: 	my $metastring;
1.924     albertel 8620: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8621: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8622: 	    $metastring = 
1.929     albertel 8623: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8624: 					  ('grade_target' => 'meta'));
                   8625: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8626: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8627:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8628: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8629: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8630: 	    $metastring=&getfile($file);
1.489     albertel 8631: 	}
1.208     albertel 8632:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8633:         my $token;
1.140     www      8634:         undef %metathesekeys;
1.71      www      8635:         while ($token=$parser->get_token) {
1.339     albertel 8636: 	    if ($token->[0] eq 'S') {
                   8637: 		if (defined($token->[2]->{'package'})) {
1.172     www      8638: #
                   8639: # This is a package - get package info
                   8640: #
1.339     albertel 8641: 		    my $package=$token->[2]->{'package'};
                   8642: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8643: 		    if (defined($token->[2]->{'id'})) { 
                   8644: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8645: 		    }
1.599     albertel 8646: 		    if ($metaentry{':packages'}) {
                   8647: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8648: 		    } else {
1.599     albertel 8649: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8650: 		    }
1.736     albertel 8651: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8652: 			my $part=$keyroot;
                   8653: 			$part=~s/^\_//;
1.736     albertel 8654: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8655: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8656: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8657: 			    # ignore package.tab specified default values
                   8658:                             # here &package_tab_default() will fetch those
                   8659: 			    if ($subp eq 'default') { next; }
1.736     albertel 8660: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8661: 			    my $unikey;
                   8662: 			    if ($pack =~ /_0$/) {
                   8663: 				$unikey='parameter_0_'.$name;
                   8664: 				$part=0;
                   8665: 			    } else {
                   8666: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8667: 			    }
1.339     albertel 8668: 			    if ($subp eq 'display') {
                   8669: 				$value.=' [Part: '.$part.']';
                   8670: 			    }
1.599     albertel 8671: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8672: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8673: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8674: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8675: 			    }
1.599     albertel 8676: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8677: 				$metaentry{':'.$unikey}=
                   8678: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8679: 			    }
1.339     albertel 8680: 			}
                   8681: 		    }
                   8682: 		} else {
1.172     www      8683: #
                   8684: # This is not a package - some other kind of start tag
1.339     albertel 8685: #
                   8686: 		    my $entry=$token->[1];
1.1068    www      8687: 		    my $unikey='';
1.175     www      8688: 
1.339     albertel 8689: 		    if ($entry eq 'import') {
1.175     www      8690: #
                   8691: # Importing a library here
1.339     albertel 8692: #
1.1067    www      8693:                         my $location=$parser->get_text('/import');
                   8694:                         my $dir=$filename;
                   8695:                         $dir=~s|[^/]*$||;
                   8696:                         $location=&filelocation($dir,$location);
1.1069    www      8697:                        
1.1068    www      8698:                         my $importmode=$token->[2]->{'importmode'};
                   8699:                         if ($importmode eq 'problem') {
1.1069    www      8700: # Import as problem/response
1.1068    www      8701:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8702:                         } elsif ($importmode eq 'part') {
                   8703: # Import as part(s)
1.1069    www      8704:                            $importedparts=1;
                   8705: # We need to get the original file and the imported file to get the part order correct
                   8706: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8707: # Load and inspect original file
1.1070    www      8708:                            if ($#origfileimportpartids<0) {
                   8709:                               undef(%importedpartids);
                   8710:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8711:                               my $origfile=&getfile($origfilelocation);
                   8712:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8713:                            }
                   8714: 
1.1069    www      8715: # Load and inspect imported file
                   8716:                            my $impfile=&getfile($location);
                   8717:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8718:                            if ($#impfilepartids>=0) {
                   8719: # This problem had parts
1.1070    www      8720:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8721:                            } else {
                   8722: # Importing by turning a single problem into a problem part
                   8723: # It gets the import-tags ID as part-ID
                   8724:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8725:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8726:                            }
1.1068    www      8727:                         } else {
                   8728: # Normal import
                   8729:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8730:                            if (defined($token->[2]->{'id'})) {
                   8731:                               $unikey.='_'.$token->[2]->{'id'};
                   8732:                            }
1.1067    www      8733:                         }
                   8734: 
1.339     albertel 8735: 			if ($depthcount<20) {
1.736     albertel 8736: 			    my $metadata = 
                   8737: 				&metadata($uri,'keys', $location,$unikey,
                   8738: 					  $depthcount+1);
                   8739: 			    foreach my $meta (split(',',$metadata)) {
                   8740: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8741: 				$metathesekeys{$meta}=1;
1.339     albertel 8742: 			    }
1.1068    www      8743: 			
                   8744:                         }
1.1067    www      8745: 		    } else {
                   8746: #
                   8747: # Not importing, some other kind of non-package, non-library start tag
                   8748: # 
                   8749:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8750:                         if (defined($token->[2]->{'id'})) {
                   8751:                             $unikey.='_'.$token->[2]->{'id'};
                   8752:                         }
1.339     albertel 8753: 			if (defined($token->[2]->{'name'})) { 
                   8754: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8755: 			}
                   8756: 			$metathesekeys{$unikey}=1;
1.736     albertel 8757: 			foreach my $param (@{$token->[3]}) {
                   8758: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8759: 				$token->[2]->{$param};
1.339     albertel 8760: 			}
                   8761: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8762: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8763: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8764: 		 # only ws inside the tag, and not in default, so use default
                   8765: 		 # as value
1.599     albertel 8766: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8767: 			} elsif ( $internaltext =~ /\S/ ) {
                   8768: 		  # something interesting inside the tag
                   8769: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8770: 			} else {
1.908     albertel 8771: 		  # no interesting values, don't set a default
1.339     albertel 8772: 			}
1.172     www      8773: # end of not-a-package not-a-library import
1.339     albertel 8774: 		    }
1.172     www      8775: # end of not-a-package start tag
1.339     albertel 8776: 		}
1.172     www      8777: # the next is the end of "start tag"
1.339     albertel 8778: 	    }
                   8779: 	}
1.483     albertel 8780: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8781: 	$extension = lc($extension);
                   8782: 	if ($extension eq 'htm') { $extension='html'; }
                   8783: 
1.737     albertel 8784: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8785: 	    #no specific packages #how's our extension
                   8786: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8787: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8788: 					 \%metathesekeys);
                   8789: 	}
1.883     albertel 8790: 
                   8791: 	if (!exists($metaentry{':packages'})
                   8792: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8793: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8794: 		#no specific packages well let's get default then
                   8795: 		if ($key!~/^default&/) { next; }
1.488     albertel 8796: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8797: 					     \%metathesekeys);
                   8798: 	    }
                   8799: 	}
1.338     www      8800: # are there custom rights to evaluate
1.599     albertel 8801: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8802: 
1.338     www      8803:     #
                   8804:     # Importing a rights file here
1.339     albertel 8805:     #
                   8806: 	    unless ($depthcount) {
1.599     albertel 8807: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8808: 		my $dir=$filename;
                   8809: 		$dir=~s|[^/]*$||;
                   8810: 		$location=&filelocation($dir,$location);
1.736     albertel 8811: 		my $rights_metadata =
                   8812: 		    &metadata($uri,'keys',$location,'_rights',
                   8813: 			      $depthcount+1);
                   8814: 		foreach my $rights (split(',',$rights_metadata)) {
                   8815: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8816: 		    $metathesekeys{$rights}=1;
1.339     albertel 8817: 		}
                   8818: 	    }
                   8819: 	}
1.737     albertel 8820: 	# uniqifiy package listing
                   8821: 	my %seen;
                   8822: 	my @uniq_packages =
                   8823: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8824: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8825: 
1.1070    www      8826:         if ($importedparts) {
                   8827: # We had imported parts and need to rebuild partorder
                   8828:            $metaentry{':partorder'}='';
                   8829:            $metathesekeys{'partorder'}=1;
                   8830:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8831:                if ($origfileimportpartids[$index] eq 'part') {
                   8832: # original part, part of the problem
                   8833:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8834:                } else {
                   8835: # we have imported parts at this position
                   8836:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8837:                }
                   8838:            }
                   8839:            $metaentry{':partorder'}=~s/^\,//;
                   8840:         }
                   8841: 
1.737     albertel 8842: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8843: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8844: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8845: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8846: # this is the end of "was not already recently cached
1.71      www      8847:     }
1.599     albertel 8848:     return $metaentry{':'.$what};
1.261     albertel 8849: }
                   8850: 
1.488     albertel 8851: sub metadata_create_package_def {
1.483     albertel 8852:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8853:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8854:     if ($subp eq 'default') { next; }
                   8855:     
1.599     albertel 8856:     if (defined($metaentry{':packages'})) {
                   8857: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8858:     } else {
1.599     albertel 8859: 	$metaentry{':packages'}=$package;
1.483     albertel 8860:     }
                   8861:     my $value=$packagetab{$key};
                   8862:     my $unikey;
                   8863:     $unikey='parameter_0_'.$name;
1.599     albertel 8864:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8865:     $$metathesekeys{$unikey}=1;
1.599     albertel 8866:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8867: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8868:     }
1.599     albertel 8869:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8870: 	$metaentry{':'.$unikey}=
                   8871: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8872:     }
                   8873: }
                   8874: 
1.261     albertel 8875: sub metadata_generate_part0 {
                   8876:     my ($metadata,$metacache,$uri) = @_;
                   8877:     my %allnames;
1.737     albertel 8878:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8879: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8880: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8881: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8882: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8883: 	    $allnames{$name}=$part;
                   8884: 	  }
                   8885: 	}
                   8886:     }
                   8887:     foreach my $name (keys(%allnames)) {
                   8888:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8889:       my $key=":parameter_0_$name";
1.261     albertel 8890:       $$metacache{"$key.part"}='0';
                   8891:       $$metacache{"$key.name"}=$name;
1.428     albertel 8892:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8893: 					   $allnames{$name}.'_'.$name.
                   8894: 					   '.type'};
1.428     albertel 8895:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8896: 			     '.display'};
1.644     www      8897:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8898:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8899:       $$metacache{"$key.display"}=$olddis;
                   8900:     }
1.71      www      8901: }
                   8902: 
1.764     albertel 8903: # ------------------------------------------------------ Devalidate title cache
                   8904: 
                   8905: sub devalidate_title_cache {
                   8906:     my ($url)=@_;
                   8907:     if (!$env{'request.course.id'}) { return; }
                   8908:     my $symb=&symbread($url);
                   8909:     if (!$symb) { return; }
                   8910:     my $key=$env{'request.course.id'}."\0".$symb;
                   8911:     &devalidate_cache_new('title',$key);
                   8912: }
                   8913: 
1.1014    droeschl 8914: # ------------------------------------------------- Get the title of a course
                   8915: 
                   8916: sub current_course_title {
                   8917:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8918: }
1.301     www      8919: # ------------------------------------------------- Get the title of a resource
                   8920: 
                   8921: sub gettitle {
                   8922:     my $urlsymb=shift;
                   8923:     my $symb=&symbread($urlsymb);
1.534     albertel 8924:     if ($symb) {
1.620     albertel 8925: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8926: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8927: 	if (defined($cached)) { 
                   8928: 	    return $result;
                   8929: 	}
1.534     albertel 8930: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8931: 	my $title='';
1.907     albertel 8932: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8933: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8934: 	} else {
                   8935: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8936: 		    &GDBM_READER(),0640)) {
                   8937: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8938: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8939: 		untie(%bighash);
                   8940: 	    }
1.534     albertel 8941: 	}
                   8942: 	$title=~s/\&colon\;/\:/gs;
                   8943: 	if ($title) {
1.599     albertel 8944: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8945: 	}
                   8946: 	$urlsymb=$url;
                   8947:     }
                   8948:     my $title=&metadata($urlsymb,'title');
                   8949:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8950:     return $title;
1.301     www      8951: }
1.613     albertel 8952: 
1.614     albertel 8953: sub get_slot {
                   8954:     my ($which,$cnum,$cdom)=@_;
                   8955:     if (!$cnum || !$cdom) {
1.790     albertel 8956: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8957: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8958: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8959:     }
1.703     albertel 8960:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8961:     my %slotinfo;
                   8962:     if (exists($remembered{$key})) {
                   8963: 	$slotinfo{$which} = $remembered{$key};
                   8964:     } else {
                   8965: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8966: 	&Apache::lonhomework::showhash(%slotinfo);
                   8967: 	my ($tmp)=keys(%slotinfo);
                   8968: 	if ($tmp=~/^error:/) { return (); }
                   8969: 	$remembered{$key} = $slotinfo{$which};
                   8970:     }
1.616     albertel 8971:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8972: 	return %{$slotinfo{$which}};
                   8973:     }
                   8974:     return $slotinfo{$which};
1.614     albertel 8975: }
1.31      www      8976: # ------------------------------------------------- Update symbolic store links
                   8977: 
                   8978: sub symblist {
                   8979:     my ($mapname,%newhash)=@_;
1.438     www      8980:     $mapname=&deversion(&declutter($mapname));
1.31      www      8981:     my %hash;
1.620     albertel 8982:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8983:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8984:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8985: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8986: 		next if ($url eq 'last_known'
                   8987: 			 && $env{'form.no_update_last_known'});
                   8988: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8989: 						    $newhash{$url}->[1],
                   8990: 						    $newhash{$url}->[0]);
1.191     harris41 8991:             }
1.31      www      8992:             if (untie(%hash)) {
                   8993: 		return 'ok';
                   8994:             }
                   8995:         }
                   8996:     }
                   8997:     return 'error';
1.212     www      8998: }
                   8999: 
                   9000: # --------------------------------------------------------------- Verify a symb
                   9001: 
                   9002: sub symbverify {
1.510     www      9003:     my ($symb,$thisurl)=@_;
                   9004:     my $thisfn=$thisurl;
1.439     www      9005:     $thisfn=&declutter($thisfn);
1.215     www      9006: # direct jump to resource in page or to a sequence - will construct own symbs
                   9007:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9008: # check URL part
1.409     www      9009:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9010: 
1.431     www      9011:     unless ($url eq $thisfn) { return 0; }
1.213     www      9012: 
1.216     www      9013:     $symb=&symbclean($symb);
1.510     www      9014:     $thisurl=&deversion($thisurl);
1.439     www      9015:     $thisfn=&deversion($thisfn);
1.213     www      9016: 
                   9017:     my %bighash;
                   9018:     my $okay=0;
1.431     www      9019: 
1.620     albertel 9020:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9021:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9022:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9023:             $thisurl =~ s/\?.+$//;
                   9024:         }
1.510     www      9025:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9026:         unless ($ids) {
                   9027:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9028:             $ids=$bighash{$idkey};
1.216     www      9029:         }
                   9030:         if ($ids) {
                   9031: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9032: 	    foreach my $id (split(/\,/,$ids)) {
                   9033: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9034:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9035:                    $symb =~ s/\?.+$//;
                   9036:                }
1.216     www      9037:                if (
                   9038:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9039:    eq $symb) { 
1.620     albertel 9040: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9041: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9042:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9043: 		       $okay=1; 
                   9044: 		   }
                   9045: 	       }
1.216     www      9046: 	   }
                   9047:         }
1.213     www      9048: 	untie(%bighash);
                   9049:     }
                   9050:     return $okay;
1.31      www      9051: }
                   9052: 
1.210     www      9053: # --------------------------------------------------------------- Clean-up symb
                   9054: 
                   9055: sub symbclean {
                   9056:     my $symb=shift;
1.568     albertel 9057:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9058: # remove version from map
                   9059:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9060: 
1.210     www      9061: # remove version from URL
                   9062:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9063: 
1.507     www      9064: # remove wrapper
                   9065: 
1.510     www      9066:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9067:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9068:     return $symb;
1.409     www      9069: }
                   9070: 
                   9071: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9072: 
                   9073: sub encode_symb {
                   9074:     my ($map,$resid,$url)=@_;
                   9075:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9076: }
1.409     www      9077: 
                   9078: sub decode_symb {
1.568     albertel 9079:     my $symb=shift;
                   9080:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9081:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9082:     return (&fixversion($map),$resid,&fixversion($url));
                   9083: }
                   9084: 
                   9085: sub fixversion {
                   9086:     my $fn=shift;
1.609     banghart 9087:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9088:     my %bighash;
                   9089:     my $uri=&clutter($fn);
1.620     albertel 9090:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9091: # is this cached?
1.599     albertel 9092:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9093:     if (defined($cached)) { return $result; }
                   9094: # unfortunately not cached, or expired
1.620     albertel 9095:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9096: 	    &GDBM_READER(),0640)) {
                   9097:  	if ($bighash{'version_'.$uri}) {
                   9098:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9099:  	    unless (($version eq 'mostrecent') || 
                   9100: 		    ($version==&getversion($uri))) {
1.440     www      9101:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9102:  	    }
                   9103:  	}
                   9104:  	untie %bighash;
1.413     www      9105:     }
1.599     albertel 9106:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9107: }
                   9108: 
                   9109: sub deversion {
                   9110:     my $url=shift;
                   9111:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9112:     return $url;
1.210     www      9113: }
                   9114: 
1.31      www      9115: # ------------------------------------------------------ Return symb list entry
                   9116: 
                   9117: sub symbread {
1.249     www      9118:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9119:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9120:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9121: # no filename provided? try from environment
1.44      www      9122:     unless ($thisfn) {
1.620     albertel 9123:         if ($env{'request.symb'}) {
                   9124: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9125: 	}
1.620     albertel 9126: 	$thisfn=$env{'request.filename'};
1.44      www      9127:     }
1.569     albertel 9128:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9129: # is that filename actually a symb? Verify, clean, and return
                   9130:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9131: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9132: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9133: 	}
1.242     www      9134:     }
1.44      www      9135:     $thisfn=declutter($thisfn);
1.31      www      9136:     my %hash;
1.37      www      9137:     my %bighash;
                   9138:     my $syval='';
1.620     albertel 9139:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9140:         my $targetfn = $thisfn;
1.609     banghart 9141:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9142:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9143:         }
1.687     albertel 9144: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9145: 	    $targetfn=$1;
                   9146: 	}
1.620     albertel 9147:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9148:                       &GDBM_READER(),0640)) {
1.481     raeburn  9149: 	    $syval=$hash{$targetfn};
1.37      www      9150:             untie(%hash);
                   9151:         }
                   9152: # ---------------------------------------------------------- There was an entry
                   9153:         if ($syval) {
1.601     albertel 9154: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9155: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9156: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9157: 		    #return $env{$cache_str}='';
1.601     albertel 9158: 		#}    
                   9159: 		#$syval.=$1;
                   9160: 	    #}
1.37      www      9161:         } else {
                   9162: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9163:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9164:                             &GDBM_READER(),0640)) {
1.37      www      9165: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9166:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9167:               unless ($ids) { 
                   9168:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9169:               }
                   9170:               unless ($ids) {
                   9171: # alias?
                   9172: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9173:               }
1.37      www      9174:               if ($ids) {
                   9175: # ------------------------------------------------------------------- Has ID(s)
                   9176:                  my @possibilities=split(/\,/,$ids);
1.39      www      9177:                  if ($#possibilities==0) {
                   9178: # ----------------------------------------------- There is only one possibility
1.37      www      9179: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9180: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9181: 						    $resid,$thisfn);
1.249     www      9182:                  } elsif (!$donotrecurse) {
1.39      www      9183: # ------------------------------------------ There is more than one possibility
                   9184:                      my $realpossible=0;
1.800     albertel 9185:                      foreach my $id (@possibilities) {
                   9186: 			 my $file=$bighash{'src_'.$id};
1.39      www      9187:                          if (&allowed('bre',$file)) {
1.800     albertel 9188:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9189:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9190: 				$realpossible++;
1.626     albertel 9191:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9192: 						    $resid,$thisfn);
1.39      www      9193:                             }
                   9194: 			 }
1.191     harris41 9195:                      }
1.39      www      9196: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9197:                  } else {
                   9198:                      $syval='';
1.37      www      9199:                  }
                   9200: 	      }
                   9201:               untie(%bighash)
1.481     raeburn  9202:            }
1.31      www      9203:         }
1.62      www      9204:         if ($syval) {
1.620     albertel 9205: 	    return $env{$cache_str}=$syval;
1.62      www      9206:         }
1.31      www      9207:     }
1.949     raeburn  9208:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9209:     return $env{$cache_str}='';
1.31      www      9210: }
                   9211: 
                   9212: # ---------------------------------------------------------- Return random seed
                   9213: 
1.32      www      9214: sub numval {
                   9215:     my $txt=shift;
                   9216:     $txt=~tr/A-J/0-9/;
                   9217:     $txt=~tr/a-j/0-9/;
                   9218:     $txt=~tr/K-T/0-9/;
                   9219:     $txt=~tr/k-t/0-9/;
                   9220:     $txt=~tr/U-Z/0-5/;
                   9221:     $txt=~tr/u-z/0-5/;
                   9222:     $txt=~s/\D//g;
1.564     albertel 9223:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9224:     return int($txt);
1.368     albertel 9225: }
                   9226: 
1.484     albertel 9227: sub numval2 {
                   9228:     my $txt=shift;
                   9229:     $txt=~tr/A-J/0-9/;
                   9230:     $txt=~tr/a-j/0-9/;
                   9231:     $txt=~tr/K-T/0-9/;
                   9232:     $txt=~tr/k-t/0-9/;
                   9233:     $txt=~tr/U-Z/0-5/;
                   9234:     $txt=~tr/u-z/0-5/;
                   9235:     $txt=~s/\D//g;
                   9236:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9237:     my $total;
                   9238:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9239:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9240:     return int($total);
                   9241: }
                   9242: 
1.575     albertel 9243: sub numval3 {
                   9244:     use integer;
                   9245:     my $txt=shift;
                   9246:     $txt=~tr/A-J/0-9/;
                   9247:     $txt=~tr/a-j/0-9/;
                   9248:     $txt=~tr/K-T/0-9/;
                   9249:     $txt=~tr/k-t/0-9/;
                   9250:     $txt=~tr/U-Z/0-5/;
                   9251:     $txt=~tr/u-z/0-5/;
                   9252:     $txt=~s/\D//g;
                   9253:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9254:     my $total;
                   9255:     foreach my $val (@txts) { $total+=$val; }
                   9256:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9257:     return $total;
                   9258: }
                   9259: 
1.675     albertel 9260: sub digest {
                   9261:     my ($data)=@_;
                   9262:     my $digest=&Digest::MD5::md5($data);
                   9263:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9264:     my ($e,$f);
                   9265:     {
                   9266:         use integer;
                   9267:         $e=($a+$b);
                   9268:         $f=($c+$d);
                   9269:         if ($_64bit) {
                   9270:             $e=(($e<<32)>>32);
                   9271:             $f=(($f<<32)>>32);
                   9272:         }
                   9273:     }
                   9274:     if (wantarray) {
                   9275: 	return ($e,$f);
                   9276:     } else {
                   9277: 	my $g;
                   9278: 	{
                   9279: 	    use integer;
                   9280: 	    $g=($e+$f);
                   9281: 	    if ($_64bit) {
                   9282: 		$g=(($g<<32)>>32);
                   9283: 	    }
                   9284: 	}
                   9285: 	return $g;
                   9286:     }
                   9287: }
                   9288: 
1.368     albertel 9289: sub latest_rnd_algorithm_id {
1.675     albertel 9290:     return '64bit5';
1.366     albertel 9291: }
1.32      www      9292: 
1.503     albertel 9293: sub get_rand_alg {
                   9294:     my ($courseid)=@_;
1.790     albertel 9295:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9296:     if ($courseid) {
1.620     albertel 9297: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9298:     }
                   9299:     return &latest_rnd_algorithm_id();
                   9300: }
                   9301: 
1.562     albertel 9302: sub validCODE {
                   9303:     my ($CODE)=@_;
                   9304:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9305:     return 0;
                   9306: }
                   9307: 
1.491     albertel 9308: sub getCODE {
1.620     albertel 9309:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9310:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9311: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9312: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9313: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9314:     }
                   9315:     return undef;
                   9316: }
                   9317: 
1.31      www      9318: sub rndseed {
1.155     albertel 9319:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9320:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9321:     if (!defined($symb)) {
1.366     albertel 9322: 	unless ($symb=$wsymb) { return time; }
                   9323:     }
                   9324:     if (!$courseid) { $courseid=$wcourseid; }
                   9325:     if (!$domain) { $domain=$wdomain; }
                   9326:     if (!$username) { $username=$wusername }
1.503     albertel 9327:     my $which=&get_rand_alg();
1.1110    www      9328: 
1.491     albertel 9329:     if (defined(&getCODE())) {
1.675     albertel 9330: 	if ($which eq '64bit5') {
                   9331: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9332: 	} elsif ($which eq '64bit4') {
1.575     albertel 9333: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9334: 	} else {
                   9335: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9336: 	}
1.675     albertel 9337:     } elsif ($which eq '64bit5') {
                   9338: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9339:     } elsif ($which eq '64bit4') {
                   9340: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9341:     } elsif ($which eq '64bit3') {
                   9342: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9343:     } elsif ($which eq '64bit2') {
                   9344: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9345:     } elsif ($which eq '64bit') {
                   9346: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9347:     }
                   9348:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9349: }
                   9350: 
                   9351: sub rndseed_32bit {
                   9352:     my ($symb,$courseid,$domain,$username)=@_;
                   9353:     {
                   9354: 	use integer;
                   9355: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9356: 	my $symbseed=numval($symb) << 22;
                   9357: 	my $namechck=unpack("%32C*",$username) << 17;
                   9358: 	my $nameseed=numval($username) << 12;
                   9359: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9360: 	my $courseseed=unpack("%32C*",$courseid);
                   9361: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9362: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9363: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9364: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9365: 	return $num;
                   9366:     }
                   9367: }
                   9368: 
                   9369: sub rndseed_64bit {
                   9370:     my ($symb,$courseid,$domain,$username)=@_;
                   9371:     {
                   9372: 	use integer;
                   9373: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9374: 	my $symbseed=numval($symb) << 10;
                   9375: 	my $namechck=unpack("%32S*",$username);
                   9376: 	
                   9377: 	my $nameseed=numval($username) << 21;
                   9378: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9379: 	my $courseseed=unpack("%32S*",$courseid);
                   9380: 	
                   9381: 	my $num1=$symbchck+$symbseed+$namechck;
                   9382: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9383: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9384: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9385: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9386: 	return "$num1,$num2";
1.155     albertel 9387:     }
1.366     albertel 9388: }
                   9389: 
1.443     albertel 9390: sub rndseed_64bit2 {
                   9391:     my ($symb,$courseid,$domain,$username)=@_;
                   9392:     {
                   9393: 	use integer;
                   9394: 	# strings need to be an even # of cahracters long, it it is odd the
                   9395:         # last characters gets thrown away
                   9396: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9397: 	my $symbseed=numval($symb) << 10;
                   9398: 	my $namechck=unpack("%32S*",$username.' ');
                   9399: 	
                   9400: 	my $nameseed=numval($username) << 21;
1.501     albertel 9401: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9402: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9403: 	
                   9404: 	my $num1=$symbchck+$symbseed+$namechck;
                   9405: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9406: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9407: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9408: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9409: 	return "$num1,$num2";
                   9410:     }
                   9411: }
                   9412: 
                   9413: sub rndseed_64bit3 {
                   9414:     my ($symb,$courseid,$domain,$username)=@_;
                   9415:     {
                   9416: 	use integer;
                   9417: 	# strings need to be an even # of cahracters long, it it is odd the
                   9418:         # last characters gets thrown away
                   9419: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9420: 	my $symbseed=numval2($symb) << 10;
                   9421: 	my $namechck=unpack("%32S*",$username.' ');
                   9422: 	
                   9423: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9424: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9425: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9426: 	
                   9427: 	my $num1=$symbchck+$symbseed+$namechck;
                   9428: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9429: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9430: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9431: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9432: 	
1.503     albertel 9433: 	return "$num1:$num2";
1.443     albertel 9434:     }
                   9435: }
                   9436: 
1.575     albertel 9437: sub rndseed_64bit4 {
                   9438:     my ($symb,$courseid,$domain,$username)=@_;
                   9439:     {
                   9440: 	use integer;
                   9441: 	# strings need to be an even # of cahracters long, it it is odd the
                   9442:         # last characters gets thrown away
                   9443: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9444: 	my $symbseed=numval3($symb) << 10;
                   9445: 	my $namechck=unpack("%32S*",$username.' ');
                   9446: 	
                   9447: 	my $nameseed=numval3($username) << 21;
                   9448: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9449: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9450: 	
                   9451: 	my $num1=$symbchck+$symbseed+$namechck;
                   9452: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9453: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9454: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9455: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9456: 	
1.575     albertel 9457: 	return "$num1:$num2";
                   9458:     }
                   9459: }
                   9460: 
1.675     albertel 9461: sub rndseed_64bit5 {
                   9462:     my ($symb,$courseid,$domain,$username)=@_;
                   9463:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9464:     return "$num1:$num2";
                   9465: }
                   9466: 
1.366     albertel 9467: sub rndseed_CODE_64bit {
                   9468:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9469:     {
1.366     albertel 9470: 	use integer;
1.443     albertel 9471: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9472: 	my $symbseed=numval2($symb);
1.491     albertel 9473: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9474: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9475: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9476: 	my $num1=$symbseed+$CODEchck;
                   9477: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9478: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9479: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9480: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9481: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9482: 	return "$num1:$num2";
1.366     albertel 9483:     }
                   9484: }
                   9485: 
1.575     albertel 9486: sub rndseed_CODE_64bit4 {
                   9487:     my ($symb,$courseid,$domain,$username)=@_;
                   9488:     {
                   9489: 	use integer;
                   9490: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9491: 	my $symbseed=numval3($symb);
                   9492: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9493: 	my $CODEseed=numval3(&getCODE());
                   9494: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9495: 	my $num1=$symbseed+$CODEchck;
                   9496: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9497: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9498: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9499: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9500: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9501: 	return "$num1:$num2";
                   9502:     }
                   9503: }
                   9504: 
1.675     albertel 9505: sub rndseed_CODE_64bit5 {
                   9506:     my ($symb,$courseid,$domain,$username)=@_;
                   9507:     my $code = &getCODE();
                   9508:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9509:     return "$num1:$num2";
                   9510: }
                   9511: 
1.366     albertel 9512: sub setup_random_from_rndseed {
                   9513:     my ($rndseed)=@_;
1.503     albertel 9514:     if ($rndseed =~/([,:])/) {
                   9515: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9516: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9517:     } else {
                   9518: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9519:     }
1.36      albertel 9520: }
                   9521: 
1.474     albertel 9522: sub latest_receipt_algorithm_id {
1.835     albertel 9523:     return 'receipt3';
1.474     albertel 9524: }
                   9525: 
1.480     www      9526: sub recunique {
                   9527:     my $fucourseid=shift;
                   9528:     my $unique;
1.835     albertel 9529:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9530: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9531: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9532:     } else {
                   9533: 	$unique=$perlvar{'lonReceipt'};
                   9534:     }
                   9535:     return unpack("%32C*",$unique);
                   9536: }
                   9537: 
                   9538: sub recprefix {
                   9539:     my $fucourseid=shift;
                   9540:     my $prefix;
1.835     albertel 9541:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9542: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9543: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9544:     } else {
                   9545: 	$prefix=$perlvar{'lonHostID'};
                   9546:     }
                   9547:     return unpack("%32C*",$prefix);
                   9548: }
                   9549: 
1.76      www      9550: sub ireceipt {
1.474     albertel 9551:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9552: 
                   9553:     my $return =&recprefix($fucourseid).'-';
                   9554: 
                   9555:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9556: 	$env{'request.state'} eq 'construct') {
                   9557: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9558: 	return $return;
                   9559:     }
                   9560: 
1.76      www      9561:     my $cuname=unpack("%32C*",$funame);
                   9562:     my $cudom=unpack("%32C*",$fudom);
                   9563:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9564:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9565:     my $cunique=&recunique($fucourseid);
1.474     albertel 9566:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9567:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9568: 
1.790     albertel 9569: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9570: 			       
                   9571: 	$return.= ($cunique%$cuname+
                   9572: 		   $cunique%$cudom+
                   9573: 		   $cusymb%$cuname+
                   9574: 		   $cusymb%$cudom+
                   9575: 		   $cucourseid%$cuname+
                   9576: 		   $cucourseid%$cudom+
                   9577: 		   $cpart%$cuname+
                   9578: 		   $cpart%$cudom);
                   9579:     } else {
                   9580: 	$return.= ($cunique%$cuname+
                   9581: 		   $cunique%$cudom+
                   9582: 		   $cusymb%$cuname+
                   9583: 		   $cusymb%$cudom+
                   9584: 		   $cucourseid%$cuname+
                   9585: 		   $cucourseid%$cudom);
                   9586:     }
                   9587:     return $return;
1.76      www      9588: }
                   9589: 
                   9590: sub receipt {
1.474     albertel 9591:     my ($part)=@_;
1.790     albertel 9592:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9593:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9594: }
1.260     ng       9595: 
1.790     albertel 9596: sub whichuser {
                   9597:     my ($passedsymb)=@_;
                   9598:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9599:     if (defined($env{'form.grade_symb'})) {
                   9600: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9601: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9602: 	if (!$allowed &&
                   9603: 	    exists($env{'request.course.sec'}) &&
                   9604: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9605: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9606: 			      '/'.$env{'request.course.sec'});
                   9607: 	}
                   9608: 	if ($allowed) {
                   9609: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9610: 	    $courseid=$tmp_courseid;
                   9611: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9612: 	    ($name)=&get_env_multiple('form.grade_username');
                   9613: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9614: 	}
                   9615:     }
                   9616:     if (!$passedsymb) {
                   9617: 	$symb=&symbread();
                   9618:     } else {
                   9619: 	$symb=$passedsymb;
                   9620:     }
                   9621:     $courseid=$env{'request.course.id'};
                   9622:     $domain=$env{'user.domain'};
                   9623:     $name=$env{'user.name'};
                   9624:     if ($name eq 'public' && $domain eq 'public') {
                   9625: 	if (!defined($env{'form.username'})) {
                   9626: 	    $env{'form.username'}.=time.rand(10000000);
                   9627: 	}
                   9628: 	$name.=$env{'form.username'};
                   9629:     }
                   9630:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9631: 
                   9632: }
                   9633: 
1.36      albertel 9634: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9635: # returns either the contents of the file or 
                   9636: # -1 if the file doesn't exist
1.481     raeburn  9637: #
                   9638: # if the target is a file that was uploaded via DOCS, 
                   9639: # a check will be made to see if a current copy exists on the local server,
                   9640: # if it does this will be served, otherwise a copy will be retrieved from
                   9641: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9642: # the local server.   
1.472     albertel 9643: 
1.36      albertel 9644: sub getfile {
1.538     albertel 9645:     my ($file) = @_;
1.609     banghart 9646:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9647:     &repcopy($file);
                   9648:     return &readfile($file);
                   9649: }
                   9650: 
                   9651: sub repcopy_userfile {
                   9652:     my ($file)=@_;
1.609     banghart 9653:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9654:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9655:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9656: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9657:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9658:     if (-e "$file") {
1.828     www      9659: # we already have a local copy, check it out
1.538     albertel 9660: 	my @fileinfo = stat($file);
1.828     www      9661: 	my $rtncode;
                   9662: 	my $info;
1.538     albertel 9663: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9664: 	if ($lwpresp ne 'ok') {
1.828     www      9665: # there is no such file anymore, even though we had a local copy
1.482     albertel 9666: 	    if ($rtncode eq '404') {
1.538     albertel 9667: 		unlink($file);
1.482     albertel 9668: 	    }
                   9669: 	    return -1;
                   9670: 	}
                   9671: 	if ($info < $fileinfo[9]) {
1.828     www      9672: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9673: 	    return 'ok';
1.828     www      9674: 	} else {
                   9675: # the file is outdated, get rid of it
                   9676: 	    unlink($file);
1.482     albertel 9677: 	}
1.828     www      9678:     }
                   9679: # one way or the other, at this point, we don't have the file
                   9680: # construct the correct path for the file
                   9681:     my @parts = ($cdom,$cnum); 
                   9682:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9683: 	push @parts, split(/\//,$1);
                   9684:     }
                   9685:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9686:     foreach my $part (@parts) {
                   9687: 	$path .= '/'.$part;
                   9688: 	if (!-e $path) {
                   9689: 	    mkdir($path,0770);
1.482     albertel 9690: 	}
                   9691:     }
1.828     www      9692: # now the path exists for sure
                   9693: # get a user agent
                   9694:     my $ua=new LWP::UserAgent;
                   9695:     my $transferfile=$file.'.in.transfer';
                   9696: # FIXME: this should flock
                   9697:     if (-e $transferfile) { return 'ok'; }
                   9698:     my $request;
                   9699:     $uri=~s/^\///;
1.980     raeburn  9700:     my $homeserver = &homeserver($cnum,$cdom);
                   9701:     my $protocol = $protocol{$homeserver};
                   9702:     $protocol = 'http' if ($protocol ne 'https');
                   9703:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9704:     my $response=$ua->request($request,$transferfile);
                   9705: # did it work?
                   9706:     if ($response->is_error()) {
                   9707: 	unlink($transferfile);
                   9708: 	&logthis("Userfile repcopy failed for $uri");
                   9709: 	return -1;
                   9710:     }
                   9711: # worked, rename the transfer file
                   9712:     rename($transferfile,$file);
1.607     raeburn  9713:     return 'ok';
1.481     raeburn  9714: }
                   9715: 
1.517     albertel 9716: sub tokenwrapper {
                   9717:     my $uri=shift;
1.980     raeburn  9718:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9719:     $uri=~s|^/||;
1.620     albertel 9720:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9721:     my $token=$1;
1.552     albertel 9722:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9723:     if ($udom && $uname && $file) {
                   9724: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9725:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9726:         my $homeserver = &homeserver($uname,$udom);
                   9727:         my $protocol = $protocol{$homeserver};
                   9728:         $protocol = 'http' if ($protocol ne 'https');
                   9729:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9730:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9731:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9732:     } else {
                   9733:         return '/adm/notfound.html';
                   9734:     }
                   9735: }
                   9736: 
1.828     www      9737: # call with reqtype HEAD: get last modification time
                   9738: # call with reqtype GET: get the file contents
                   9739: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9740: #
1.481     raeburn  9741: sub getuploaded {
                   9742:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9743:     $uri=~s/^\///;
1.980     raeburn  9744:     my $homeserver = &homeserver($cnum,$cdom);
                   9745:     my $protocol = $protocol{$homeserver};
                   9746:     $protocol = 'http' if ($protocol ne 'https');
                   9747:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9748:     my $ua=new LWP::UserAgent;
                   9749:     my $request=new HTTP::Request($reqtype,$uri);
                   9750:     my $response=$ua->request($request);
                   9751:     $$rtncode = $response->code;
1.482     albertel 9752:     if (! $response->is_success()) {
                   9753: 	return 'failed';
                   9754:     }      
                   9755:     if ($reqtype eq 'HEAD') {
1.486     www      9756: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9757:     } elsif ($reqtype eq 'GET') {
                   9758: 	$$info = $response->content;
1.472     albertel 9759:     }
1.482     albertel 9760:     return 'ok';
1.36      albertel 9761: }
                   9762: 
1.481     raeburn  9763: sub readfile {
                   9764:     my $file = shift;
                   9765:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9766:     my $fh;
                   9767:     open($fh,"<$file");
                   9768:     my $a='';
1.800     albertel 9769:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9770:     return $a;
                   9771: }
                   9772: 
1.36      albertel 9773: sub filelocation {
1.590     banghart 9774:     my ($dir,$file) = @_;
                   9775:     my $location;
                   9776:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9777: 
                   9778:     if ($file =~ m-^/adm/-) {
                   9779: 	$file=~s-^/adm/wrapper/-/-;
                   9780: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9781:     }
1.882     albertel 9782: 
1.590     banghart 9783:     if ($file=~m:^/~:) { # is a contruction space reference
                   9784:         $location = $file;
                   9785:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9786:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9787: 	# is a correct contruction space reference
                   9788:         $location = $file;
1.956     raeburn  9789:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9790:         $location = $file;
1.609     banghart 9791:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9792:         my ($udom,$uname,$filename)=
1.811     albertel 9793:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9794:         my $home=&homeserver($uname,$udom);
                   9795:         my $is_me=0;
                   9796:         my @ids=&current_machine_ids();
                   9797:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9798:         if ($is_me) {
1.1117    foxr     9799:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9800:         } else {
                   9801:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9802:   	      $udom.'/'.$uname.'/'.$filename;
                   9803:         }
1.882     albertel 9804:     } elsif ($file =~ m-^/adm/-) {
                   9805: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9806:     } else {
                   9807:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9808:         $file=~s:^/res/:/:;
                   9809:         if ( !( $file =~ m:^/:) ) {
                   9810:             $location = $dir. '/'.$file;
                   9811:         } else {
                   9812:             $location = '/home/httpd/html/res'.$file;
                   9813:         }
1.59      albertel 9814:     }
1.590     banghart 9815:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9816:     while ($location=~m{/\.\./}) {
                   9817: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9818: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9819: 	} else {
                   9820: 	    $location=~ s{/\.\./}{/}g;
                   9821: 	}
                   9822:     } #remove dir/..
1.590     banghart 9823:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9824:     return $location;
1.46      www      9825: }
1.36      albertel 9826: 
1.46      www      9827: sub hreflocation {
                   9828:     my ($dir,$file)=@_;
1.980     raeburn  9829:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9830: 	$file=filelocation($dir,$file);
1.700     albertel 9831:     } elsif ($file=~m-^/adm/-) {
                   9832: 	$file=~s-^/adm/wrapper/-/-;
                   9833: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9834:     }
                   9835:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9836: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9837:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9838: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9839:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9840: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9841: 	    -/uploaded/$1/$2/-x;
1.46      www      9842:     }
1.913     albertel 9843:     if ($file=~ m{^/userfiles/}) {
                   9844: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9845:     }
1.462     albertel 9846:     return $file;
1.465     albertel 9847: }
                   9848: 
                   9849: sub current_machine_domains {
1.853     albertel 9850:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9851: }
                   9852: 
                   9853: sub machine_domains {
                   9854:     my ($hostname) = @_;
1.465     albertel 9855:     my @domains;
1.838     albertel 9856:     my %hostname = &all_hostnames();
1.465     albertel 9857:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9858: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9859: 	if ($hostname eq $name) {
1.844     albertel 9860: 	    push(@domains,&host_domain($id));
1.465     albertel 9861: 	}
                   9862:     }
                   9863:     return @domains;
                   9864: }
                   9865: 
                   9866: sub current_machine_ids {
1.853     albertel 9867:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9868: }
                   9869: 
                   9870: sub machine_ids {
                   9871:     my ($hostname) = @_;
                   9872:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9873:     my @ids;
1.888     albertel 9874:     my %name_to_host = &all_names();
1.889     albertel 9875:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9876: 	return @{ $name_to_host{$hostname} };
                   9877:     }
                   9878:     return;
1.31      www      9879: }
                   9880: 
1.824     raeburn  9881: sub additional_machine_domains {
                   9882:     my @domains;
                   9883:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9884:     while( my $line = <$fh>) {
                   9885:         $line =~ s/\s//g;
                   9886:         push(@domains,$line);
                   9887:     }
                   9888:     return @domains;
                   9889: }
                   9890: 
                   9891: sub default_login_domain {
                   9892:     my $domain = $perlvar{'lonDefDomain'};
                   9893:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9894:     foreach my $posdom (&current_machine_domains(),
                   9895:                         &additional_machine_domains()) {
                   9896:         if (lc($posdom) eq lc($testdomain)) {
                   9897:             $domain=$posdom;
                   9898:             last;
                   9899:         }
                   9900:     }
                   9901:     return $domain;
                   9902: }
                   9903: 
1.31      www      9904: # ------------------------------------------------------------- Declutters URLs
                   9905: 
                   9906: sub declutter {
                   9907:     my $thisfn=shift;
1.569     albertel 9908:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9909:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9910:     $thisfn=~s/^\///;
1.697     albertel 9911:     $thisfn=~s|^adm/wrapper/||;
                   9912:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9913:     $thisfn=~s/^res\///;
1.1032    raeburn  9914:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9915:         $thisfn=~s/\?.+$//;
                   9916:     }
1.268     www      9917:     return $thisfn;
                   9918: }
                   9919: 
                   9920: # ------------------------------------------------------------- Clutter up URLs
                   9921: 
                   9922: sub clutter {
                   9923:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9924:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9925: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9926:        $thisfn='/res'.$thisfn; 
                   9927:     }
1.1031    raeburn  9928:     if ($thisfn !~m|^/adm|) {
                   9929: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9930: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9931: 	} else {
                   9932: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9933: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9934: 	    if ($embstyle eq 'ssi'
                   9935: 		|| ($embstyle eq 'hdn')
                   9936: 		|| ($embstyle eq 'rat')
                   9937: 		|| ($embstyle eq 'prv')
                   9938: 		|| ($embstyle eq 'ign')) {
                   9939: 		#do nothing with these
                   9940: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9941: 		|| ($embstyle eq 'emb')
                   9942: 		|| ($embstyle eq 'wrp')) {
                   9943: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9944: 	    } elsif ($embstyle eq 'unk'
                   9945: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9946: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9947: 	    } else {
1.718     www      9948: #		&logthis("Got a blank emb style");
1.695     albertel 9949: 	    }
1.694     albertel 9950: 	}
                   9951:     }
1.31      www      9952:     return $thisfn;
1.12      www      9953: }
                   9954: 
1.787     albertel 9955: sub clutter_with_no_wrapper {
                   9956:     my $uri = &clutter(shift);
                   9957:     if ($uri =~ m-^/adm/-) {
                   9958: 	$uri =~ s-^/adm/wrapper/-/-;
                   9959: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9960:     }
                   9961:     return $uri;
                   9962: }
                   9963: 
1.557     albertel 9964: sub freeze_escape {
                   9965:     my ($value)=@_;
                   9966:     if (ref($value)) {
                   9967: 	$value=&nfreeze($value);
                   9968: 	return '__FROZEN__'.&escape($value);
                   9969:     }
                   9970:     return &escape($value);
                   9971: }
                   9972: 
1.11      www      9973: 
1.557     albertel 9974: sub thaw_unescape {
                   9975:     my ($value)=@_;
                   9976:     if ($value =~ /^__FROZEN__/) {
                   9977: 	substr($value,0,10,undef);
                   9978: 	$value=&unescape($value);
                   9979: 	return &thaw($value);
                   9980:     }
                   9981:     return &unescape($value);
                   9982: }
                   9983: 
1.436     albertel 9984: sub correct_line_ends {
                   9985:     my ($result)=@_;
                   9986:     $$result =~s/\r\n/\n/mg;
                   9987:     $$result =~s/\r/\n/mg;
1.415     albertel 9988: }
1.1       albertel 9989: # ================================================================ Main Program
                   9990: 
1.184     www      9991: sub goodbye {
1.204     albertel 9992:    &logthis("Starting Shut down");
1.443     albertel 9993: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9994:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9995: #converted
1.599     albertel 9996: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9997:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9998: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9999: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10000: #1.1 only
1.870     albertel 10001: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10002: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10003: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10004: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10005:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10006:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10007:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10008:    &flushcourselogs();
                   10009:    &logthis("Shutting down");
                   10010: }
                   10011: 
1.852     albertel 10012: sub get_dns {
1.869     albertel 10013:     my ($url,$func,$ignore_cache) = @_;
                   10014:     if (!$ignore_cache) {
                   10015: 	my ($content,$cached)=
                   10016: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10017: 	if ($cached) {
                   10018: 	    &$func($content);
                   10019: 	    return;
                   10020: 	}
                   10021:     }
                   10022: 
                   10023:     my %alldns;
1.852     albertel 10024:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10025:     foreach my $dns (<$config>) {
                   10026: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10027:         my $line = $1;
                   10028:         my ($host,$protocol) = split(/:/,$line);
                   10029:         if ($protocol ne 'https') {
                   10030:             $protocol = 'http';
                   10031:         }
                   10032: 	$alldns{$host} = $protocol;
1.869     albertel 10033:     }
                   10034:     while (%alldns) {
                   10035: 	my ($dns) = keys(%alldns);
1.852     albertel 10036: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10037: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10038: 	my $response=$ua->request($request);
1.979     raeburn  10039:         delete($alldns{$dns});
1.852     albertel 10040: 	next if ($response->is_error());
                   10041: 	my @content = split("\n",$response->content);
1.869     albertel 10042: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10043: 	&$func(\@content);
1.869     albertel 10044: 	return;
1.852     albertel 10045:     }
                   10046:     close($config);
1.871     albertel 10047:     my $which = (split('/',$url))[3];
                   10048:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10049:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10050:     my @content = <$config>;
                   10051:     &$func(\@content);
                   10052:     return;
1.852     albertel 10053: }
1.327     albertel 10054: # ------------------------------------------------------------ Read domain file
                   10055: {
1.852     albertel 10056:     my $loaded;
1.846     albertel 10057:     my %domain;
                   10058: 
1.852     albertel 10059:     sub parse_domain_tab {
                   10060: 	my ($lines) = @_;
                   10061: 	foreach my $line (@$lines) {
                   10062: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10063: 
1.846     albertel 10064: 	    chomp($line);
1.852     albertel 10065: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10066: 	    my %this_domain;
                   10067: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10068: 			       'lang_def', 'city', 'longi', 'lati',
                   10069: 			       'primary') {
                   10070: 		$this_domain{$field} = shift(@elements);
                   10071: 	    }
                   10072: 	    $domain{$name} = \%this_domain;
1.852     albertel 10073: 	}
                   10074:     }
1.864     albertel 10075: 
                   10076:     sub reset_domain_info {
                   10077: 	undef($loaded);
                   10078: 	undef(%domain);
                   10079:     }
                   10080: 
1.852     albertel 10081:     sub load_domain_tab {
1.869     albertel 10082: 	my ($ignore_cache) = @_;
                   10083: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10084: 	my $fh;
                   10085: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10086: 	    my @lines = <$fh>;
                   10087: 	    &parse_domain_tab(\@lines);
1.448     albertel 10088: 	}
1.852     albertel 10089: 	close($fh);
                   10090: 	$loaded = 1;
1.327     albertel 10091:     }
1.846     albertel 10092: 
                   10093:     sub domain {
1.852     albertel 10094: 	&load_domain_tab() if (!$loaded);
                   10095: 
1.846     albertel 10096: 	my ($name,$what) = @_;
                   10097: 	return if ( !exists($domain{$name}) );
                   10098: 
                   10099: 	if (!$what) {
                   10100: 	    return $domain{$name}{'description'};
                   10101: 	}
                   10102: 	return $domain{$name}{$what};
                   10103:     }
1.974     raeburn  10104: 
                   10105:     sub domain_info {
                   10106:         &load_domain_tab() if (!$loaded);
                   10107:         return %domain;
                   10108:     }
                   10109: 
1.327     albertel 10110: }
                   10111: 
                   10112: 
1.1       albertel 10113: # ------------------------------------------------------------- Read hosts file
                   10114: {
1.838     albertel 10115:     my %hostname;
1.844     albertel 10116:     my %hostdom;
1.845     albertel 10117:     my %libserv;
1.852     albertel 10118:     my $loaded;
1.888     albertel 10119:     my %name_to_host;
1.1074    raeburn  10120:     my %internetdom;
1.1107    raeburn  10121:     my %LC_dns_serv;
1.852     albertel 10122: 
                   10123:     sub parse_hosts_tab {
                   10124: 	my ($file) = @_;
                   10125: 	foreach my $configline (@$file) {
                   10126: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10127:             chomp($configline);
                   10128: 	    if ($configline =~ /^\^/) {
                   10129:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10130:                     $LC_dns_serv{$1} = 1;
                   10131:                 }
                   10132:                 next;
                   10133:             }
1.1074    raeburn  10134: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10135: 	    $name=~s/\s//g;
                   10136: 	    if ($id && $domain && $role && $name) {
                   10137: 		$hostname{$id}=$name;
1.888     albertel 10138: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10139: 		$hostdom{$id}=$domain;
                   10140: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10141:                 if (defined($protocol)) {
                   10142:                     if ($protocol eq 'https') {
                   10143:                         $protocol{$id} = $protocol;
                   10144:                     } else {
                   10145:                         $protocol{$id} = 'http'; 
                   10146:                     }
1.968     raeburn  10147:                 } else {
1.969     raeburn  10148:                     $protocol{$id} = 'http';
1.968     raeburn  10149:                 }
1.1074    raeburn  10150:                 if (defined($intdom)) {
                   10151:                     $internetdom{$id} = $intdom;
                   10152:                 }
1.852     albertel 10153: 	    }
                   10154: 	}
                   10155:     }
1.864     albertel 10156:     
                   10157:     sub reset_hosts_info {
1.897     albertel 10158: 	&purge_remembered();
1.864     albertel 10159: 	&reset_domain_info();
                   10160: 	&reset_hosts_ip_info();
1.892     albertel 10161: 	undef(%name_to_host);
1.864     albertel 10162: 	undef(%hostname);
                   10163: 	undef(%hostdom);
                   10164: 	undef(%libserv);
                   10165: 	undef($loaded);
                   10166:     }
1.1       albertel 10167: 
1.852     albertel 10168:     sub load_hosts_tab {
1.869     albertel 10169: 	my ($ignore_cache) = @_;
                   10170: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10171: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10172: 	my @config = <$config>;
                   10173: 	&parse_hosts_tab(\@config);
                   10174: 	close($config);
                   10175: 	$loaded=1;
1.1       albertel 10176:     }
1.852     albertel 10177: 
1.838     albertel 10178:     sub hostname {
1.852     albertel 10179: 	&load_hosts_tab() if (!$loaded);
                   10180: 
1.838     albertel 10181: 	my ($lonid) = @_;
                   10182: 	return $hostname{$lonid};
                   10183:     }
1.845     albertel 10184: 
1.838     albertel 10185:     sub all_hostnames {
1.852     albertel 10186: 	&load_hosts_tab() if (!$loaded);
                   10187: 
1.838     albertel 10188: 	return %hostname;
                   10189:     }
1.845     albertel 10190: 
1.888     albertel 10191:     sub all_names {
                   10192: 	&load_hosts_tab() if (!$loaded);
                   10193: 
                   10194: 	return %name_to_host;
                   10195:     }
                   10196: 
1.974     raeburn  10197:     sub all_host_domain {
                   10198:         &load_hosts_tab() if (!$loaded);
                   10199:         return %hostdom;
                   10200:     }
                   10201: 
1.845     albertel 10202:     sub is_library {
1.852     albertel 10203: 	&load_hosts_tab() if (!$loaded);
                   10204: 
1.845     albertel 10205: 	return exists($libserv{$_[0]});
                   10206:     }
                   10207: 
                   10208:     sub all_library {
1.852     albertel 10209: 	&load_hosts_tab() if (!$loaded);
                   10210: 
1.845     albertel 10211: 	return %libserv;
                   10212:     }
                   10213: 
1.1062    droeschl 10214:     sub unique_library {
                   10215: 	#2x reverse removes all hostnames that appear more than once
                   10216:         my %unique = reverse &all_library();
                   10217:         return reverse %unique;
                   10218:     }
                   10219: 
1.841     albertel 10220:     sub get_servers {
1.852     albertel 10221: 	&load_hosts_tab() if (!$loaded);
                   10222: 
1.841     albertel 10223: 	my ($domain,$type) = @_;
                   10224: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10225: 	                                          : %hostname;
                   10226: 	my %result;
1.842     albertel 10227: 	if (ref($domain) eq 'ARRAY') {
                   10228: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10229: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10230: 		    $result{$host} = $hostname;
                   10231: 		}
                   10232: 	    }
                   10233: 	} else {
                   10234: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10235: 		if ($hostdom{$host} eq $domain) {
                   10236: 		    $result{$host} = $hostname;
                   10237: 		}
1.841     albertel 10238: 	    }
                   10239: 	}
                   10240: 	return %result;
                   10241:     }
1.845     albertel 10242: 
1.1062    droeschl 10243:     sub get_unique_servers {
                   10244:         my %unique = reverse &get_servers(@_);
                   10245: 	return reverse %unique;
                   10246:     }
                   10247: 
1.844     albertel 10248:     sub host_domain {
1.852     albertel 10249: 	&load_hosts_tab() if (!$loaded);
                   10250: 
1.844     albertel 10251: 	my ($lonid) = @_;
                   10252: 	return $hostdom{$lonid};
                   10253:     }
                   10254: 
1.841     albertel 10255:     sub all_domains {
1.852     albertel 10256: 	&load_hosts_tab() if (!$loaded);
                   10257: 
1.841     albertel 10258: 	my %seen;
                   10259: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10260: 	return @uniq;
                   10261:     }
1.1074    raeburn  10262: 
                   10263:     sub internet_dom {
                   10264:         &load_hosts_tab() if (!$loaded);
                   10265: 
                   10266:         my ($lonid) = @_;
                   10267:         return $internetdom{$lonid};
                   10268:     }
1.1107    raeburn  10269: 
                   10270:     sub is_LC_dns {
                   10271:         &load_hosts_tab() if (!$loaded);
                   10272: 
                   10273:         my ($hostname) = @_;
                   10274:         return exists($LC_dns_serv{$hostname});
                   10275:     }
                   10276: 
1.1       albertel 10277: }
                   10278: 
1.847     albertel 10279: { 
                   10280:     my %iphost;
1.856     albertel 10281:     my %name_to_ip;
                   10282:     my %lonid_to_ip;
1.869     albertel 10283: 
1.847     albertel 10284:     sub get_hosts_from_ip {
                   10285: 	my ($ip) = @_;
                   10286: 	my %iphosts = &get_iphost();
                   10287: 	if (ref($iphosts{$ip})) {
                   10288: 	    return @{$iphosts{$ip}};
                   10289: 	}
                   10290: 	return;
1.839     albertel 10291:     }
1.864     albertel 10292:     
                   10293:     sub reset_hosts_ip_info {
                   10294: 	undef(%iphost);
                   10295: 	undef(%name_to_ip);
                   10296: 	undef(%lonid_to_ip);
                   10297:     }
1.856     albertel 10298: 
                   10299:     sub get_host_ip {
                   10300: 	my ($lonid) = @_;
                   10301: 	if (exists($lonid_to_ip{$lonid})) {
                   10302: 	    return $lonid_to_ip{$lonid};
                   10303: 	}
                   10304: 	my $name=&hostname($lonid);
                   10305:    	my $ip = gethostbyname($name);
                   10306: 	return if (!$ip || length($ip) ne 4);
                   10307: 	$ip=inet_ntoa($ip);
                   10308: 	$name_to_ip{$name}   = $ip;
                   10309: 	$lonid_to_ip{$lonid} = $ip;
                   10310: 	return $ip;
                   10311:     }
1.847     albertel 10312:     
                   10313:     sub get_iphost {
1.869     albertel 10314: 	my ($ignore_cache) = @_;
1.894     albertel 10315: 
1.869     albertel 10316: 	if (!$ignore_cache) {
                   10317: 	    if (%iphost) {
                   10318: 		return %iphost;
                   10319: 	    }
                   10320: 	    my ($ip_info,$cached)=
                   10321: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10322: 	    if ($cached) {
                   10323: 		%iphost      = %{$ip_info->[0]};
                   10324: 		%name_to_ip  = %{$ip_info->[1]};
                   10325: 		%lonid_to_ip = %{$ip_info->[2]};
                   10326: 		return %iphost;
                   10327: 	    }
                   10328: 	}
1.894     albertel 10329: 
                   10330: 	# get yesterday's info for fallback
                   10331: 	my %old_name_to_ip;
                   10332: 	my ($ip_info,$cached)=
                   10333: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10334: 	if ($cached) {
                   10335: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10336: 	}
                   10337: 
1.888     albertel 10338: 	my %name_to_host = &all_names();
                   10339: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10340: 	    my $ip;
                   10341: 	    if (!exists($name_to_ip{$name})) {
                   10342: 		$ip = gethostbyname($name);
                   10343: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10344: 		    if (defined($old_name_to_ip{$name})) {
                   10345: 			$ip = $old_name_to_ip{$name};
                   10346: 			&logthis("Can't find $name defaulting to old $ip");
                   10347: 		    } else {
                   10348: 			&logthis("Name $name no IP found");
                   10349: 			next;
                   10350: 		    }
                   10351: 		} else {
                   10352: 		    $ip=inet_ntoa($ip);
1.847     albertel 10353: 		}
                   10354: 		$name_to_ip{$name} = $ip;
                   10355: 	    } else {
                   10356: 		$ip = $name_to_ip{$name};
1.653     albertel 10357: 	    }
1.888     albertel 10358: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10359: 		$lonid_to_ip{$id} = $ip;
                   10360: 	    }
                   10361: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10362: 	}
1.869     albertel 10363: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10364: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10365: 				      48*60*60);
1.869     albertel 10366: 
1.847     albertel 10367: 	return %iphost;
1.598     albertel 10368:     }
                   10369: 
1.992     raeburn  10370:     #
                   10371:     #  Given a DNS returns the loncapa host name for that DNS 
                   10372:     # 
                   10373:     sub host_from_dns {
                   10374:         my ($dns) = @_;
                   10375:         my @hosts;
                   10376:         my $ip;
                   10377: 
1.993     raeburn  10378:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10379:             $ip = $name_to_ip{$dns};
                   10380:         }
                   10381:         if (!$ip) {
                   10382:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10383:             if (length($ip) == 4) { 
                   10384: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10385:             }
                   10386:         }
                   10387:         if ($ip) {
                   10388: 	    @hosts = get_hosts_from_ip($ip);
                   10389: 	    return $hosts[0];
                   10390:         }
                   10391:         return undef;
1.986     foxr     10392:     }
1.992     raeburn  10393: 
1.1074    raeburn  10394:     sub get_internet_names {
                   10395:         my ($lonid) = @_;
                   10396:         return if ($lonid eq '');
                   10397:         my ($idnref,$cached)=
                   10398:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10399:         if ($cached) {
                   10400:             return $idnref;
                   10401:         }
                   10402:         my $ip = &get_host_ip($lonid);
                   10403:         my @hosts = &get_hosts_from_ip($ip);
                   10404:         my %iphost = &get_iphost();
                   10405:         my (@idns,%seen);
                   10406:         foreach my $id (@hosts) {
                   10407:             my $dom = &host_domain($id);
                   10408:             my $prim_id = &domain($dom,'primary');
                   10409:             my $prim_ip = &get_host_ip($prim_id);
                   10410:             next if ($seen{$prim_ip});
                   10411:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10412:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10413:                     my $intdom = &internet_dom($id);
                   10414:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10415:                         push(@idns,$intdom);
                   10416:                     }
                   10417:                 }
                   10418:             }
                   10419:             $seen{$prim_ip} = 1;
                   10420:         }
                   10421:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10422:     }
                   10423: 
1.986     foxr     10424: }
                   10425: 
1.1079    raeburn  10426: sub all_loncaparevs {
                   10427:     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);
                   10428: }
                   10429: 
1.862     albertel 10430: BEGIN {
                   10431: 
                   10432: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10433:     unless ($readit) {
                   10434: {
                   10435:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10436:     %perlvar = (%perlvar,%{$configvars});
                   10437: }
                   10438: 
                   10439: 
1.1       albertel 10440: # ------------------------------------------------------ Read spare server file
                   10441: {
1.448     albertel 10442:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10443: 
                   10444:     while (my $configline=<$config>) {
                   10445:        chomp($configline);
1.284     matthew  10446:        if ($configline) {
1.784     albertel 10447: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10448: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10449: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10450:        }
                   10451:     }
1.448     albertel 10452:     close($config);
1.1       albertel 10453: }
1.11      www      10454: # ------------------------------------------------------------ Read permissions
                   10455: {
1.448     albertel 10456:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10457: 
                   10458:     while (my $configline=<$config>) {
1.448     albertel 10459: 	chomp($configline);
                   10460: 	if ($configline) {
                   10461: 	    my ($role,$perm)=split(/ /,$configline);
                   10462: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10463: 	}
1.11      www      10464:     }
1.448     albertel 10465:     close($config);
1.11      www      10466: }
                   10467: 
                   10468: # -------------------------------------------- Read plain texts for permissions
                   10469: {
1.448     albertel 10470:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10471: 
                   10472:     while (my $configline=<$config>) {
1.448     albertel 10473: 	chomp($configline);
                   10474: 	if ($configline) {
1.742     raeburn  10475: 	    my ($short,@plain)=split(/:/,$configline);
                   10476:             %{$prp{$short}} = ();
                   10477: 	    if (@plain > 0) {
                   10478:                 $prp{$short}{'std'} = $plain[0];
                   10479:                 for (my $i=1; $i<@plain; $i++) {
                   10480:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10481:                 }
                   10482:             }
1.448     albertel 10483: 	}
1.135     www      10484:     }
1.448     albertel 10485:     close($config);
1.135     www      10486: }
                   10487: 
                   10488: # ---------------------------------------------------------- Read package table
                   10489: {
1.448     albertel 10490:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10491: 
                   10492:     while (my $configline=<$config>) {
1.483     albertel 10493: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10494: 	chomp($configline);
                   10495: 	my ($short,$plain)=split(/:/,$configline);
                   10496: 	my ($pack,$name)=split(/\&/,$short);
                   10497: 	if ($plain ne '') {
                   10498: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10499: 	    $packagetab{$short}=$plain; 
                   10500: 	}
1.11      www      10501:     }
1.448     albertel 10502:     close($config);
1.329     matthew  10503: }
                   10504: 
1.1073    raeburn  10505: # ---------------------------------------------------------- Read loncaparev table
                   10506: {
                   10507:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10508:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10509:             while (my $configline=<$config>) {
                   10510:                 chomp($configline);
                   10511:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10512:                 $loncaparevs{$hostid}=$loncaparev;
                   10513:             }
                   10514:             close($config);
                   10515:         }
                   10516:     }
                   10517: }
                   10518: 
1.1074    raeburn  10519: # ---------------------------------------------------------- Read serverhostID table
                   10520: {
                   10521:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10522:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10523:             while (my $configline=<$config>) {
                   10524:                 chomp($configline);
                   10525:                 my ($name,$id)=split(/:/,$configline);
                   10526:                 $serverhomeIDs{$name}=$id;
                   10527:             }
                   10528:             close($config);
                   10529:         }
                   10530:     }
                   10531: }
                   10532: 
1.1079    raeburn  10533: {
                   10534:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10535:     if (-e $file) {
                   10536:         my $parser = HTML::LCParser->new($file);
                   10537:         while (my $token = $parser->get_token()) {
                   10538:             if ($token->[0] eq 'S') {
                   10539:                 my $item = $token->[1];
                   10540:                 my $name = $token->[2]{'name'};
                   10541:                 my $value = $token->[2]{'value'};
                   10542:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10543:                     my $release = $parser->get_text();
                   10544:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10545:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10546:                 }
                   10547:             }
                   10548:         }
                   10549:     }
1.1073    raeburn  10550: }
                   10551: 
1.329     matthew  10552: # ------------- set up temporary directory
                   10553: {
1.1117    foxr     10554:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10555: 
1.11      www      10556: }
                   10557: 
1.794     albertel 10558: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10559: 				'compress_threshold'=> 20_000,
                   10560:  			        });
1.185     www      10561: 
1.281     www      10562: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10563: $dumpcount=0;
1.958     www      10564: $locknum=0;
1.22      www      10565: 
1.163     harris41 10566: &logtouch();
1.672     albertel 10567: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10568: $readit=1;
1.564     albertel 10569:     {
                   10570: 	use integer;
                   10571: 	my $test=(2**32)+1;
1.568     albertel 10572: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10573: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10574:     }
1.195     www      10575: }
1.1       albertel 10576: }
1.179     www      10577: 
1.1       albertel 10578: 1;
1.191     harris41 10579: __END__
                   10580: 
1.243     albertel 10581: =pod
                   10582: 
1.191     harris41 10583: =head1 NAME
                   10584: 
1.243     albertel 10585: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10586: 
                   10587: =head1 SYNOPSIS
                   10588: 
1.243     albertel 10589: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10590: 
                   10591:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10592: 
1.243     albertel 10593: Common parameters:
                   10594: 
                   10595: =over 4
                   10596: 
                   10597: =item *
                   10598: 
                   10599: $uname : an internal username (if $cname expecting a course Id specifically)
                   10600: 
                   10601: =item *
                   10602: 
                   10603: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10604: 
                   10605: =item *
                   10606: 
                   10607: $symb : a resource instance identifier
                   10608: 
                   10609: =item *
                   10610: 
                   10611: $namespace : the name of a .db file that contains the data needed or
                   10612: being set.
                   10613: 
                   10614: =back
                   10615: 
1.394     bowersj2 10616: =head1 OVERVIEW
1.191     harris41 10617: 
1.394     bowersj2 10618: lonnet provides subroutines which interact with the
                   10619: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10620: about classes, users, and resources.
1.243     albertel 10621: 
                   10622: For many of these objects you can also use this to store data about
                   10623: them or modify them in various ways.
1.191     harris41 10624: 
1.394     bowersj2 10625: =head2 Symbs
1.191     harris41 10626: 
1.394     bowersj2 10627: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10628: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10629: map, the resource number of the resource in the map, and the URL of
                   10630: the resource itself. The latter is somewhat redundant, but might help
                   10631: if maps change.
                   10632: 
                   10633: An example is
                   10634: 
                   10635:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10636: 
                   10637: The respective map entry is
                   10638: 
                   10639:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10640:   title="Problem 2">
                   10641:  </resource>
                   10642: 
                   10643: Symbs are used by the random number generator, as well as to store and
                   10644: restore data specific to a certain instance of for example a problem.
                   10645: 
                   10646: =head2 Storing And Retrieving Data
                   10647: 
                   10648: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10649: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10650: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10651: is is the non-critical message twin of cstore. These functions are for
                   10652: handlers to store a perl hash to a user's permanent data space in an
                   10653: easy manner, and to retrieve it again on another call. It is expected
                   10654: that a handler would use this once at the beginning to retrieve data,
                   10655: and then again once at the end to send only the new data back.
                   10656: 
                   10657: The data is stored in the user's data directory on the user's
                   10658: homeserver under the ID of the course.
                   10659: 
                   10660: The hash that is returned by restore will have all of the previous
                   10661: value for all of the elements of the hash.
                   10662: 
                   10663: Example:
                   10664: 
                   10665:  #creating a hash
                   10666:  my %hash;
                   10667:  $hash{'foo'}='bar';
                   10668: 
                   10669:  #storing it
                   10670:  &Apache::lonnet::cstore(\%hash);
                   10671: 
                   10672:  #changing a value
                   10673:  $hash{'foo'}='notbar';
                   10674: 
                   10675:  #adding a new value
                   10676:  $hash{'bar'}='foo';
                   10677:  &Apache::lonnet::cstore(\%hash);
                   10678: 
                   10679:  #retrieving the hash
                   10680:  my %history=&Apache::lonnet::restore();
                   10681: 
                   10682:  #print the hash
                   10683:  foreach my $key (sort(keys(%history))) {
                   10684:    print("\%history{$key} = $history{$key}");
                   10685:  }
                   10686: 
                   10687: Will print out:
1.191     harris41 10688: 
1.394     bowersj2 10689:  %history{1:foo} = bar
                   10690:  %history{1:keys} = foo:timestamp
                   10691:  %history{1:timestamp} = 990455579
                   10692:  %history{2:bar} = foo
                   10693:  %history{2:foo} = notbar
                   10694:  %history{2:keys} = foo:bar:timestamp
                   10695:  %history{2:timestamp} = 990455580
                   10696:  %history{bar} = foo
                   10697:  %history{foo} = notbar
                   10698:  %history{timestamp} = 990455580
                   10699:  %history{version} = 2
                   10700: 
                   10701: Note that the special hash entries C<keys>, C<version> and
                   10702: C<timestamp> were added to the hash. C<version> will be equal to the
                   10703: total number of versions of the data that have been stored. The
                   10704: C<timestamp> attribute will be the UNIX time the hash was
                   10705: stored. C<keys> is available in every historical section to list which
                   10706: keys were added or changed at a specific historical revision of a
                   10707: hash.
                   10708: 
                   10709: B<Warning>: do not store the hash that restore returns directly. This
                   10710: will cause a mess since it will restore the historical keys as if the
                   10711: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10712: 
1.394     bowersj2 10713: Calling convention:
1.191     harris41 10714: 
1.394     bowersj2 10715:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10716:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10717: 
1.394     bowersj2 10718: For more detailed information, see lonnet specific documentation.
1.191     harris41 10719: 
1.394     bowersj2 10720: =head1 RETURN MESSAGES
1.191     harris41 10721: 
1.394     bowersj2 10722: =over 4
1.191     harris41 10723: 
1.394     bowersj2 10724: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10725: 
1.394     bowersj2 10726: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10727: when the connection is brought back up
1.191     harris41 10728: 
1.394     bowersj2 10729: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10730: for later delivery
1.191     harris41 10731: 
1.967     bisitz   10732: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10733: 
1.394     bowersj2 10734: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10735: that was requested
1.191     harris41 10736: 
1.243     albertel 10737: =back
1.191     harris41 10738: 
1.243     albertel 10739: =head1 PUBLIC SUBROUTINES
1.191     harris41 10740: 
1.243     albertel 10741: =head2 Session Environment Functions
1.191     harris41 10742: 
1.243     albertel 10743: =over 4
1.191     harris41 10744: 
1.394     bowersj2 10745: =item * 
                   10746: X<appenv()>
1.949     raeburn  10747: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10748: the user envirnoment file, and will be restored for each access this
1.620     albertel 10749: user makes during this session, also modifies the %env for the current
1.949     raeburn  10750: process. Optional rolesarrayref - if defined contains a reference to an array
                   10751: of roles which are exempt from the restriction on modifying user.role entries 
                   10752: in the user's environment.db and in %env.    
1.191     harris41 10753: 
                   10754: =item *
1.394     bowersj2 10755: X<delenv()>
1.987     raeburn  10756: B<delenv($delthis,$regexp)>: removes all items from the session
                   10757: environment file that begin with $delthis. If the 
                   10758: optional second arg - $regexp - is true, $delthis is treated as a 
                   10759: regular expression, otherwise \Q$delthis\E is used. 
                   10760: The values are also deleted from the current processes %env.
1.191     harris41 10761: 
1.795     albertel 10762: =item * get_env_multiple($name) 
                   10763: 
                   10764: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10765: values may be defined and end up as an array ref.
                   10766: 
                   10767: returns an array of values
                   10768: 
1.243     albertel 10769: =back
                   10770: 
                   10771: =head2 User Information
1.191     harris41 10772: 
1.243     albertel 10773: =over 4
1.191     harris41 10774: 
                   10775: =item *
1.394     bowersj2 10776: X<queryauthenticate()>
                   10777: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10778: authentication scheme
                   10779: 
                   10780: =item *
1.394     bowersj2 10781: X<authenticate()>
1.1073    raeburn  10782: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10783: authenticate user from domain's lib servers (first use the current
                   10784: one). C<$upass> should be the users password.
1.1073    raeburn  10785: $checkdefauth is optional (value is 1 if a check should be made to
                   10786:    authenticate user using default authentication method, and allow
                   10787:    account creation if username does not have account in the domain).
                   10788: $clientcancheckhost is optional (value is 1 if checking whether the
                   10789:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10790: 
                   10791: =item *
1.394     bowersj2 10792: X<homeserver()>
                   10793: B<homeserver($uname,$udom)>: find the server which has
                   10794: the user's directory and files (there must be only one), this caches
                   10795: the answer, and also caches if there is a borken connection.
1.191     harris41 10796: 
                   10797: =item *
1.394     bowersj2 10798: X<idget()>
                   10799: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10800: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10801: username, and only 1 username per ID in a specific domain) (returns
                   10802: hash: id=>name,id=>name)
1.191     harris41 10803: 
                   10804: =item *
1.394     bowersj2 10805: X<idrget()>
                   10806: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10807: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10808: 
                   10809: =item *
1.394     bowersj2 10810: X<idput()>
                   10811: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10812: 
                   10813: =item *
1.394     bowersj2 10814: X<rolesinit()>
                   10815: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10816: 
                   10817: =item *
1.551     albertel 10818: X<getsection()>
                   10819: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10820: course $cname, return section name/number or '' for "not in course"
                   10821: and '-1' for "no section"
                   10822: 
                   10823: =item *
1.394     bowersj2 10824: X<userenvironment()>
                   10825: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10826: passed in @what from the requested user's environment, returns a hash
                   10827: 
1.858     raeburn  10828: =item * 
                   10829: X<userlog_query()>
1.859     albertel 10830: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10831: activity.log file. %filters defines filters applied when parsing the
                   10832: log file. These can be start or end timestamps, or the type of action
                   10833: - log to look for Login or Logout events, check for Checkin or
                   10834: Checkout, role for role selection. The response is in the form
                   10835: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10836: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10837: 
1.243     albertel 10838: =back
                   10839: 
                   10840: =head2 User Roles
                   10841: 
                   10842: =over 4
                   10843: 
                   10844: =item *
                   10845: 
1.810     raeburn  10846: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10847:  F: full access
                   10848:  U,I,K: authentication modes (cxx only)
                   10849:  '': forbidden
                   10850:  1: user needs to choose course
                   10851:  2: browse allowed
1.766     albertel 10852:  A: passphrase authentication needed
1.243     albertel 10853: 
                   10854: =item *
                   10855: 
                   10856: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10857: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10858: and course level
                   10859: 
                   10860: =item *
                   10861: 
1.988     raeburn  10862: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10863: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10864: $type is Course (default) or Community.
1.988     raeburn  10865: If $forcedefault evaluates to true, text returned will be default 
                   10866: text for $type. Otherwise, if this is a course, the text returned 
                   10867: will be a custom name for the role (if defined in the course's 
                   10868: environment).  If no custom name is defined the default is returned.
                   10869:    
1.832     raeburn  10870: =item *
                   10871: 
1.935     raeburn  10872: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10873: All arguments are optional. Returns a hash of a roles, either for
                   10874: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10875: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10876: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10877: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10878: For each key, value is set to colon-separated start and end times for
                   10879: the role.  If no username and domain are specified, will default to
1.934     raeburn  10880: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10881: of role statuses (active, future or previous), roles 
                   10882: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10883: to restrict the list of roles reported. If no array ref is 
                   10884: provided for types, will default to return only active roles.
1.834     albertel 10885: 
1.243     albertel 10886: =back
                   10887: 
                   10888: =head2 User Modification
                   10889: 
                   10890: =over 4
                   10891: 
                   10892: =item *
                   10893: 
1.957     raeburn  10894: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10895: user for the level given by URL.  Optional start and end dates (leave empty
                   10896: string or zero for "no date")
1.191     harris41 10897: 
                   10898: =item *
                   10899: 
1.243     albertel 10900: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10901: change a users, password, possible return values are: ok,
                   10902: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10903: refused
1.191     harris41 10904: 
                   10905: =item *
                   10906: 
1.243     albertel 10907: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10908: 
                   10909: =item *
                   10910: 
1.1058    raeburn  10911: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10912:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10913: 
                   10914: will update user information (firstname,middlename,lastname,generation,
                   10915: permanentemail), and if forceid is true, student/employee ID also.
                   10916: A user's institutional affiliation(s) can also be updated.
                   10917: User information fields will not be overwritten with empty entries 
                   10918: unless the field is included in the $candelete array reference.
                   10919: This array is included when a single user is modified via "Manage Users",
                   10920: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10921: 
                   10922: =item *
                   10923: 
1.286     matthew  10924: modifystudent
                   10925: 
1.957     raeburn  10926: modify a student's enrollment and identification information.
1.286     matthew  10927: The course id is resolved based on the current users environment.  
                   10928: This means the envoking user must be a course coordinator or otherwise
                   10929: associated with a course.
                   10930: 
1.297     matthew  10931: This call is essentially a wrapper for lonnet::modifyuser and
                   10932: lonnet::modify_student_enrollment
1.286     matthew  10933: 
                   10934: Inputs: 
                   10935: 
                   10936: =over 4
                   10937: 
1.957     raeburn  10938: =item B<$udom> Student's loncapa domain
1.286     matthew  10939: 
1.957     raeburn  10940: =item B<$uname> Student's loncapa login name
1.286     matthew  10941: 
1.964     bisitz   10942: =item B<$uid> Student/Employee ID
1.286     matthew  10943: 
1.957     raeburn  10944: =item B<$umode> Student's authentication mode
1.286     matthew  10945: 
1.957     raeburn  10946: =item B<$upass> Student's password
1.286     matthew  10947: 
1.957     raeburn  10948: =item B<$first> Student's first name
1.286     matthew  10949: 
1.957     raeburn  10950: =item B<$middle> Student's middle name
1.286     matthew  10951: 
1.957     raeburn  10952: =item B<$last> Student's last name
1.286     matthew  10953: 
1.957     raeburn  10954: =item B<$gene> Student's generation
1.286     matthew  10955: 
1.957     raeburn  10956: =item B<$usec> Student's section in course
1.286     matthew  10957: 
                   10958: =item B<$end> Unix time of the roles expiration
                   10959: 
                   10960: =item B<$start> Unix time of the roles start date
                   10961: 
                   10962: =item B<$forceid> If defined, allow $uid to be changed
                   10963: 
                   10964: =item B<$desiredhome> server to use as home server for student
                   10965: 
1.957     raeburn  10966: =item B<$email> Student's permanent e-mail address
                   10967: 
                   10968: =item B<$type> Type of enrollment (auto or manual)
                   10969: 
1.963     raeburn  10970: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10971: 
                   10972: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10973: 
1.963     raeburn  10974: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10975: 
1.963     raeburn  10976: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10977: 
1.963     raeburn  10978: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10979: 
1.286     matthew  10980: =back
1.297     matthew  10981: 
                   10982: =item *
                   10983: 
                   10984: modify_student_enrollment
                   10985: 
                   10986: Change a students enrollment status in a class.  The environment variable
                   10987: 'role.request.course' must be defined for this function to proceed.
                   10988: 
                   10989: Inputs:
                   10990: 
                   10991: =over 4
                   10992: 
                   10993: =item $udom, students domain
                   10994: 
                   10995: =item $uname, students name
                   10996: 
                   10997: =item $uid, students user id
                   10998: 
                   10999: =item $first, students first name
                   11000: 
                   11001: =item $middle
                   11002: 
                   11003: =item $last
                   11004: 
                   11005: =item $gene
                   11006: 
                   11007: =item $usec
                   11008: 
                   11009: =item $end
                   11010: 
                   11011: =item $start
                   11012: 
1.957     raeburn  11013: =item $type
                   11014: 
                   11015: =item $locktype
                   11016: 
                   11017: =item $cid
                   11018: 
                   11019: =item $selfenroll
                   11020: 
                   11021: =item $context
                   11022: 
1.297     matthew  11023: =back
                   11024: 
1.191     harris41 11025: 
                   11026: =item *
                   11027: 
1.243     albertel 11028: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11029: custom role; give a custom role to a user for the level given by URL.  Specify
                   11030: name and domain of role author, and role name
1.191     harris41 11031: 
                   11032: =item *
                   11033: 
1.243     albertel 11034: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11035: 
                   11036: =item *
                   11037: 
1.243     albertel 11038: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11039: 
                   11040: =back
                   11041: 
                   11042: =head2 Course Infomation
                   11043: 
                   11044: =over 4
1.191     harris41 11045: 
                   11046: =item *
                   11047: 
1.1118    foxr     11048: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11049: specified course id, including all environment settings for the
                   11050: course, the description of the course will be in the hash under the
                   11051: key 'description'
1.191     harris41 11052: 
1.1118    foxr     11053: $options is an optional parameter that if supplied is a hash reference that controls
                   11054: what how this function works.  It has the following key/values:
                   11055: 
                   11056: =over 4
                   11057: 
                   11058: =item freshen_cache
                   11059: 
                   11060: If defined, and the environment cache for the course is valid, it is 
                   11061: returned in the returned hash.
                   11062: 
                   11063: =item one_time
                   11064: 
                   11065: If defined, the last cache time is set to _now_
                   11066: 
                   11067: =item user
                   11068: 
                   11069: If defined, the supplied username is used instead of the current user.
                   11070: 
                   11071: 
                   11072: =back
                   11073: 
1.191     harris41 11074: =item *
                   11075: 
1.624     albertel 11076: resdata($name,$domain,$type,@which) : request for current parameter
                   11077: setting for a specific $type, where $type is either 'course' or 'user',
                   11078: @what should be a list of parameters to ask about. This routine caches
                   11079: answers for 5 minutes.
1.243     albertel 11080: 
1.877     foxr     11081: =item *
                   11082: 
                   11083: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11084: data base, returning a hash that is keyed by the resource name and has
                   11085: values that are the resource value.  I believe that the timestamps and
                   11086: versions are also returned.
                   11087: 
                   11088: 
1.243     albertel 11089: =back
                   11090: 
                   11091: =head2 Course Modification
                   11092: 
                   11093: =over 4
1.191     harris41 11094: 
                   11095: =item *
                   11096: 
1.243     albertel 11097: writecoursepref($courseid,%prefs) : write preferences (environment
                   11098: database) for a course
1.191     harris41 11099: 
                   11100: =item *
                   11101: 
1.1011    raeburn  11102: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11103: 
                   11104: =item *
                   11105: 
1.1038    raeburn  11106: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11107: 
                   11108: =back
                   11109: 
                   11110: =head2 Resource Subroutines
                   11111: 
                   11112: =over 4
1.191     harris41 11113: 
                   11114: =item *
                   11115: 
1.243     albertel 11116: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11117: 
                   11118: =item *
                   11119: 
1.243     albertel 11120: repcopy($filename) : subscribes to the requested file, and attempts to
                   11121: replicate from the owning library server, Might return
1.607     raeburn  11122: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11123: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11124: resource. Expects the local filesystem pathname
                   11125: (/home/httpd/html/res/....)
                   11126: 
                   11127: =back
                   11128: 
                   11129: =head2 Resource Information
                   11130: 
                   11131: =over 4
1.191     harris41 11132: 
                   11133: =item *
                   11134: 
1.243     albertel 11135: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11136: a vairety of different possible values, $varname should be a request
                   11137: string, and the other parameters can be used to specify who and what
                   11138: one is asking about.
                   11139: 
                   11140: Possible values for $varname are environment.lastname (or other item
                   11141: from the envirnment hash), user.name (or someother aspect about the
                   11142: user), resource.0.maxtries (or some other part and parameter of a
                   11143: resource)
1.204     albertel 11144: 
                   11145: =item *
                   11146: 
1.243     albertel 11147: directcondval($number) : get current value of a condition; reads from a state
                   11148: string
1.204     albertel 11149: 
                   11150: =item *
                   11151: 
1.243     albertel 11152: condval($condidx) : value of condition index based on state
1.204     albertel 11153: 
                   11154: =item *
                   11155: 
1.243     albertel 11156: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11157: resource's metadata, $what should be either a specific key, or either
                   11158: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11159: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11160: 
                   11161: this function automatically caches all requests
1.191     harris41 11162: 
                   11163: =item *
                   11164: 
1.243     albertel 11165: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11166: network of library servers; returns file handle of where SQL and regex results
                   11167: will be stored for query
1.191     harris41 11168: 
                   11169: =item *
                   11170: 
1.243     albertel 11171: symbread($filename) : return symbolic list entry (filename argument optional);
                   11172: returns the data handle
1.191     harris41 11173: 
                   11174: =item *
                   11175: 
1.243     albertel 11176: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11177: a possible symb for the URL in $thisfn, and if is an encryypted
                   11178: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11179: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11180: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11181: 
1.191     harris41 11182: 
                   11183: =item *
                   11184: 
1.243     albertel 11185: symbclean($symb) : removes versions numbers from a symb, returns the
                   11186: cleaned symb
1.191     harris41 11187: 
                   11188: =item *
                   11189: 
1.243     albertel 11190: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11191: course map, user must be in a course for it to work.
1.191     harris41 11192: 
                   11193: =item *
                   11194: 
1.243     albertel 11195: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11196: 
                   11197: =item *
                   11198: 
1.243     albertel 11199: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11200: a random seed, all arguments are optional, if they aren't sent it uses the
                   11201: environment to derive them. Note: if symb isn't sent and it can't get one
                   11202: from &symbread it will use the current time as its return value
1.191     harris41 11203: 
                   11204: =item *
                   11205: 
1.243     albertel 11206: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11207: unfakeable, receipt
1.191     harris41 11208: 
                   11209: =item *
                   11210: 
1.620     albertel 11211: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11212: 
                   11213: =item *
                   11214: 
1.243     albertel 11215: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11216: 
                   11217: =item *
                   11218: 
1.243     albertel 11219: 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 11220: 
                   11221: =item *
                   11222: 
1.243     albertel 11223: 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 11224: 
                   11225: =item *
                   11226: 
1.243     albertel 11227: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11228: 
                   11229: =item *
                   11230: 
1.243     albertel 11231: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11232: forcing spreadsheet to reevaluate the resource scores next time.
                   11233: 
                   11234: =back
                   11235: 
                   11236: =head2 Storing/Retreiving Data
                   11237: 
                   11238: =over 4
1.191     harris41 11239: 
                   11240: =item *
                   11241: 
1.243     albertel 11242: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11243: for this url; hashref needs to be given and should be a \%hashname; the
                   11244: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11245: be derived from the env
1.191     harris41 11246: 
                   11247: =item *
                   11248: 
1.243     albertel 11249: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11250: uses critical subroutine
1.191     harris41 11251: 
                   11252: =item *
                   11253: 
1.243     albertel 11254: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11255: all args are optional
1.191     harris41 11256: 
                   11257: =item *
                   11258: 
1.717     albertel 11259: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11260: dumps the complete (or key matching regexp) namespace into a hash
                   11261: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11262: normally &store()ed into
                   11263: 
                   11264: $range should be either an integer '100' (give me the first 100
                   11265:                                            matching records)
                   11266:               or be  two integers sperated by a - with no spaces
                   11267:                  '30-50' (give me the 30th through the 50th matching
                   11268:                           records)
                   11269: 
                   11270: 
                   11271: =item *
                   11272: 
                   11273: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11274: replaces a &store() version of data with a replacement set of data
                   11275: for a particular resource in a namespace passed in the $storehash hash 
                   11276: reference
                   11277: 
                   11278: =item *
                   11279: 
1.243     albertel 11280: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11281: works very similar to store/cstore, but all data is stored in a
                   11282: temporary location and can be reset using tmpreset, $storehash should
                   11283: be a hash reference, returns nothing on success
1.191     harris41 11284: 
                   11285: =item *
                   11286: 
1.243     albertel 11287: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11288: similar to restore, but all data is stored in a temporary location and
                   11289: can be reset using tmpreset. Returns a hash of values on success,
                   11290: error string otherwise.
1.191     harris41 11291: 
                   11292: =item *
                   11293: 
1.243     albertel 11294: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11295: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11296: 
                   11297: =item *
                   11298: 
1.243     albertel 11299: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11300: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11301: 
                   11302: =item *
                   11303: 
1.243     albertel 11304: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11305: namesp ($udom and $uname are optional)
1.191     harris41 11306: 
                   11307: =item *
                   11308: 
1.702     albertel 11309: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11310: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11311: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11312: 
1.702     albertel 11313: $range should be either an integer '100' (give me the first 100
                   11314:                                            matching records)
                   11315:               or be  two integers sperated by a - with no spaces
                   11316:                  '30-50' (give me the 30th through the 50th matching
                   11317:                           records)
1.449     matthew  11318: =item *
                   11319: 
                   11320: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11321: $store can be a scalar, an array reference, or if the amount to be 
                   11322: incremented is > 1, a hash reference.
                   11323: 
                   11324: ($udom and $uname are optional)
1.191     harris41 11325: 
                   11326: =item *
                   11327: 
1.243     albertel 11328: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11329: ($udom and $uname are optional)
1.191     harris41 11330: 
                   11331: =item *
                   11332: 
1.243     albertel 11333: cput($namespace,$storehash,$udom,$uname) : critical put
                   11334: ($udom and $uname are optional)
1.191     harris41 11335: 
                   11336: =item *
                   11337: 
1.748     albertel 11338: newput($namespace,$storehash,$udom,$uname) :
                   11339: 
                   11340: Attempts to store the items in the $storehash, but only if they don't
                   11341: currently exist, if this succeeds you can be certain that you have 
                   11342: successfully created a new key value pair in the $namespace db.
                   11343: 
                   11344: 
                   11345: Args:
                   11346:  $namespace: name of database to store values to
                   11347:  $storehash: hashref to store to the db
                   11348:  $udom: (optional) domain of user containing the db
                   11349:  $uname: (optional) name of user caontaining the db
                   11350: 
                   11351: Returns:
                   11352:  'ok' -> succeeded in storing all keys of $storehash
                   11353:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11354:                         least <key> already existed in the db (other
                   11355:                         requested keys may also already exist)
1.967     bisitz   11356:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11357:  'con_lost' -> unable to contact request server
                   11358:  'refused' -> action was not allowed by remote machine
                   11359: 
                   11360: 
                   11361: =item *
                   11362: 
1.243     albertel 11363: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11364: reference filled in from namesp (encrypts the return communication)
                   11365: ($udom and $uname are optional)
1.191     harris41 11366: 
                   11367: =item *
                   11368: 
1.243     albertel 11369: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11370: critical subroutine
                   11371: 
1.806     raeburn  11372: =item *
                   11373: 
1.860     raeburn  11374: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11375: array reference filled in from namespace found in domain level on either
                   11376: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11377: 
                   11378: =item *
                   11379: 
1.860     raeburn  11380: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11381: domain level either on specified domain server ($uhome) or primary domain 
                   11382: server ($udom and $uhome are optional)
1.806     raeburn  11383: 
1.943     raeburn  11384: =item * 
                   11385: 
                   11386: get_domain_defaults($target_domain) : returns hash with defaults for
                   11387: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11388: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11389: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11390: Values are retrieved from cache (if current), or from domain's configuration.db
                   11391: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11392: or lonTabs/domain.tab. 
                   11393: 
                   11394: %domdefaults = &get_auth_defaults($target_domain);
                   11395: 
1.243     albertel 11396: =back
                   11397: 
                   11398: =head2 Network Status Functions
                   11399: 
                   11400: =over 4
1.191     harris41 11401: 
                   11402: =item *
                   11403: 
                   11404: dirlist($uri) : return directory list based on URI
                   11405: 
                   11406: =item *
                   11407: 
1.243     albertel 11408: spareserver() : find server with least workload from spare.tab
                   11409: 
1.986     foxr     11410: 
                   11411: =item *
                   11412: 
                   11413: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11414: if there is no corresponding loncapa host.
                   11415: 
1.243     albertel 11416: =back
                   11417: 
1.986     foxr     11418: 
1.243     albertel 11419: =head2 Apache Request
                   11420: 
                   11421: =over 4
1.191     harris41 11422: 
                   11423: =item *
                   11424: 
1.243     albertel 11425: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11426: localhost, posts hash
                   11427: 
                   11428: =back
                   11429: 
                   11430: =head2 Data to String to Data
                   11431: 
                   11432: =over 4
1.191     harris41 11433: 
                   11434: =item *
                   11435: 
1.243     albertel 11436: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11437: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11438: 
                   11439: =item *
                   11440: 
1.243     albertel 11441: hashref2str($hashref) : convert a hashref into a string complete with
                   11442: escaping and '=' and '&' separators, supports elements that are
                   11443: arrayrefs and hashrefs
1.191     harris41 11444: 
                   11445: =item *
                   11446: 
1.243     albertel 11447: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11448: with escaping and '&' separators, supports elements that are arrayrefs
                   11449: and hashrefs
1.191     harris41 11450: 
                   11451: =item *
                   11452: 
1.243     albertel 11453: str2hash($string) : convert string to hash using unescaping and
                   11454: splitting on '=' and '&', supports elements that are arrayrefs and
                   11455: hashrefs
1.191     harris41 11456: 
                   11457: =item *
                   11458: 
1.243     albertel 11459: str2array($string) : convert string to hash using unescaping and
                   11460: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11461: 
                   11462: =back
                   11463: 
                   11464: =head2 Logging Routines
                   11465: 
                   11466: 
                   11467: These routines allow one to make log messages in the lonnet.log and
                   11468: lonnet.perm logfiles.
1.191     harris41 11469: 
1.1119  ! foxr     11470: =over 4
        !          11471: 
1.191     harris41 11472: =item *
                   11473: 
1.243     albertel 11474: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11475: 
                   11476: =item *
                   11477: 
1.243     albertel 11478: logthis() : append message to the normal lonnet.log file, it gets
                   11479: preiodically rolled over and deleted.
1.191     harris41 11480: 
                   11481: =item *
                   11482: 
1.243     albertel 11483: logperm() : append a permanent message to lonnet.perm.log, this log
                   11484: file never gets deleted by any automated portion of the system, only
                   11485: messages of critical importance should go in here.
                   11486: 
1.1119  ! foxr     11487: 
1.243     albertel 11488: =back
                   11489: 
                   11490: =head2 General File Helper Routines
                   11491: 
                   11492: =over 4
1.191     harris41 11493: 
                   11494: =item *
                   11495: 
1.481     raeburn  11496: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11497: (a) files in /uploaded
                   11498:   (i) If a local copy of the file exists - 
                   11499:       compares modification date of local copy with last-modified date for 
                   11500:       definitive version stored on home server for course. If local copy is 
                   11501:       stale, requests a new version from the home server and stores it. 
                   11502:       If the original has been removed from the home server, then local copy 
                   11503:       is unlinked.
                   11504:   (ii) If local copy does not exist -
                   11505:       requests the file from the home server and stores it. 
                   11506:   
                   11507:   If $caller is 'uploadrep':  
                   11508:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11509:     for request for files originally uploaded via DOCS. 
                   11510:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11511:   
                   11512:   Otherwise:
                   11513:      This indicates a call from the content generation phase of the request.
                   11514:      -  returns the entire contents of the file or -1.
                   11515:      
                   11516: (b) files in /res
                   11517:    - returns the entire contents of a file or -1; 
                   11518:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11519: 
1.712     albertel 11520: 
                   11521: =item *
                   11522: 
                   11523: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11524:                   reference
                   11525: 
                   11526: returns either a stat() list of data about the file or an empty list
                   11527: if the file doesn't exist or couldn't find out about it (connection
                   11528: problems or user unknown)
                   11529: 
1.191     harris41 11530: =item *
                   11531: 
1.243     albertel 11532: filelocation($dir,$file) : returns file system location of a file
                   11533: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11534: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11535: and a file of ../bob will become /a/bob)
1.191     harris41 11536: 
                   11537: =item *
                   11538: 
                   11539: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11540: filelocation except for hrefs
                   11541: 
                   11542: =item *
                   11543: 
                   11544: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11545: 
1.243     albertel 11546: =back
                   11547: 
1.608     albertel 11548: =head2 Usererfile file routines (/uploaded*)
                   11549: 
                   11550: =over 4
                   11551: 
                   11552: =item *
                   11553: 
                   11554: userfileupload(): main rotine for putting a file in a user or course's
                   11555:                   filespace, arguments are,
                   11556: 
1.620     albertel 11557:  formname - required - this is the name of the element in $env where the
1.608     albertel 11558:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11559:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11560:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11561:  context - if coursedoc, store the file in the course of the active role
                   11562:              of the current user; 
                   11563:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11564:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11565:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11566:          if undefined, it will be placed in "unknown"
                   11567: 
                   11568:  (This routine calls clean_filename() to remove any dangerous
                   11569:  characters from the filename, and then calls finuserfileupload() to
                   11570:  complete the transaction)
                   11571: 
                   11572:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11573:  and /adm/notfound.html if unsuccessful
                   11574: 
                   11575: =item *
                   11576: 
                   11577: clean_filename(): routine for cleaing a filename up for storage in
                   11578:                  userfile space, argument is:
                   11579: 
                   11580:  filename - proposed filename
                   11581: 
                   11582: returns: the new clean filename
                   11583: 
                   11584: =item *
                   11585: 
1.1090    raeburn  11586: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11587: userspace, probably shouldn't be called directly
                   11588: 
                   11589:   docuname: username or courseid of destination for the file
                   11590:   docudom: domain of user/course of destination for the file
                   11591:   formname: same as for userfileupload()
1.1090    raeburn  11592:   fname: filename (including subdirectories) for the file
                   11593:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11594:   allfiles: reference to hash used to store objects found by parser
                   11595:   codebase: reference to hash used for codebases of java objects found by parser
                   11596:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11597:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11598:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11599:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11600:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11601:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11602:   mimetype: reference to scalar to accommodate mime type determined
                   11603:             from File::MMagic if $parser = parse.
1.608     albertel 11604: 
                   11605:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11606:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11607:  was 'overwrite').
                   11608:  
1.608     albertel 11609: 
                   11610: =item *
                   11611: 
                   11612: renameuserfile(): renames an existing userfile to a new name
                   11613: 
                   11614:   Args:
                   11615:    docuname: username or courseid of destination for the file
                   11616:    docudom: domain of user/course of destination for the file
                   11617:    old: current file name (including any subdirs under userfiles)
                   11618:    new: desired file name (including any subdirs under userfiles)
                   11619: 
                   11620: =item *
                   11621: 
                   11622: mkdiruserfile(): creates a directory is a userfiles dir
                   11623: 
                   11624:   Args:
                   11625:    docuname: username or courseid of destination for the file
                   11626:    docudom: domain of user/course of destination for the file
                   11627:    dir: dir to create (including any subdirs under userfiles)
                   11628: 
                   11629: =item *
                   11630: 
                   11631: removeuserfile(): removes a file that exists in userfiles
                   11632: 
                   11633:   Args:
                   11634:    docuname: username or courseid of destination for the file
                   11635:    docudom: domain of user/course of destination for the file
                   11636:    fname: filname to delete (including any subdirs under userfiles)
                   11637: 
                   11638: =item *
                   11639: 
                   11640: removeuploadedurl(): convience function for removeuserfile()
                   11641: 
                   11642:   Args:
                   11643:    url:  a full /uploaded/... url to delete
                   11644: 
1.747     albertel 11645: =item * 
                   11646: 
                   11647: get_portfile_permissions():
                   11648:   Args:
                   11649:     domain: domain of user or course contain the portfolio files
                   11650:     user: name of user or num of course contain the portfolio files
                   11651:   Returns:
                   11652:     hashref of a dump of the proper file_permissions.db
                   11653:    
                   11654: 
                   11655: =item * 
                   11656: 
                   11657: get_access_controls():
                   11658: 
                   11659: Args:
                   11660:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11661:   group: (optional) the group you want the files associated with
                   11662:   file: (optional) the file you want access info on
                   11663: 
                   11664: Returns:
1.749     raeburn  11665:     a hash (keys are file names) of hashes containing
                   11666:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11667:         values are XML containing access control settings (see below) 
1.747     albertel 11668: 
                   11669: Internal notes:
                   11670: 
1.749     raeburn  11671:  access controls are stored in file_permissions.db as key=value pairs.
                   11672:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11673:         where scope -> public,guest,course,group,domains or users.
                   11674:               end -> UNIX time for end of access (0 -> no end date)
                   11675:               start -> UNIX time for start of access
                   11676: 
                   11677:     value -> XML description of access control
                   11678:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11679:             <start></start>
                   11680:             <end></end>
                   11681: 
                   11682:             <password></password>  for scope type = guest
                   11683: 
                   11684:             <domain></domain>     for scope type = course or group
                   11685:             <number></number>
                   11686:             <roles id="">
                   11687:              <role></role>
                   11688:              <access></access>
                   11689:              <section></section>
                   11690:              <group></group>
                   11691:             </roles>
                   11692: 
                   11693:             <dom></dom>         for scope type = domains
                   11694: 
                   11695:             <users>             for scope type = users
                   11696:              <user>
                   11697:               <uname></uname>
                   11698:               <udom></udom>
                   11699:              </user>
                   11700:             </users>
                   11701:            </scope> 
                   11702:               
                   11703:  Access data is also aggregated for each file in an additional key=value pair:
                   11704:  key -> path to file/file_name\0accesscontrol 
                   11705:  value -> reference to hash
                   11706:           hash contains key = value pairs
                   11707:           where key = uniqueID:scope_end_start
                   11708:                 value = UNIX time record was last updated
                   11709: 
                   11710:           Used to improve speed of look-ups of access controls for each file.  
                   11711:  
                   11712:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11713: 
                   11714: modify_access_controls():
                   11715: 
                   11716: Modifies access controls for a portfolio file
                   11717: Args
                   11718: 1. file name
                   11719: 2. reference to hash of required changes,
                   11720: 3. domain
                   11721: 4. username
                   11722:   where domain,username are the domain of the portfolio owner 
                   11723:   (either a user or a course) 
                   11724: 
                   11725: Returns:
                   11726: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11727: 2. result of deletions ('ok' or 'error', with error message).
                   11728: 3. reference to hash of any new or updated access controls.
                   11729: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11730:    key = integer (inbound ID)
                   11731:    value = uniqueID  
1.747     albertel 11732: 
1.608     albertel 11733: =back
                   11734: 
1.243     albertel 11735: =head2 HTTP Helper Routines
                   11736: 
                   11737: =over 4
                   11738: 
1.191     harris41 11739: =item *
                   11740: 
                   11741: escape() : unpack non-word characters into CGI-compatible hex codes
                   11742: 
                   11743: =item *
                   11744: 
                   11745: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11746: 
1.243     albertel 11747: =back
                   11748: 
                   11749: =head1 PRIVATE SUBROUTINES
                   11750: 
                   11751: =head2 Underlying communication routines (Shouldn't call)
                   11752: 
                   11753: =over 4
                   11754: 
                   11755: =item *
                   11756: 
                   11757: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11758: 
                   11759: =item *
                   11760: 
                   11761: reply() : uses subreply to send a message to remote machine, logs all failures
                   11762: 
                   11763: =item *
                   11764: 
                   11765: critical() : passes a critical message to another server; if cannot
                   11766: get through then place message in connection buffer directory and
                   11767: returns con_delayed, if incapable of saving message, returns
                   11768: con_failed
                   11769: 
                   11770: =item *
                   11771: 
                   11772: reconlonc() : tries to reconnect lonc client processes.
                   11773: 
                   11774: =back
                   11775: 
                   11776: =head2 Resource Access Logging
                   11777: 
                   11778: =over 4
                   11779: 
                   11780: =item *
                   11781: 
                   11782: flushcourselogs() : flush (save) buffer logs and access logs
                   11783: 
                   11784: =item *
                   11785: 
                   11786: courselog($what) : save message for course in hash
                   11787: 
                   11788: =item *
                   11789: 
                   11790: courseacclog($what) : save message for course using &courselog().  Perform
                   11791: special processing for specific resource types (problems, exams, quizzes, etc).
                   11792: 
1.191     harris41 11793: =item *
                   11794: 
                   11795: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11796: as a PerlChildExitHandler
1.243     albertel 11797: 
                   11798: =back
                   11799: 
                   11800: =head2 Other
                   11801: 
                   11802: =over 4
                   11803: 
                   11804: =item *
                   11805: 
                   11806: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11807: 
                   11808: =back
                   11809: 
                   11810: =cut
1.877     foxr     11811: 

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